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.
Files changed (169) hide show
  1. ai_edge_torch/__init__.py +5 -4
  2. ai_edge_torch/_convert/conversion.py +112 -0
  3. ai_edge_torch/_convert/conversion_utils.py +64 -0
  4. ai_edge_torch/{convert → _convert}/converter.py +94 -48
  5. ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
  6. ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
  7. ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
  8. ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
  9. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
  10. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
  11. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
  12. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
  13. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
  14. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
  15. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
  16. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
  17. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
  18. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
  19. ai_edge_torch/_convert/signature.py +66 -0
  20. ai_edge_torch/_convert/test/test_convert.py +495 -0
  21. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  22. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  23. ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
  24. ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
  25. ai_edge_torch/config.py +27 -0
  26. ai_edge_torch/conftest.py +20 -0
  27. ai_edge_torch/debug/culprit.py +72 -40
  28. ai_edge_torch/debug/test/test_culprit.py +7 -5
  29. ai_edge_torch/debug/test/test_search_model.py +8 -7
  30. ai_edge_torch/debug/utils.py +14 -3
  31. ai_edge_torch/fx_pass_base.py +101 -0
  32. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
  33. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
  34. ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
  35. ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
  36. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  37. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
  38. ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
  39. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
  40. ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
  41. ai_edge_torch/generative/examples/openelm/verify.py +64 -0
  42. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  43. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
  44. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
  45. ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
  46. ai_edge_torch/generative/examples/phi/phi3.py +286 -0
  47. ai_edge_torch/generative/examples/phi/verify.py +65 -0
  48. ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
  49. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  50. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
  51. ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
  52. ai_edge_torch/generative/examples/smollm/verify.py +62 -0
  53. ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
  54. ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
  55. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
  56. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
  57. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
  58. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
  59. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
  60. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
  61. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
  62. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
  63. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
  64. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
  65. ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
  66. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
  67. ai_edge_torch/generative/examples/t5/t5.py +208 -159
  68. ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
  69. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  70. ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
  71. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
  72. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  73. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
  74. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
  75. ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
  76. ai_edge_torch/generative/fx_passes/__init__.py +4 -5
  77. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
  78. ai_edge_torch/generative/layers/attention.py +141 -102
  79. ai_edge_torch/generative/layers/attention_utils.py +53 -12
  80. ai_edge_torch/generative/layers/builder.py +37 -7
  81. ai_edge_torch/generative/layers/feed_forward.py +39 -14
  82. ai_edge_torch/generative/layers/kv_cache.py +162 -50
  83. ai_edge_torch/generative/layers/model_config.py +84 -30
  84. ai_edge_torch/generative/layers/normalization.py +185 -7
  85. ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
  86. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
  87. ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
  88. ai_edge_torch/generative/layers/unet/builder.py +7 -4
  89. ai_edge_torch/generative/layers/unet/model_config.py +17 -15
  90. ai_edge_torch/generative/quantize/example.py +7 -8
  91. ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
  92. ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
  93. ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
  94. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  95. ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
  96. ai_edge_torch/generative/test/test_model_conversion.py +124 -188
  97. ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
  98. ai_edge_torch/generative/test/test_quantize.py +76 -60
  99. ai_edge_torch/generative/test/utils.py +54 -0
  100. ai_edge_torch/generative/utilities/converter.py +82 -0
  101. ai_edge_torch/generative/utilities/loader.py +120 -57
  102. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
  103. ai_edge_torch/generative/utilities/t5_loader.py +110 -81
  104. ai_edge_torch/generative/utilities/verifier.py +247 -0
  105. ai_edge_torch/hlfb/__init__.py +1 -1
  106. ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
  107. ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
  108. ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
  109. ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
  110. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
  111. ai_edge_torch/lowertools/__init__.py +18 -0
  112. ai_edge_torch/lowertools/_shim.py +80 -0
  113. ai_edge_torch/lowertools/common_utils.py +142 -0
  114. ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
  115. ai_edge_torch/lowertools/test_utils.py +60 -0
  116. ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
  117. ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
  118. ai_edge_torch/model.py +53 -18
  119. ai_edge_torch/odml_torch/__init__.py +20 -0
  120. ai_edge_torch/odml_torch/_torch_future.py +61 -0
  121. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  122. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  123. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  124. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  125. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  126. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  127. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  128. ai_edge_torch/odml_torch/export.py +357 -0
  129. ai_edge_torch/odml_torch/export_utils.py +168 -0
  130. ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
  131. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
  132. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  133. ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
  134. ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
  135. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  136. ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
  137. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
  138. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
  139. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  140. ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
  141. ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
  142. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  143. ai_edge_torch/odml_torch/tf_integration.py +194 -0
  144. ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
  145. ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
  146. ai_edge_torch/quantize/quant_config.py +13 -9
  147. ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
  148. ai_edge_torch/version.py +16 -0
  149. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
  150. ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
  151. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
  152. ai_edge_torch/convert/conversion.py +0 -117
  153. ai_edge_torch/convert/conversion_utils.py +0 -400
  154. ai_edge_torch/convert/fx_passes/__init__.py +0 -59
  155. ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
  156. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
  157. ai_edge_torch/convert/test/test_convert.py +0 -311
  158. ai_edge_torch/convert/test/test_convert_composites.py +0 -192
  159. ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
  160. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
  161. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
  162. ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
  163. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
  164. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
  165. /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
  166. /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
  167. /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
  168. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
  169. {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
@@ -18,11 +18,10 @@ import glob
18
18
  import os
19
19
  from typing import Callable, Dict
20
20
 
21
+ from ai_edge_torch.generative.layers import model_config
21
22
  from safetensors import safe_open
22
23
  import torch
23
24
 
24
- from ai_edge_torch.generative.layers import model_config
25
-
26
25
 
27
26
  def load_safetensors(full_path: str):
28
27
  """Loads safetensors into a single state dictionary.
@@ -71,7 +70,11 @@ def load_pytorch_statedict(full_path: str):
71
70
  Raises:
72
71
  ValueError: If no tensors are loaded from the provided directory or file.
73
72
  """
74
- pattern = os.path.join(full_path, "*.bin") if os.path.isdir(full_path) else full_path
73
+ pattern = (
74
+ os.path.join(full_path, "*.bin")
75
+ if os.path.isdir(full_path)
76
+ else full_path
77
+ )
75
78
  files = []
76
79
  for file in glob.glob(pattern):
77
80
  files.append(file)
@@ -89,9 +92,7 @@ def load_pytorch_statedict(full_path: str):
89
92
 
90
93
 
91
94
  class ModelLoader:
92
- """A utility class for loading and converting model checkpoints to ODML
93
- transformer layer format.
94
- """
95
+ """Utility class for loading and converting checkpoints to ODML transformer layer format."""
95
96
 
96
97
  @dataclass
97
98
  class TensorNames:
@@ -112,18 +113,19 @@ class ModelLoader:
112
113
 
113
114
  pre_attn_norm: str = None
114
115
  pre_cross_attn_norm: str = None
115
- pre_ff_norm: str = None
116
+ post_attn_norm: str = None
116
117
  embedding: str = None
117
118
  final_norm: str = None
118
119
  lm_head: str = None
119
120
 
120
121
  def __init__(self, file_name: str, names: TensorNames) -> None:
121
- """ModelLoader constructor. Can be used to load multiple models of the same
122
- type.
122
+ """ModelLoader constructor.
123
+
124
+ Can be used to load multiple models of the same type.
123
125
 
124
126
  Args:
125
- file_name (str): Path to the checkpoint. Can be a directory or an
126
- exact file.
127
+ file_name (str): Path to the checkpoint. Can be a directory or an exact
128
+ file.
127
129
  names (TensorNames): An instance of `TensorNames` to determine mappings.
128
130
  """
129
131
  self._file_name = file_name
@@ -131,7 +133,10 @@ class ModelLoader:
131
133
  self._loader = self._get_loader()
132
134
 
133
135
  def load(
134
- self, model: torch.nn.Module, strict: bool = True, fuse_attention: bool = True
136
+ self,
137
+ model: torch.nn.Module,
138
+ strict: bool = True,
139
+ fuse_attention: bool = True,
135
140
  ):
136
141
  """Load the model from the checkpoint
137
142
 
@@ -152,7 +157,7 @@ class ModelLoader:
152
157
  )
153
158
  elif isinstance(self._names, dict):
154
159
  converted_state = {}
155
- for additional_prefix, names in self._names.items():
160
+ for additional_prefix, _ in self._names.items():
156
161
  local_converted_state = self._do_load(
157
162
  model,
158
163
  state,
@@ -166,11 +171,14 @@ class ModelLoader:
166
171
 
167
172
  if strict and state:
168
173
  raise ValueError(
169
- f"Failed to map all tensor. Remaining tensor are: {list(state.keys())}"
174
+ "Failed to map all tensor. Remaining tensor are:"
175
+ f" {list(state.keys())}"
170
176
  )
171
177
  model.load_state_dict(converted_state, strict=strict)
172
178
 
173
- def _do_load(self, model, state, names, additional_prefix="", fuse_attention=True):
179
+ def _do_load(
180
+ self, model, state, names, additional_prefix="", fuse_attention=True
181
+ ):
174
182
  """Load the model from the checkpoint
175
183
 
176
184
  Args:
@@ -183,7 +191,9 @@ class ModelLoader:
183
191
  """
184
192
  converted_state = dict()
185
193
  if names.embedding is not None:
186
- converted_state["tok_embedding.weight"] = state.pop(f"{names.embedding}.weight")
194
+ converted_state["tok_embedding.weight"] = state.pop(
195
+ f"{names.embedding}.weight"
196
+ )
187
197
  if names.lm_head is not None:
188
198
  converted_state["lm_head.weight"] = state.pop(f"{names.lm_head}.weight")
189
199
  if model.config.lm_head_use_bias:
@@ -195,17 +205,21 @@ class ModelLoader:
195
205
  f"{final_norm_name}.weight"
196
206
  )
197
207
  if f"{final_norm_name}.bias" in state:
198
- converted_state["final_norm.bias"] = state.pop(f"{final_norm_name}.bias")
208
+ converted_state["final_norm.bias"] = state.pop(
209
+ f"{final_norm_name}.bias"
210
+ )
199
211
 
200
212
  if names.relative_attn_bias:
201
213
  rel_attn_name = names.relative_attn_bias
202
- prefix = additional_prefix + f"transformer_blocks.0"
214
+ prefix = additional_prefix + "transformer_blocks.0"
203
215
  converted_state[f"{prefix}.atten_func.relative_attention_bias.weight"] = (
204
216
  state.pop(f"{rel_attn_name}.weight")
205
217
  )
206
218
 
207
219
  for i in range(model.config.num_layers):
208
- self._map_norm(i, model.config, state, converted_state, names, additional_prefix)
220
+ self._map_norm(
221
+ i, model.config, state, converted_state, names, additional_prefix
222
+ )
209
223
  self._map_feedforward(
210
224
  i, model.config, state, converted_state, names, additional_prefix
211
225
  )
@@ -251,7 +265,7 @@ class ModelLoader:
251
265
  if self._file_name.endswith(".bin"):
252
266
  return load_pytorch_statedict
253
267
 
254
- raise ValueError(f"File format not supported.")
268
+ raise ValueError("File format not supported.")
255
269
 
256
270
  def _map_feedforward(
257
271
  self,
@@ -265,16 +279,23 @@ class ModelLoader:
265
279
  prefix = additional_prefix + f"transformer_blocks.{idx}"
266
280
  if names.ff_up_proj is None or names.ff_down_proj is None:
267
281
  return
268
- if config.ff_config.type == model_config.FeedForwardType.SEQUENTIAL:
282
+ ff_config = config.block_config(idx).ff_config
283
+ if ff_config.type == model_config.FeedForwardType.SEQUENTIAL:
269
284
  ff_up_proj_name = names.ff_up_proj.format(idx)
270
285
  ff_down_proj_name = names.ff_down_proj.format(idx)
271
- converted_state[f"{prefix}.ff.w1.weight"] = state.pop(f"{ff_up_proj_name}.weight")
286
+ converted_state[f"{prefix}.ff.w1.weight"] = state.pop(
287
+ f"{ff_up_proj_name}.weight"
288
+ )
272
289
  converted_state[f"{prefix}.ff.w2.weight"] = state.pop(
273
290
  f"{ff_down_proj_name}.weight"
274
291
  )
275
- if config.ff_config.use_bias:
276
- converted_state[f"{prefix}.ff.w1.bias"] = state.pop(f"{ff_up_proj_name}.bias")
277
- converted_state[f"{prefix}.ff.w2.bias"] = state.pop(f"{ff_down_proj_name}.bias")
292
+ if ff_config.use_bias:
293
+ converted_state[f"{prefix}.ff.w1.bias"] = state.pop(
294
+ f"{ff_up_proj_name}.bias"
295
+ )
296
+ converted_state[f"{prefix}.ff.w2.bias"] = state.pop(
297
+ f"{ff_down_proj_name}.bias"
298
+ )
278
299
  else:
279
300
  if names.ff_gate_proj is not None:
280
301
  ff_up_proj_name = names.ff_up_proj.format(idx)
@@ -289,8 +310,10 @@ class ModelLoader:
289
310
  converted_state[f"{prefix}.ff.w1.weight"] = state.pop(
290
311
  f"{ff_gate_proj_name}.weight"
291
312
  )
292
- if config.ff_config.use_bias:
293
- converted_state[f"{prefix}.ff.w3.bias"] = state.pop(f"{ff_up_proj_name}.bias")
313
+ if ff_config.use_bias:
314
+ converted_state[f"{prefix}.ff.w3.bias"] = state.pop(
315
+ f"{ff_up_proj_name}.bias"
316
+ )
294
317
  converted_state[f"{prefix}.ff.w2.bias"] = state.pop(
295
318
  f"{ff_down_proj_name}.bias"
296
319
  )
@@ -315,20 +338,21 @@ class ModelLoader:
315
338
  ):
316
339
  return
317
340
  prefix = additional_prefix + f"transformer_blocks.{idx}"
341
+ attn_config = config.block_config(idx).attn_config
318
342
  q_name = names.attn_query_proj.format(idx)
319
343
  k_name = names.attn_key_proj.format(idx)
320
344
  v_name = names.attn_value_proj.format(idx)
321
345
  # model.encoder.transformer_blocks[0].atten_func.q_projection.weight
322
346
  if fuse_attention:
323
347
  converted_state[f"{prefix}.atten_func.attn.weight"] = self._fuse_qkv(
324
- config,
348
+ attn_config,
325
349
  state.pop(f"{q_name}.weight"),
326
350
  state.pop(f"{k_name}.weight"),
327
351
  state.pop(f"{v_name}.weight"),
328
352
  )
329
- if config.attn_config.qkv_use_bias:
353
+ if attn_config.qkv_use_bias:
330
354
  converted_state[f"{prefix}.atten_func.attn.bias"] = self._fuse_qkv(
331
- config,
355
+ attn_config,
332
356
  state.pop(f"{q_name}.bias"),
333
357
  state.pop(f"{k_name}.bias"),
334
358
  state.pop(f"{v_name}.bias"),
@@ -343,7 +367,7 @@ class ModelLoader:
343
367
  converted_state[f"{prefix}.atten_func.v_projection.weight"] = state.pop(
344
368
  f"{v_name}.weight"
345
369
  )
346
- if config.attn_config.qkv_use_bias:
370
+ if attn_config.qkv_use_bias:
347
371
  converted_state[f"{prefix}.atten_func.q_projection.bias"] = state.pop(
348
372
  f"{q_name}.bias"
349
373
  )
@@ -355,12 +379,12 @@ class ModelLoader:
355
379
  )
356
380
 
357
381
  o_name = names.attn_output_proj.format(idx)
358
- converted_state[f"{prefix}.atten_func.output_projection.weight"] = state.pop(
359
- f"{o_name}.weight"
382
+ converted_state[f"{prefix}.atten_func.output_projection.weight"] = (
383
+ state.pop(f"{o_name}.weight")
360
384
  )
361
- if config.attn_config.output_proj_use_bias:
362
- converted_state[f"{prefix}.atten_func.output_projection.bias"] = state.pop(
363
- f"{o_name}.bias"
385
+ if attn_config.output_proj_use_bias:
386
+ converted_state[f"{prefix}.atten_func.output_projection.bias"] = (
387
+ state.pop(f"{o_name}.bias")
364
388
  )
365
389
 
366
390
  def _map_cross_attention(
@@ -380,52 +404,57 @@ class ModelLoader:
380
404
  ):
381
405
  return
382
406
  prefix = additional_prefix + f"transformer_blocks.{idx}"
407
+ attn_config = config.block_config(idx).attn_config
383
408
  q_name = names.cross_attn_query_proj.format(idx)
384
409
  k_name = names.cross_attn_key_proj.format(idx)
385
410
  v_name = names.cross_attn_value_proj.format(idx)
386
411
 
387
412
  if fuse_attention:
388
- converted_state[f"{prefix}.cross_atten_func.attn.weight"] = self._fuse_qkv(
389
- config,
390
- state.pop(f"{q_name}.weight"),
391
- state.pop(f"{k_name}.weight"),
392
- state.pop(f"{v_name}.weight"),
413
+ converted_state[f"{prefix}.cross_atten_func.attn.weight"] = (
414
+ self._fuse_qkv(
415
+ attn_config,
416
+ state.pop(f"{q_name}.weight"),
417
+ state.pop(f"{k_name}.weight"),
418
+ state.pop(f"{v_name}.weight"),
419
+ )
393
420
  )
394
- if config.attn_config.qkv_use_bias:
395
- converted_state[f"{prefix}.cross_atten_func.attn.bias"] = self._fuse_qkv(
396
- config,
397
- state.pop(f"{q_name}.bias"),
398
- state.pop(f"{k_name}.bias"),
399
- state.pop(f"{v_name}.bias"),
421
+ if attn_config.qkv_use_bias:
422
+ converted_state[f"{prefix}.cross_atten_func.attn.bias"] = (
423
+ self._fuse_qkv(
424
+ attn_config,
425
+ state.pop(f"{q_name}.bias"),
426
+ state.pop(f"{k_name}.bias"),
427
+ state.pop(f"{v_name}.bias"),
428
+ )
400
429
  )
401
430
  else:
402
- converted_state[f"{prefix}.cross_atten_func.q_projection.weight"] = state.pop(
403
- f"{q_name}.weight"
431
+ converted_state[f"{prefix}.cross_atten_func.q_projection.weight"] = (
432
+ state.pop(f"{q_name}.weight")
404
433
  )
405
- converted_state[f"{prefix}.cross_atten_func.k_projection.weight"] = state.pop(
406
- f"{k_name}.weight"
434
+ converted_state[f"{prefix}.cross_atten_func.k_projection.weight"] = (
435
+ state.pop(f"{k_name}.weight")
407
436
  )
408
- converted_state[f"{prefix}.cross_atten_func.v_projection.weight"] = state.pop(
409
- f"{v_name}.weight"
437
+ converted_state[f"{prefix}.cross_atten_func.v_projection.weight"] = (
438
+ state.pop(f"{v_name}.weight")
410
439
  )
411
- if config.attn_config.qkv_use_bias:
412
- converted_state[f"{prefix}.cross_atten_func.q_projection.bias"] = state.pop(
413
- f"{q_name}.bias"
440
+ if attn_config.qkv_use_bias:
441
+ converted_state[f"{prefix}.cross_atten_func.q_projection.bias"] = (
442
+ state.pop(f"{q_name}.bias")
414
443
  )
415
- converted_state[f"{prefix}.cross_atten_func.k_projection.bias"] = state.pop(
416
- f"{k_name}.bias"
444
+ converted_state[f"{prefix}.cross_atten_func.k_projection.bias"] = (
445
+ state.pop(f"{k_name}.bias")
417
446
  )
418
- converted_state[f"{prefix}.cross_atten_func.v_projection.bias"] = state.pop(
419
- f"{v_name}.bias"
447
+ converted_state[f"{prefix}.cross_atten_func.v_projection.bias"] = (
448
+ state.pop(f"{v_name}.bias")
420
449
  )
421
450
 
422
451
  o_name = names.cross_attn_output_proj.format(idx)
423
- converted_state[f"{prefix}.cross_atten_func.output_projection.weight"] = state.pop(
424
- f"{o_name}.weight"
452
+ converted_state[f"{prefix}.cross_atten_func.output_projection.weight"] = (
453
+ state.pop(f"{o_name}.weight")
425
454
  )
426
- if config.attn_config.output_proj_use_bias:
427
- converted_state[f"{prefix}.cross_atten_func.output_projection.bias"] = state.pop(
428
- f"{o_name}.bias"
455
+ if attn_config.output_proj_use_bias:
456
+ converted_state[f"{prefix}.cross_atten_func.output_projection.bias"] = (
457
+ state.pop(f"{o_name}.bias")
429
458
  )
430
459
 
431
460
  def _map_norm(
@@ -450,34 +479,34 @@ class ModelLoader:
450
479
 
451
480
  if names.pre_cross_attn_norm:
452
481
  pre_cross_attn_norm_name = names.pre_cross_attn_norm.format(idx)
453
- converted_state[f"{prefix}.cross_atten_func.pre_atten_norm.weight"] = state.pop(
454
- f"{pre_cross_attn_norm_name}.weight"
482
+ converted_state[f"{prefix}.cross_atten_func.pre_atten_norm.weight"] = (
483
+ state.pop(f"{pre_cross_attn_norm_name}.weight")
455
484
  )
456
485
  if f"{pre_cross_attn_norm_name}.bias" in state:
457
- converted_state[f"{prefix}.cross_atten_func.pre_atten_norm.bias"] = state.pop(
458
- f"{pre_cross_attn_norm_name}.bias"
486
+ converted_state[f"{prefix}.cross_atten_func.pre_atten_norm.bias"] = (
487
+ state.pop(f"{pre_cross_attn_norm_name}.bias")
459
488
  )
460
489
 
461
- if names.pre_ff_norm is not None:
462
- pre_ff_norm_name = names.pre_ff_norm.format(idx)
463
- converted_state[f"{prefix}.pre_ff_norm.weight"] = state.pop(
464
- f"{pre_ff_norm_name}.weight"
490
+ if names.post_attn_norm is not None:
491
+ post_attn_norm_name = names.post_attn_norm.format(idx)
492
+ converted_state[f"{prefix}.post_atten_norm.weight"] = state.pop(
493
+ f"{post_attn_norm_name}.weight"
465
494
  )
466
- if f"{pre_ff_norm_name}.bias" in state:
467
- converted_state[f"{prefix}.pre_ff_norm.bias"] = state.pop(
468
- f"{pre_ff_norm_name}.bias"
495
+ if f"{post_attn_norm_name}.bias" in state:
496
+ converted_state[f"{prefix}.post_atten_norm.bias"] = state.pop(
497
+ f"{post_attn_norm_name}.bias"
469
498
  )
470
499
 
471
500
  def _fuse_qkv(
472
501
  self,
473
- config: model_config.ModelConfig,
502
+ attn_config: model_config.AttentionConfig,
474
503
  q: torch.Tensor,
475
504
  k: torch.Tensor,
476
505
  v: torch.Tensor,
477
506
  ) -> torch.Tensor:
478
- q_per_kv = config.attn_config.num_heads // config.attn_config.num_query_groups
479
- qs = torch.split(q, config.head_dim * q_per_kv)
480
- ks = torch.split(k, config.head_dim)
481
- vs = torch.split(v, config.head_dim)
507
+ q_per_kv = attn_config.num_heads // attn_config.num_query_groups
508
+ qs = torch.split(q, attn_config.head_dim * q_per_kv)
509
+ ks = torch.split(k, attn_config.head_dim)
510
+ vs = torch.split(v, attn_config.head_dim)
482
511
  cycled = [t for group in zip(qs, ks, vs) for t in group]
483
512
  return torch.cat(cycled)
@@ -0,0 +1,247 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Common utility functions to verify the reauthored models."""
17
+
18
+ import logging
19
+ from typing import List, Optional, Union
20
+
21
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
22
+ import torch
23
+ import transformers
24
+
25
+
26
+ class ModelWrapper(torch.nn.Module):
27
+ """A wrapper for the model to be verified, this could be a HuggingFace model
28
+
29
+ or a regular PyTorch model.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ model: torch.nn.Module,
35
+ model_format: str = "huggingface",
36
+ hf_generation_config: Optional[transformers.GenerationConfig] = None,
37
+ ):
38
+ """Initializes the wrapper.
39
+
40
+ Args:
41
+ model (torch.nn.Module): The original model. This could be a model built
42
+ from HuggingFace transformers, or a regular PyTorch model.
43
+ model_format (str): The format of the model. It should be either
44
+ "huggingface" or "pytorch".
45
+ hf_generation_config (transformers.GenerationConfig): The HuggingFace
46
+ generation config. This config will only be used if the underlying model
47
+ is built from HuggingFace transformers.
48
+ """
49
+ super().__init__()
50
+ self.model = model
51
+ self.model_format = model_format
52
+ self.hf_generation_config = hf_generation_config
53
+
54
+ def generate(
55
+ self, inputs: torch.Tensor
56
+ ) -> Union[transformers.utils.ModelOutput, torch.LongTensor]:
57
+ if self.model_format == "huggingface":
58
+ return self.model.generate(
59
+ inputs=inputs, generation_config=self.hf_generation_config
60
+ )
61
+ else:
62
+ raise NotImplementedError(
63
+ "generate() is not implemented for model format: %s"
64
+ % self.model_format
65
+ )
66
+
67
+ def forward(
68
+ self,
69
+ inputs: torch.Tensor,
70
+ ):
71
+ return self.model.forward(inputs)
72
+
73
+
74
+ def forward(
75
+ model: torch.nn.Module,
76
+ tokens: torch.Tensor,
77
+ kv_cache: kv_utils.KVCache,
78
+ ) -> tuple[torch.Tensor, kv_utils.KVCache]:
79
+ """Forwards the model reauthored with ai_edge_torch Generative API.
80
+
81
+ Args:
82
+ model (torch.nn.Module): The model to forward. It should be a model built
83
+ with ai_edge_torch Generative API.
84
+ tokens (torch.Tensor): The input tokens to forward.
85
+ kv_cache (KVCache): The KV cache to forward.
86
+
87
+ Returns:
88
+ The output logits and the updated KV cache.
89
+ """
90
+ input_pos = torch.arange(0, tokens.shape[1], dtype=torch.int)
91
+ output = model.forward(tokens, input_pos, kv_cache)
92
+ return output["logits"], output["kv_cache"]
93
+
94
+
95
+ def generate(
96
+ model: torch.nn.Module, prompts: torch.Tensor, response_len: int
97
+ ) -> torch.Tensor:
98
+ """Generates the response to the prompts.
99
+
100
+ It appends tokens output by the model to the prompts and feeds them back to
101
+ the model up to decode_len.
102
+
103
+ Args:
104
+ model (torch.nn.Module): The model to generate. It should be a model built
105
+ with ai_edge_torch Generative API.
106
+ prompts (torch.Tensor): The prompts to generate.
107
+ response_len (int): The number of tokens to generate.
108
+
109
+ Returns:
110
+ The generated tokens.
111
+ """
112
+ input_ids = prompts[0].int().tolist()
113
+ kv_cache = kv_utils.KVCache.from_model_config(model.config)
114
+ for _ in range(response_len - len(input_ids)):
115
+ logits, kv_cache = forward(model, torch.tensor([input_ids]), kv_cache)
116
+ generated_token = logits[0][-1].argmax().item()
117
+ input_ids.append(generated_token)
118
+ return torch.tensor([input_ids])
119
+
120
+
121
+ def verify_with_input_ids(
122
+ original_model: ModelWrapper,
123
+ reauthored_model: torch.nn.Module,
124
+ input_ids: List[int],
125
+ kv_cache_max_len: int = 1024,
126
+ rtol: float = 1e-05,
127
+ atol: float = 1e-05,
128
+ ) -> bool:
129
+ """Verifies if the model reauthored generates the same output of the oringal.
130
+
131
+ It compares only one outputs from the original and the reauthored model.
132
+
133
+ Args:
134
+ original_model (ModelWrapper): The original model.
135
+ reauthored_model (torch.nn.Module): The model reauthored with ai_edge_torch
136
+ Generative API.
137
+ input_ids (List[int]): The input token IDs to forward with.
138
+ kv_cache_max_len (int): The maximum sequence length of the KV cache.
139
+ rtol (float): The relative tolerance for the comparison.
140
+ atol (float): The absolute tolerance for the comparison.
141
+
142
+ Returns:
143
+ True if the model reauthored generates the same output of the original.
144
+ """
145
+ tokens = torch.full((1, kv_cache_max_len), 0, dtype=torch.int, device="cpu")
146
+ tokens[0, : len(input_ids)] = torch.tensor([input_ids]).int()
147
+
148
+ logging.info("Forwarding the original model...")
149
+ outputs_original = original_model.forward(tokens)
150
+ logits_original = outputs_original.logits[0, len(input_ids) - 1, :]
151
+ logging.info("logits_original: %s", logits_original)
152
+
153
+ logging.info("Forwarding the reauthored model...")
154
+ kv_cache = kv_utils.KVCache.from_model_config(reauthored_model.config)
155
+ outputs_reauthored = forward(reauthored_model, tokens, kv_cache)
156
+ logits_reauthored = outputs_reauthored[0][0, len(input_ids) - 1, :]
157
+ logging.info("logits_reauthored: %s", logits_reauthored)
158
+
159
+ return torch.allclose(
160
+ logits_original, logits_reauthored, rtol=rtol, atol=atol
161
+ )
162
+
163
+
164
+ def verify_model_with_prompts(
165
+ original_model: ModelWrapper,
166
+ reauthored_model: torch.nn.Module,
167
+ tokenizer: torch.nn.Module,
168
+ prompts: str,
169
+ ) -> bool:
170
+ """Verifies if the model reauthored generates the same answer of the oringal.
171
+
172
+ It compares an answer, i.e. multiple continuous outputs generated by the
173
+ original and the reauthored model.
174
+
175
+ Args:
176
+ original_model (ModelWrapper): The original model.
177
+ reauthored_model (torch.nn.Module): The model reauthored with ai_edge_torch
178
+ Generative API.
179
+ tokenizer (torch.nn.Module): The tokenizer.
180
+ prompts (str): The input prompts to generate answers.
181
+
182
+ Returns:
183
+ True if the model reauthored generates the same answer of the original.
184
+ """
185
+ prompt_tokens = tokenizer.encode(prompts, return_tensors="pt")
186
+
187
+ logging.info("Generating answer with the original model...")
188
+ outputs_original = original_model.generate(prompt_tokens)
189
+ response_original = tokenizer.decode(outputs_original[0])
190
+ logging.info("outputs_from_original_model: [[%s]]", response_original)
191
+
192
+ logging.info("Generating answer with the reauthored model...")
193
+ generate_len = len(outputs_original[0])
194
+ outputs_reauthored = generate(reauthored_model, prompt_tokens, generate_len)
195
+ response_reauthored = tokenizer.decode(outputs_reauthored[0])
196
+ logging.info("outputs from reauthored model: [[%s]]", response_reauthored)
197
+
198
+ return response_original == response_reauthored
199
+
200
+
201
+ def verify_reauthored_model(
202
+ original_model: ModelWrapper,
203
+ reauthored_model: torch.nn.Module,
204
+ tokenizer: torch.nn.Module,
205
+ generate_prompts: List[str],
206
+ forward_input_ids: List[List[int]] = [[1, 2, 3, 4]],
207
+ rtol: float = 1e-05,
208
+ atol: float = 1e-05,
209
+ ):
210
+ """Verifies the reauthored model against the original model.
211
+
212
+ It verifies the reauthored model with two methods:
213
+ 1. It compares the output of the original and the reauthored model with an
214
+ arbitrary input.
215
+ 2. It compares the answer generated by the original and the reauthored model
216
+ with a prompt.
217
+
218
+ It prints out "PASS" or "FAILED" to the console.
219
+
220
+ Args:
221
+ original_model (ModelWrapper): The original model.
222
+ reauthored_model (torch.nn.Module): The model reauthored with ai_edge_torch
223
+ Generative API.
224
+ tokenizer (torch.nn.Module): The tokenizer.
225
+ generate_prompts (List[str]): List of the input prompts to generate answers.
226
+ forward_input_ids (List[torch.Tensor]): List if ihe input token IDs to
227
+ forward with.
228
+ rtol (float): The relative tolerance for the comparison.
229
+ atol (float): The absolute tolerance for the comparison.
230
+ """
231
+ for input_ids in forward_input_ids:
232
+ logging.info("Verifying the reauthored model with input IDs: %s", input_ids)
233
+ if verify_with_input_ids(
234
+ original_model, reauthored_model, input_ids, rtol=rtol, atol=atol
235
+ ):
236
+ logging.info("PASS")
237
+ else:
238
+ logging.info("FAILED")
239
+
240
+ for prompts in generate_prompts:
241
+ logging.info("Verifying the reauthored model with prompts:%s", prompts)
242
+ if verify_model_with_prompts(
243
+ original_model, reauthored_model, tokenizer, prompts
244
+ ):
245
+ logging.info("PASS")
246
+ else:
247
+ logging.info("FAILED")
@@ -13,4 +13,4 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
- from torch_xla.experimental.mark_pattern_utils import StableHLOCompositeBuilder
16
+ from ai_edge_torch.lowertools import StableHLOCompositeBuilder
@@ -16,11 +16,10 @@ import copy
16
16
  from typing import Any
17
17
  import uuid
18
18
 
19
+ from ai_edge_torch import lowertools
20
+ from ai_edge_torch.hlfb.mark_pattern import passes
21
+ from ai_edge_torch.hlfb.mark_pattern import pattern as pattern_module
19
22
  import torch
20
- from torch_xla.experimental import xla_marker
21
-
22
- from ai_edge_torch.hlfb.mark_pattern.pattern import Pattern
23
- from ai_edge_torch.hlfb.mark_pattern.pattern import ScalarAttrTracker # NOQA
24
23
 
25
24
 
26
25
  @torch._dynamo.assume_constant_result
@@ -49,10 +48,10 @@ def _insert_marker(
49
48
  is_input: bool,
50
49
  attr: dict[str, Any] = None,
51
50
  ):
52
- attr = xla_marker.serialize_composite_attr(attr) if attr else None
51
+ attr = lowertools.serialize_composite_attr(attr) if attr else None
53
52
  with graph_module.graph.inserting_after(node):
54
53
  new_node = graph_module.graph.call_function(
55
- torch.ops.xla.mark_tensor,
54
+ lowertools.mark_tensor_op,
56
55
  args=(node,),
57
56
  kwargs={
58
57
  "name": name,
@@ -69,13 +68,16 @@ def _insert_marker(
69
68
 
70
69
  def mark_pattern(
71
70
  graph_module: torch.fx.GraphModule,
72
- pattern: Pattern,
71
+ pattern: pattern_module.Pattern,
73
72
  ) -> torch.fx.GraphModule:
74
73
  """Mark all existences of pattern graph in the GraphModule with fx pattern matching.
74
+
75
75
  The marked subgraphs will be lowered in StableHLO composite ops.
76
+
76
77
  Args:
77
78
  graph_module (torch.fx.GraphModule): GraphModule to be matched and marked.
78
79
  pattern (ai_edge_torch.hlfb.mark_pattern.Pattern): Pattern to match.
80
+
79
81
  Returns:
80
82
  The modified graph_module with additional marker ops in graph.
81
83
  """