ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl → 0.3.0.dev20240926__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- ai_edge_torch/__init__.py +5 -4
- ai_edge_torch/_convert/conversion.py +112 -0
- ai_edge_torch/_convert/conversion_utils.py +64 -0
- ai_edge_torch/{convert → _convert}/converter.py +94 -48
- ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
- ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
- ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
- ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
- ai_edge_torch/_convert/signature.py +66 -0
- ai_edge_torch/_convert/test/test_convert.py +495 -0
- ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
- ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
- ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
- ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
- ai_edge_torch/config.py +27 -0
- ai_edge_torch/conftest.py +20 -0
- ai_edge_torch/debug/culprit.py +72 -40
- ai_edge_torch/debug/test/test_culprit.py +7 -5
- ai_edge_torch/debug/test/test_search_model.py +8 -7
- ai_edge_torch/debug/utils.py +14 -3
- ai_edge_torch/fx_pass_base.py +101 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
- ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
- ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
- ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
- ai_edge_torch/generative/examples/openelm/verify.py +64 -0
- ai_edge_torch/generative/examples/phi/__init__.py +14 -0
- ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
- ai_edge_torch/generative/examples/phi/phi3.py +286 -0
- ai_edge_torch/generative/examples/phi/verify.py +65 -0
- ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
- ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
- ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
- ai_edge_torch/generative/examples/smollm/verify.py +62 -0
- ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
- ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
- ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
- ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
- ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
- ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
- ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
- ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
- ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
- ai_edge_torch/generative/examples/t5/t5.py +208 -159
- ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
- ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
- ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
- ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
- ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
- ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
- ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
- ai_edge_torch/generative/fx_passes/__init__.py +4 -5
- ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
- ai_edge_torch/generative/layers/attention.py +141 -102
- ai_edge_torch/generative/layers/attention_utils.py +53 -12
- ai_edge_torch/generative/layers/builder.py +37 -7
- ai_edge_torch/generative/layers/feed_forward.py +39 -14
- ai_edge_torch/generative/layers/kv_cache.py +162 -50
- ai_edge_torch/generative/layers/model_config.py +84 -30
- ai_edge_torch/generative/layers/normalization.py +185 -7
- ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
- ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
- ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
- ai_edge_torch/generative/layers/unet/builder.py +7 -4
- ai_edge_torch/generative/layers/unet/model_config.py +17 -15
- ai_edge_torch/generative/quantize/example.py +7 -8
- ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
- ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
- ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
- ai_edge_torch/generative/test/test_kv_cache.py +120 -0
- ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
- ai_edge_torch/generative/test/test_model_conversion.py +124 -188
- ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
- ai_edge_torch/generative/test/test_quantize.py +76 -60
- ai_edge_torch/generative/test/utils.py +54 -0
- ai_edge_torch/generative/utilities/converter.py +82 -0
- ai_edge_torch/generative/utilities/loader.py +120 -57
- ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
- ai_edge_torch/generative/utilities/t5_loader.py +110 -81
- ai_edge_torch/generative/utilities/verifier.py +247 -0
- ai_edge_torch/hlfb/__init__.py +1 -1
- ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
- ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
- ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
- ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
- ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
- ai_edge_torch/lowertools/__init__.py +18 -0
- ai_edge_torch/lowertools/_shim.py +80 -0
- ai_edge_torch/lowertools/common_utils.py +142 -0
- ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
- ai_edge_torch/lowertools/test_utils.py +60 -0
- ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
- ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
- ai_edge_torch/model.py +53 -18
- ai_edge_torch/odml_torch/__init__.py +20 -0
- ai_edge_torch/odml_torch/_torch_future.py +61 -0
- ai_edge_torch/odml_torch/_torch_library.py +19 -0
- ai_edge_torch/odml_torch/composite/__init__.py +16 -0
- ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
- ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
- ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
- ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
- ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
- ai_edge_torch/odml_torch/export.py +357 -0
- ai_edge_torch/odml_torch/export_utils.py +168 -0
- ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
- ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
- ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
- ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
- ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
- ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
- ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
- ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
- ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
- ai_edge_torch/odml_torch/lowerings/context.py +42 -0
- ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
- ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
- ai_edge_torch/odml_torch/passes/__init__.py +38 -0
- ai_edge_torch/odml_torch/tf_integration.py +194 -0
- ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
- ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
- ai_edge_torch/quantize/quant_config.py +13 -9
- ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
- ai_edge_torch/version.py +16 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
- ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
- ai_edge_torch/convert/conversion.py +0 -117
- ai_edge_torch/convert/conversion_utils.py +0 -400
- ai_edge_torch/convert/fx_passes/__init__.py +0 -59
- ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
- ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
- ai_edge_torch/convert/test/test_convert.py +0 -311
- ai_edge_torch/convert/test/test_convert_composites.py +0 -192
- ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
- ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
- ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
- ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
- ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
- ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
- /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
- /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
- /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/top_level.txt +0 -0
@@ -13,10 +13,7 @@
|
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
15
|
|
16
|
-
from typing import List, Optional, Tuple
|
17
|
-
|
18
|
-
import torch
|
19
|
-
from torch import nn
|
16
|
+
from typing import List, Optional, Tuple, Union
|
20
17
|
|
21
18
|
from ai_edge_torch.generative.layers.attention import CrossAttention
|
22
19
|
from ai_edge_torch.generative.layers.attention import SelfAttention
|
@@ -24,6 +21,8 @@ import ai_edge_torch.generative.layers.builder as layers_builder
|
|
24
21
|
import ai_edge_torch.generative.layers.model_config as layers_cfg
|
25
22
|
import ai_edge_torch.generative.layers.unet.builder as unet_builder
|
26
23
|
import ai_edge_torch.generative.layers.unet.model_config as unet_cfg
|
24
|
+
import torch
|
25
|
+
from torch import nn
|
27
26
|
|
28
27
|
|
29
28
|
class ResidualBlock2D(nn.Module):
|
@@ -41,26 +40,38 @@ class ResidualBlock2D(nn.Module):
|
|
41
40
|
config.in_channels, config.normalization_config
|
42
41
|
)
|
43
42
|
self.conv_1 = nn.Conv2d(
|
44
|
-
config.in_channels,
|
43
|
+
config.in_channels,
|
44
|
+
config.hidden_channels,
|
45
|
+
kernel_size=3,
|
46
|
+
stride=1,
|
47
|
+
padding=1,
|
45
48
|
)
|
46
49
|
if config.time_embedding_channels is not None:
|
47
50
|
self.time_emb_proj = nn.Linear(
|
48
|
-
config.time_embedding_channels, config.
|
51
|
+
config.time_embedding_channels, config.hidden_channels
|
49
52
|
)
|
50
53
|
else:
|
51
54
|
self.time_emb_proj = None
|
52
55
|
self.norm_2 = layers_builder.build_norm(
|
53
|
-
config.
|
56
|
+
config.hidden_channels, config.normalization_config
|
54
57
|
)
|
55
58
|
self.conv_2 = nn.Conv2d(
|
56
|
-
config.
|
59
|
+
config.hidden_channels,
|
60
|
+
config.out_channels,
|
61
|
+
kernel_size=3,
|
62
|
+
stride=1,
|
63
|
+
padding=1,
|
57
64
|
)
|
58
65
|
self.act_fn = layers_builder.get_activation(config.activation_config)
|
59
66
|
if config.in_channels == config.out_channels:
|
60
67
|
self.residual_layer = nn.Identity()
|
61
68
|
else:
|
62
69
|
self.residual_layer = nn.Conv2d(
|
63
|
-
config.in_channels,
|
70
|
+
config.in_channels,
|
71
|
+
config.out_channels,
|
72
|
+
kernel_size=1,
|
73
|
+
stride=1,
|
74
|
+
padding=0,
|
64
75
|
)
|
65
76
|
|
66
77
|
def forward(
|
@@ -94,7 +105,6 @@ class AttentionBlock2D(nn.Module):
|
|
94
105
|
"""2D self attention block
|
95
106
|
|
96
107
|
x = SelfAttention(Norm(input_tensor)) + x
|
97
|
-
|
98
108
|
"""
|
99
109
|
|
100
110
|
def __init__(self, config: unet_cfg.AttentionBlock2DConfig):
|
@@ -105,12 +115,13 @@ class AttentionBlock2D(nn.Module):
|
|
105
115
|
"""
|
106
116
|
super().__init__()
|
107
117
|
self.config = config
|
108
|
-
self.norm = layers_builder.build_norm(
|
118
|
+
self.norm = layers_builder.build_norm(
|
119
|
+
config.dim, config.normalization_config
|
120
|
+
)
|
109
121
|
self.attention = SelfAttention(
|
110
122
|
config.attention_batch_size,
|
111
123
|
config.dim,
|
112
124
|
config.attention_config,
|
113
|
-
0,
|
114
125
|
enable_hlfb=config.enable_hlfb,
|
115
126
|
)
|
116
127
|
|
@@ -125,20 +136,23 @@ class AttentionBlock2D(nn.Module):
|
|
125
136
|
"""
|
126
137
|
residual = input_tensor
|
127
138
|
B, C, H, W = input_tensor.shape
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
139
|
+
if (
|
140
|
+
self.config.normalization_config.type
|
141
|
+
== layers_cfg.NormalizationType.GROUP_NORM
|
142
|
+
):
|
143
|
+
x = self.norm(input_tensor)
|
144
|
+
x = x.view(B, C, H * W)
|
132
145
|
x = x.transpose(-1, -2)
|
133
146
|
else:
|
134
|
-
x =
|
135
|
-
x = x.transpose(-1, -2)
|
147
|
+
x = torch.permute(input_tensor, (0, 2, 3, 1))
|
136
148
|
x = self.norm(x)
|
149
|
+
x = x.view(B, H * W, C)
|
137
150
|
x = x.contiguous() # Prevent BATCH_MATMUL op in converted tflite.
|
138
151
|
x = self.attention(x)
|
139
|
-
x = x.
|
140
|
-
|
152
|
+
x = x.view(B, H, W, C)
|
153
|
+
residual = torch.permute(residual, (0, 2, 3, 1))
|
141
154
|
x = x + residual
|
155
|
+
x = torch.permute(x, (0, 3, 1, 2))
|
142
156
|
return x
|
143
157
|
|
144
158
|
|
@@ -146,24 +160,27 @@ class CrossAttentionBlock2D(nn.Module):
|
|
146
160
|
"""2D cross attention block
|
147
161
|
|
148
162
|
x = CrossAttention(Norm(input_tensor), context) + x
|
149
|
-
|
150
163
|
"""
|
151
164
|
|
152
165
|
def __init__(self, config: unet_cfg.CrossAttentionBlock2DConfig):
|
153
166
|
"""Initialize an instance of the AttentionBlock2D.
|
154
167
|
|
155
168
|
Args:
|
156
|
-
config (unet_cfg.CrossAttentionBlock2DConfig): the configuration of this
|
169
|
+
config (unet_cfg.CrossAttentionBlock2DConfig): the configuration of this
|
170
|
+
block.
|
157
171
|
"""
|
158
172
|
super().__init__()
|
159
173
|
self.config = config
|
160
|
-
self.norm = layers_builder.build_norm(
|
174
|
+
self.norm = layers_builder.build_norm(
|
175
|
+
config.query_dim, config.normalization_config
|
176
|
+
)
|
161
177
|
self.attention = CrossAttention(
|
162
178
|
config.attention_batch_size,
|
163
179
|
config.query_dim,
|
164
180
|
config.cross_dim,
|
181
|
+
config.hidden_dim,
|
182
|
+
config.output_dim,
|
165
183
|
config.attention_config,
|
166
|
-
0,
|
167
184
|
enable_hlfb=config.enable_hlfb,
|
168
185
|
)
|
169
186
|
|
@@ -174,26 +191,30 @@ class CrossAttentionBlock2D(nn.Module):
|
|
174
191
|
|
175
192
|
Args:
|
176
193
|
input_tensor (torch.Tensor): the input tensor.
|
177
|
-
context_tensor (torch.Tensor): the context tensor to apply cross attention
|
194
|
+
context_tensor (torch.Tensor): the context tensor to apply cross attention
|
195
|
+
on.
|
178
196
|
|
179
197
|
Returns:
|
180
198
|
output activation tensor after cross attention.
|
181
199
|
"""
|
182
200
|
residual = input_tensor
|
183
201
|
B, C, H, W = input_tensor.shape
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
202
|
+
if (
|
203
|
+
self.config.normalization_config.type
|
204
|
+
== layers_cfg.NormalizationType.GROUP_NORM
|
205
|
+
):
|
206
|
+
x = self.norm(input_tensor)
|
207
|
+
x = x.view(B, C, H * W)
|
188
208
|
x = x.transpose(-1, -2)
|
189
209
|
else:
|
190
|
-
x =
|
191
|
-
x = x.transpose(-1, -2)
|
210
|
+
x = torch.permute(input_tensor, (0, 2, 3, 1))
|
192
211
|
x = self.norm(x)
|
212
|
+
x = x.view(B, H * W, C)
|
193
213
|
x = self.attention(x, context_tensor)
|
194
|
-
x = x.
|
195
|
-
|
214
|
+
x = x.view(B, H, W, C)
|
215
|
+
residual = torch.permute(residual, (0, 2, 3, 1))
|
196
216
|
x = x + residual
|
217
|
+
x = torch.permute(x, (0, 3, 1, 2))
|
197
218
|
return x
|
198
219
|
|
199
220
|
|
@@ -201,7 +222,6 @@ class FeedForwardBlock2D(nn.Module):
|
|
201
222
|
"""2D feed forward block
|
202
223
|
|
203
224
|
x = w2(Activation(w1(Norm(x)))) + x
|
204
|
-
|
205
225
|
"""
|
206
226
|
|
207
227
|
def __init__(
|
@@ -211,7 +231,9 @@ class FeedForwardBlock2D(nn.Module):
|
|
211
231
|
super().__init__()
|
212
232
|
self.config = config
|
213
233
|
self.act = layers_builder.get_activation(config.activation_config)
|
214
|
-
self.norm = layers_builder.build_norm(
|
234
|
+
self.norm = layers_builder.build_norm(
|
235
|
+
config.dim, config.normalization_config
|
236
|
+
)
|
215
237
|
if config.activation_config.type == layers_cfg.ActivationType.GE_GLU:
|
216
238
|
self.w1 = nn.Identity()
|
217
239
|
self.w2 = nn.Linear(config.hidden_dim, config.dim)
|
@@ -222,23 +244,25 @@ class FeedForwardBlock2D(nn.Module):
|
|
222
244
|
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
|
223
245
|
residual = input_tensor
|
224
246
|
B, C, H, W = input_tensor.shape
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
|
247
|
+
if (
|
248
|
+
self.config.normalization_config.type
|
249
|
+
== layers_cfg.NormalizationType.GROUP_NORM
|
250
|
+
):
|
251
|
+
x = self.norm(input_tensor)
|
252
|
+
x = x.view(B, C, H * W)
|
229
253
|
x = x.transpose(-1, -2)
|
230
254
|
else:
|
231
|
-
x =
|
232
|
-
x = x.transpose(-1, -2)
|
255
|
+
x = torch.permute(input_tensor, (0, 2, 3, 1))
|
233
256
|
x = self.norm(x)
|
257
|
+
x = x.view(B, H * W, C)
|
234
258
|
x = self.w1(x)
|
235
259
|
x = self.act(x)
|
236
260
|
x = self.w2(x)
|
237
|
-
|
238
|
-
|
239
|
-
x = x
|
240
|
-
|
241
|
-
return x
|
261
|
+
x = x.view(B, H, W, C)
|
262
|
+
residual = torch.permute(residual, (0, 2, 3, 1))
|
263
|
+
x = x + residual
|
264
|
+
x = torch.permute(x, (0, 3, 1, 2))
|
265
|
+
return x
|
242
266
|
|
243
267
|
|
244
268
|
class TransformerBlock2D(nn.Module):
|
@@ -268,15 +292,14 @@ class TransformerBlock2D(nn.Module):
|
|
268
292
|
└─────────┬─────────┘
|
269
293
|
▼
|
270
294
|
hidden_states
|
271
|
-
|
272
|
-
|
273
295
|
"""
|
274
296
|
|
275
297
|
def __init__(self, config: unet_cfg.TransformerBlock2DConfig):
|
276
298
|
"""Initialize an instance of the TransformerBlock2D.
|
277
299
|
|
278
300
|
Args:
|
279
|
-
config (unet_cfg.TransformerBlock2Dconfig): the configuration of this
|
301
|
+
config (unet_cfg.TransformerBlock2Dconfig): the configuration of this
|
302
|
+
block.
|
280
303
|
"""
|
281
304
|
super().__init__()
|
282
305
|
self.config = config
|
@@ -290,7 +313,9 @@ class TransformerBlock2D(nn.Module):
|
|
290
313
|
padding=0,
|
291
314
|
)
|
292
315
|
self.self_attention = AttentionBlock2D(config.attention_block_config)
|
293
|
-
self.cross_attention = CrossAttentionBlock2D(
|
316
|
+
self.cross_attention = CrossAttentionBlock2D(
|
317
|
+
config.cross_attention_block_config
|
318
|
+
)
|
294
319
|
self.feed_forward = FeedForwardBlock2D(config.feed_forward_block_config)
|
295
320
|
self.conv_out = nn.Conv2d(
|
296
321
|
config.attention_block_config.dim,
|
@@ -304,7 +329,8 @@ class TransformerBlock2D(nn.Module):
|
|
304
329
|
|
305
330
|
Args:
|
306
331
|
input_tensor (torch.Tensor): the input tensor.
|
307
|
-
context_tensor (torch.Tensor): the context tensor to apply cross attention
|
332
|
+
context_tensor (torch.Tensor): the context tensor to apply cross attention
|
333
|
+
on.
|
308
334
|
|
309
335
|
Returns:
|
310
336
|
output activation tensor after transformer block.
|
@@ -352,7 +378,8 @@ class DownEncoderBlock2D(nn.Module):
|
|
352
378
|
"""Initialize an instance of the DownEncoderBlock2D.
|
353
379
|
|
354
380
|
Args:
|
355
|
-
config (unet_cfg.DownEncoderBlock2DConfig): the configuration of this
|
381
|
+
config (unet_cfg.DownEncoderBlock2DConfig): the configuration of this
|
382
|
+
block.
|
356
383
|
"""
|
357
384
|
super().__init__()
|
358
385
|
self.config = config
|
@@ -364,6 +391,7 @@ class DownEncoderBlock2D(nn.Module):
|
|
364
391
|
ResidualBlock2D(
|
365
392
|
unet_cfg.ResidualBlock2DConfig(
|
366
393
|
in_channels=input_channels,
|
394
|
+
hidden_channels=config.out_channels,
|
367
395
|
out_channels=config.out_channels,
|
368
396
|
time_embedding_channels=config.time_embedding_channels,
|
369
397
|
normalization_config=config.normalization_config,
|
@@ -374,7 +402,9 @@ class DownEncoderBlock2D(nn.Module):
|
|
374
402
|
if config.transformer_block_config:
|
375
403
|
transformers.append(TransformerBlock2D(config.transformer_block_config))
|
376
404
|
self.resnets = nn.ModuleList(resnets)
|
377
|
-
self.transformers =
|
405
|
+
self.transformers = (
|
406
|
+
nn.ModuleList(transformers) if len(transformers) > 0 else None
|
407
|
+
)
|
378
408
|
if config.add_downsample:
|
379
409
|
self.downsampler = unet_builder.build_downsampling(config.sampling_config)
|
380
410
|
else:
|
@@ -386,15 +416,18 @@ class DownEncoderBlock2D(nn.Module):
|
|
386
416
|
time_emb: Optional[torch.Tensor] = None,
|
387
417
|
context_tensor: Optional[torch.Tensor] = None,
|
388
418
|
output_hidden_states: bool = False,
|
389
|
-
) -> torch.Tensor
|
419
|
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
|
390
420
|
"""Forward function of the DownEncoderBlock2D.
|
391
421
|
|
392
422
|
Args:
|
393
423
|
input_tensor (torch.Tensor): the input tensor.
|
394
|
-
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
395
|
-
time embedding.
|
396
|
-
context_tensor (torch.Tensor): optional context tensor, if the block if
|
397
|
-
|
424
|
+
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
425
|
+
configured to accept time embedding.
|
426
|
+
context_tensor (torch.Tensor): optional context tensor, if the block if
|
427
|
+
configured to use transofrmer block.
|
428
|
+
output_hidden_states (bool): whether to output hidden states, usually for
|
429
|
+
skip connections.
|
430
|
+
|
398
431
|
Returns:
|
399
432
|
output hidden_states tensor after DownEncoderBlock2D.
|
400
433
|
"""
|
@@ -460,6 +493,7 @@ class UpDecoderBlock2D(nn.Module):
|
|
460
493
|
ResidualBlock2D(
|
461
494
|
unet_cfg.ResidualBlock2DConfig(
|
462
495
|
in_channels=input_channels,
|
496
|
+
hidden_channels=config.out_channels,
|
463
497
|
out_channels=config.out_channels,
|
464
498
|
time_embedding_channels=config.time_embedding_channels,
|
465
499
|
normalization_config=config.normalization_config,
|
@@ -470,12 +504,18 @@ class UpDecoderBlock2D(nn.Module):
|
|
470
504
|
if config.transformer_block_config:
|
471
505
|
transformers.append(TransformerBlock2D(config.transformer_block_config))
|
472
506
|
self.resnets = nn.ModuleList(resnets)
|
473
|
-
self.transformers =
|
507
|
+
self.transformers = (
|
508
|
+
nn.ModuleList(transformers) if len(transformers) > 0 else None
|
509
|
+
)
|
474
510
|
if config.add_upsample:
|
475
511
|
self.upsampler = unet_builder.build_upsampling(config.sampling_config)
|
476
512
|
if config.upsample_conv:
|
477
513
|
self.upsample_conv = nn.Conv2d(
|
478
|
-
config.out_channels,
|
514
|
+
config.out_channels,
|
515
|
+
config.out_channels,
|
516
|
+
kernel_size=3,
|
517
|
+
stride=1,
|
518
|
+
padding=1,
|
479
519
|
)
|
480
520
|
else:
|
481
521
|
self.upsampler = None
|
@@ -490,9 +530,10 @@ class UpDecoderBlock2D(nn.Module):
|
|
490
530
|
|
491
531
|
Args:
|
492
532
|
input_tensor (torch.Tensor): the input tensor.
|
493
|
-
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
494
|
-
time embedding.
|
495
|
-
context_tensor (torch.Tensor): optional context tensor, if the block if
|
533
|
+
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
534
|
+
configured to accept time embedding.
|
535
|
+
context_tensor (torch.Tensor): optional context tensor, if the block if
|
536
|
+
configured to use transofrmer block.
|
496
537
|
|
497
538
|
Returns:
|
498
539
|
output hidden_states tensor after UpDecoderBlock2D.
|
@@ -543,7 +584,8 @@ class SkipUpDecoderBlock2D(nn.Module):
|
|
543
584
|
"""Initialize an instance of the SkipUpDecoderBlock2D.
|
544
585
|
|
545
586
|
Args:
|
546
|
-
config (unet_cfg.SkipUpDecoderBlock2DConfig): the configuration of this
|
587
|
+
config (unet_cfg.SkipUpDecoderBlock2DConfig): the configuration of this
|
588
|
+
block.
|
547
589
|
"""
|
548
590
|
super().__init__()
|
549
591
|
self.config = config
|
@@ -551,13 +593,18 @@ class SkipUpDecoderBlock2D(nn.Module):
|
|
551
593
|
transformers = []
|
552
594
|
for i in range(config.num_layers):
|
553
595
|
res_skip_channels = (
|
554
|
-
config.in_channels
|
596
|
+
config.in_channels
|
597
|
+
if (i == config.num_layers - 1)
|
598
|
+
else config.out_channels
|
599
|
+
)
|
600
|
+
resnet_in_channels = (
|
601
|
+
config.prev_out_channels if i == 0 else config.out_channels
|
555
602
|
)
|
556
|
-
resnet_in_channels = config.prev_out_channels if i == 0 else config.out_channels
|
557
603
|
resnets.append(
|
558
604
|
ResidualBlock2D(
|
559
605
|
unet_cfg.ResidualBlock2DConfig(
|
560
606
|
in_channels=resnet_in_channels + res_skip_channels,
|
607
|
+
hidden_channels=config.out_channels,
|
561
608
|
out_channels=config.out_channels,
|
562
609
|
time_embedding_channels=config.time_embedding_channels,
|
563
610
|
normalization_config=config.normalization_config,
|
@@ -568,12 +615,18 @@ class SkipUpDecoderBlock2D(nn.Module):
|
|
568
615
|
if config.transformer_block_config:
|
569
616
|
transformers.append(TransformerBlock2D(config.transformer_block_config))
|
570
617
|
self.resnets = nn.ModuleList(resnets)
|
571
|
-
self.transformers =
|
618
|
+
self.transformers = (
|
619
|
+
nn.ModuleList(transformers) if len(transformers) > 0 else None
|
620
|
+
)
|
572
621
|
if config.add_upsample:
|
573
622
|
self.upsampler = unet_builder.build_upsampling(config.sampling_config)
|
574
623
|
if config.upsample_conv:
|
575
624
|
self.upsample_conv = nn.Conv2d(
|
576
|
-
config.out_channels,
|
625
|
+
config.out_channels,
|
626
|
+
config.out_channels,
|
627
|
+
kernel_size=3,
|
628
|
+
stride=1,
|
629
|
+
padding=1,
|
577
630
|
)
|
578
631
|
else:
|
579
632
|
self.upsampler = None
|
@@ -589,10 +642,12 @@ class SkipUpDecoderBlock2D(nn.Module):
|
|
589
642
|
|
590
643
|
Args:
|
591
644
|
input_tensor (torch.Tensor): the input tensor.
|
592
|
-
skip_connection_tensors (List[torch.Tensor]): the skip connection tensors
|
593
|
-
|
594
|
-
|
595
|
-
|
645
|
+
skip_connection_tensors (List[torch.Tensor]): the skip connection tensors
|
646
|
+
from encoder blocks.
|
647
|
+
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
648
|
+
configured to accept time embedding.
|
649
|
+
context_tensor (torch.Tensor): optional context tensor, if the block if
|
650
|
+
configured to use transofrmer block.
|
596
651
|
|
597
652
|
Returns:
|
598
653
|
output hidden_states tensor after SkipUpDecoderBlock2D.
|
@@ -654,6 +709,7 @@ class MidBlock2D(nn.Module):
|
|
654
709
|
ResidualBlock2D(
|
655
710
|
unet_cfg.ResidualBlock2DConfig(
|
656
711
|
in_channels=config.in_channels,
|
712
|
+
hidden_channels=config.in_channels,
|
657
713
|
out_channels=config.in_channels,
|
658
714
|
time_embedding_channels=config.time_embedding_channels,
|
659
715
|
normalization_config=config.normalization_config,
|
@@ -672,6 +728,7 @@ class MidBlock2D(nn.Module):
|
|
672
728
|
ResidualBlock2D(
|
673
729
|
unet_cfg.ResidualBlock2DConfig(
|
674
730
|
in_channels=config.in_channels,
|
731
|
+
hidden_channels=config.in_channels,
|
675
732
|
out_channels=config.in_channels,
|
676
733
|
time_embedding_channels=config.time_embedding_channels,
|
677
734
|
normalization_config=config.normalization_config,
|
@@ -681,7 +738,9 @@ class MidBlock2D(nn.Module):
|
|
681
738
|
)
|
682
739
|
self.resnets = nn.ModuleList(resnets)
|
683
740
|
self.attentions = nn.ModuleList(attentions) if len(attentions) > 0 else None
|
684
|
-
self.transformers =
|
741
|
+
self.transformers = (
|
742
|
+
nn.ModuleList(transformers) if len(transformers) > 0 else None
|
743
|
+
)
|
685
744
|
|
686
745
|
def forward(
|
687
746
|
self,
|
@@ -693,10 +752,10 @@ class MidBlock2D(nn.Module):
|
|
693
752
|
|
694
753
|
Args:
|
695
754
|
input_tensor (torch.Tensor): the input tensor.
|
696
|
-
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
697
|
-
time embedding.
|
698
|
-
context_tensor (torch.Tensor): optional context tensor, if the block if
|
699
|
-
transofrmer block.
|
755
|
+
time_emb (torch.Tensor): optional time embedding tensor, if the block is
|
756
|
+
configured to accept time embedding.
|
757
|
+
context_tensor (torch.Tensor): optional context tensor, if the block if
|
758
|
+
configured to use transofrmer block.
|
700
759
|
|
701
760
|
Returns:
|
702
761
|
output hidden_states tensor after MidBlock2D.
|
@@ -14,9 +14,8 @@
|
|
14
14
|
# ==============================================================================
|
15
15
|
# Builder utils for individual components.
|
16
16
|
|
17
|
-
from torch import nn
|
18
|
-
|
19
17
|
import ai_edge_torch.generative.layers.unet.model_config as unet_config
|
18
|
+
from torch import nn
|
20
19
|
|
21
20
|
|
22
21
|
def build_upsampling(config: unet_config.UpSamplingConfig):
|
@@ -30,10 +29,14 @@ def build_upsampling(config: unet_config.UpSamplingConfig):
|
|
30
29
|
|
31
30
|
def build_downsampling(config: unet_config.DownSamplingConfig):
|
32
31
|
if config.mode == unet_config.SamplingType.AVERAGE:
|
33
|
-
return nn.AvgPool2d(
|
32
|
+
return nn.AvgPool2d(
|
33
|
+
config.kernel_size, config.stride, padding=config.padding
|
34
|
+
)
|
34
35
|
elif config.mode == unet_config.SamplingType.CONVOLUTION:
|
35
36
|
out_channels = (
|
36
|
-
config.in_channels
|
37
|
+
config.in_channels
|
38
|
+
if config.out_channels is None
|
39
|
+
else config.out_channels
|
37
40
|
)
|
38
41
|
padding = (0, 1, 0, 1) if config.padding == 0 else config.padding
|
39
42
|
return nn.Conv2d(
|
@@ -14,8 +14,7 @@
|
|
14
14
|
# ==============================================================================
|
15
15
|
|
16
16
|
# UNet configuration class.
|
17
|
-
|
18
|
-
from dataclasses import field
|
17
|
+
import dataclasses
|
19
18
|
import enum
|
20
19
|
from typing import List, Optional
|
21
20
|
|
@@ -30,13 +29,13 @@ class SamplingType(enum.Enum):
|
|
30
29
|
CONVOLUTION = enum.auto()
|
31
30
|
|
32
31
|
|
33
|
-
@dataclass
|
32
|
+
@dataclasses.dataclass
|
34
33
|
class UpSamplingConfig:
|
35
34
|
mode: SamplingType
|
36
35
|
scale_factor: float
|
37
36
|
|
38
37
|
|
39
|
-
@dataclass
|
38
|
+
@dataclasses.dataclass
|
40
39
|
class DownSamplingConfig:
|
41
40
|
mode: SamplingType
|
42
41
|
in_channels: int
|
@@ -46,9 +45,10 @@ class DownSamplingConfig:
|
|
46
45
|
out_channels: Optional[int] = None
|
47
46
|
|
48
47
|
|
49
|
-
@dataclass
|
48
|
+
@dataclasses.dataclass
|
50
49
|
class ResidualBlock2DConfig:
|
51
50
|
in_channels: int
|
51
|
+
hidden_channels: int
|
52
52
|
out_channels: int
|
53
53
|
normalization_config: layers_cfg.NormalizationConfig
|
54
54
|
activation_config: layers_cfg.ActivationConfig
|
@@ -56,7 +56,7 @@ class ResidualBlock2DConfig:
|
|
56
56
|
time_embedding_channels: Optional[int] = None
|
57
57
|
|
58
58
|
|
59
|
-
@dataclass
|
59
|
+
@dataclasses.dataclass
|
60
60
|
class AttentionBlock2DConfig:
|
61
61
|
dim: int
|
62
62
|
normalization_config: layers_cfg.NormalizationConfig
|
@@ -65,17 +65,19 @@ class AttentionBlock2DConfig:
|
|
65
65
|
attention_batch_size: int = 1
|
66
66
|
|
67
67
|
|
68
|
-
@dataclass
|
68
|
+
@dataclasses.dataclass
|
69
69
|
class CrossAttentionBlock2DConfig:
|
70
70
|
query_dim: int
|
71
71
|
cross_dim: int
|
72
|
+
hidden_dim: int
|
73
|
+
output_dim: int
|
72
74
|
normalization_config: layers_cfg.NormalizationConfig
|
73
75
|
attention_config: layers_cfg.AttentionConfig
|
74
76
|
enable_hlfb: bool = True
|
75
77
|
attention_batch_size: int = 1
|
76
78
|
|
77
79
|
|
78
|
-
@dataclass
|
80
|
+
@dataclasses.dataclass
|
79
81
|
class FeedForwardBlock2DConfig:
|
80
82
|
dim: int
|
81
83
|
hidden_dim: int
|
@@ -84,7 +86,7 @@ class FeedForwardBlock2DConfig:
|
|
84
86
|
use_bias: bool
|
85
87
|
|
86
88
|
|
87
|
-
@dataclass
|
89
|
+
@dataclasses.dataclass
|
88
90
|
class TransformerBlock2DConfig:
|
89
91
|
pre_conv_normalization_config: layers_cfg.NormalizationConfig
|
90
92
|
attention_block_config: AttentionBlock2DConfig
|
@@ -92,7 +94,7 @@ class TransformerBlock2DConfig:
|
|
92
94
|
feed_forward_block_config: FeedForwardBlock2DConfig
|
93
95
|
|
94
96
|
|
95
|
-
@dataclass
|
97
|
+
@dataclasses.dataclass
|
96
98
|
class UpDecoderBlock2DConfig:
|
97
99
|
in_channels: int
|
98
100
|
out_channels: int
|
@@ -113,7 +115,7 @@ class UpDecoderBlock2DConfig:
|
|
113
115
|
context_dim: Optional[int] = None
|
114
116
|
|
115
117
|
|
116
|
-
@dataclass
|
118
|
+
@dataclasses.dataclass
|
117
119
|
class SkipUpDecoderBlock2DConfig:
|
118
120
|
in_channels: int
|
119
121
|
out_channels: int
|
@@ -136,7 +138,7 @@ class SkipUpDecoderBlock2DConfig:
|
|
136
138
|
context_dim: Optional[int] = None
|
137
139
|
|
138
140
|
|
139
|
-
@dataclass
|
141
|
+
@dataclasses.dataclass
|
140
142
|
class DownEncoderBlock2DConfig:
|
141
143
|
in_channels: int
|
142
144
|
out_channels: int
|
@@ -157,7 +159,7 @@ class DownEncoderBlock2DConfig:
|
|
157
159
|
context_dim: Optional[int] = None
|
158
160
|
|
159
161
|
|
160
|
-
@dataclass
|
162
|
+
@dataclasses.dataclass
|
161
163
|
class MidBlock2DConfig:
|
162
164
|
in_channels: int
|
163
165
|
normalization_config: layers_cfg.NormalizationConfig
|
@@ -173,7 +175,7 @@ class MidBlock2DConfig:
|
|
173
175
|
context_dim: Optional[int] = None
|
174
176
|
|
175
177
|
|
176
|
-
@dataclass
|
178
|
+
@dataclasses.dataclass
|
177
179
|
class AutoEncoderConfig:
|
178
180
|
"""Configurations of encoder/decoder in the autoencoder model."""
|
179
181
|
|
@@ -210,7 +212,7 @@ class AutoEncoderConfig:
|
|
210
212
|
mid_block_config: MidBlock2DConfig
|
211
213
|
|
212
214
|
|
213
|
-
@dataclass
|
215
|
+
@dataclasses.dataclass
|
214
216
|
class DiffusionModelConfig:
|
215
217
|
"""Configurations of Diffusion model."""
|
216
218
|
|
@@ -13,22 +13,21 @@
|
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
15
|
|
16
|
-
import numpy as np
|
17
|
-
import torch
|
18
|
-
|
19
16
|
import ai_edge_torch
|
20
|
-
from ai_edge_torch.generative.examples.gemma import
|
17
|
+
from ai_edge_torch.generative.examples.gemma import gemma1
|
21
18
|
from ai_edge_torch.generative.quantize import quant_recipes
|
19
|
+
import numpy as np
|
20
|
+
import torch
|
22
21
|
|
23
22
|
|
24
23
|
def main():
|
25
24
|
# Build a PyTorch model as usual
|
26
|
-
config =
|
27
|
-
model =
|
25
|
+
config = gemma1.get_fake_model_config()
|
26
|
+
model = gemma1.Gemma(config)
|
28
27
|
idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
|
29
|
-
tokens = torch.full((1, 10), 0, dtype=torch.
|
28
|
+
tokens = torch.full((1, 10), 0, dtype=torch.int, device="cpu")
|
30
29
|
tokens[0, :4] = idx
|
31
|
-
input_pos = torch.arange(0, 10)
|
30
|
+
input_pos = torch.arange(0, 10, dtype=torch.int)
|
32
31
|
|
33
32
|
# Create a quantization recipe to be applied to the model
|
34
33
|
quant_config = quant_recipes.full_int8_dynamic_recipe()
|