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
@@ -25,7 +25,8 @@ class LayerQuantRecipe:
25
25
  """Quantization recipe for a single Edge Generative API layer (e.g. Attention).
26
26
 
27
27
  Generic layer-scoped quantization recipe that specifies how this layer should
28
- be quantized by the Edge Generative API. This is applicable to layers implemented
28
+ be quantized by the Edge Generative API. This is applicable to layers
29
+ implemented
29
30
  in ai_edge_torch/generative/layers/. Combinations of attributes that are not
30
31
  supported during runtime will be detected when .verify() is called.
31
32
 
@@ -74,7 +75,8 @@ class LayerQuantRecipe:
74
75
 
75
76
  if not is_valid:
76
77
  raise ValueError(
77
- 'Unsupported LayerQuantRecipe configuration. See get_supported_recipe_matrix()'
78
+ 'Unsupported LayerQuantRecipe configuration. See'
79
+ ' get_supported_recipe_matrix()'
78
80
  )
79
81
 
80
82
 
@@ -82,7 +84,8 @@ class LayerQuantRecipe:
82
84
  class GenerativeQuantRecipe:
83
85
  """Quantization recipe for a model composed of the Edge Generative API layers.
84
86
 
85
- Some layers can be specified with different `LayerQuantRecipe` for each block by
87
+ Some layers can be specified with different `LayerQuantRecipe` for each block
88
+ by
86
89
  providing a dictionary keyed by the TransformerBlock index, e.g. attention
87
90
  and feedforward. For example,
88
91
 
@@ -101,11 +104,11 @@ class GenerativeQuantRecipe:
101
104
  default: The quantization recipe for global scope of the model.
102
105
  embedding: Recipe for the embedding table.
103
106
  attention: Recipe for the attention blocks. This could be specified with
104
- different LayerQuantRecipe for each block by providing a dictionary
105
- keyed by the TransformerBlock index.
107
+ different LayerQuantRecipe for each block by providing a dictionary keyed
108
+ by the TransformerBlock index.
106
109
  feedforward: Recipe for the feedforward layers. This could be specified with
107
- different LayerQuantRecipe for each block by providing a dictionary
108
- keyed by the TransformerBlock index.
110
+ different LayerQuantRecipe for each block by providing a dictionary keyed
111
+ by the TransformerBlock index.
109
112
  """
110
113
 
111
114
  default: Optional[LayerQuantRecipe] = None
@@ -16,7 +16,8 @@
16
16
  """Helper functions to construct custom quantization recipes.
17
17
 
18
18
  These are intended for more advanced users who want to configure their own
19
- quantization recipes. For pre-constructed recipes, use `quant_recipes.py` instead.
19
+ quantization recipes. For pre-constructed recipes, use `quant_recipes.py`
20
+ instead.
20
21
 
21
22
  Typical usage example:
22
23
 
@@ -41,6 +42,16 @@ def create_layer_quant_int8_dynamic() -> quant_recipe.LayerQuantRecipe:
41
42
  )
42
43
 
43
44
 
45
+ def create_layer_quant_int8_weight_only() -> quant_recipe.LayerQuantRecipe:
46
+ return quant_recipe.LayerQuantRecipe(
47
+ activation_dtype=quant_attrs.Dtype.FP32,
48
+ weight_dtype=quant_attrs.Dtype.INT8,
49
+ mode=quant_attrs.Mode.WEIGHT_ONLY,
50
+ algorithm=quant_attrs.Algorithm.MIN_MAX,
51
+ granularity=quant_attrs.Granularity.CHANNELWISE,
52
+ )
53
+
54
+
44
55
  def create_layer_quant_fp16() -> quant_recipe.LayerQuantRecipe:
45
56
  return quant_recipe.LayerQuantRecipe(
46
57
  activation_dtype=quant_attrs.Dtype.FP32,
@@ -40,6 +40,14 @@ def full_int8_dynamic_recipe() -> quant_config.QuantConfig:
40
40
  )
41
41
 
42
42
 
43
+ def full_int8_weight_only_recipe() -> quant_config.QuantConfig:
44
+ return quant_config.QuantConfig(
45
+ generative_recipe=quant_recipe.GenerativeQuantRecipe(
46
+ default=quant_recipe_utils.create_layer_quant_int8_weight_only(),
47
+ )
48
+ )
49
+
50
+
43
51
  def full_fp16_recipe() -> quant_config.QuantConfig:
44
52
  return quant_config.QuantConfig(
45
53
  generative_recipe=quant_recipe.GenerativeQuantRecipe(
@@ -0,0 +1,120 @@
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
+ """A suite of tests to validate KV Cache layer."""
17
+
18
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
19
+ import ai_edge_torch.generative.layers.model_config as cfg
20
+ import torch
21
+
22
+ from absl.testing import absltest as googletest
23
+
24
+
25
+ class TestKVLayers(googletest.TestCase):
26
+
27
+ def _get_test_config(
28
+ self, num_layers, head_dim, num_query_groups, kv_cache_max_len
29
+ ):
30
+ attn_config = cfg.AttentionConfig(
31
+ num_heads=1, head_dim=head_dim, num_query_groups=num_query_groups
32
+ )
33
+ block_config = cfg.TransformerBlockConfig(
34
+ attn_config=attn_config, ff_config=None
35
+ )
36
+ config = cfg.ModelConfig(
37
+ kv_cache_max_len=kv_cache_max_len,
38
+ embedding_dim=head_dim,
39
+ block_configs=block_config,
40
+ num_layers=num_layers,
41
+ max_seq_len=None,
42
+ vocab_size=None,
43
+ )
44
+ return config
45
+
46
+ def test_cache_udpate(self):
47
+ N = 1
48
+ HEAD_DIM = 2
49
+ NUM_QG = 1
50
+ KV_LEN = 4
51
+ config = self._get_test_config(
52
+ num_layers=N,
53
+ head_dim=HEAD_DIM,
54
+ num_query_groups=NUM_QG,
55
+ kv_cache_max_len=KV_LEN,
56
+ )
57
+ kv = kv_utils.KVCache.from_model_config(config)
58
+ entry = kv.caches[0]
59
+ # single-slice update
60
+ input_pos = torch.tensor([1])
61
+ k_slice = v_slice = torch.full(
62
+ (1, 1, NUM_QG, HEAD_DIM), 5, dtype=torch.float
63
+ )
64
+ updated_entry = kv_utils.update(entry, input_pos, k_slice, v_slice)
65
+ self.assertEqual(
66
+ updated_entry.k_cache.numpy().flatten().tolist(),
67
+ [0, 0, 5, 5, 0, 0, 0, 0],
68
+ )
69
+ self.assertEqual(
70
+ updated_entry.v_cache.numpy().flatten().tolist(),
71
+ [0, 0, 5, 5, 0, 0, 0, 0],
72
+ )
73
+ # multi-slice update
74
+ input_pos = torch.tensor([0, 3])
75
+ k_slice = v_slice = torch.full(
76
+ (1, 2, NUM_QG, HEAD_DIM), 7, dtype=torch.float
77
+ )
78
+ updated_entry = kv_utils.update(entry, input_pos, k_slice, v_slice)
79
+ self.assertEqual(
80
+ updated_entry.k_cache.numpy().flatten().tolist(),
81
+ [7, 7, 0, 0, 0, 0, 7, 7],
82
+ )
83
+ self.assertEqual(
84
+ updated_entry.v_cache.numpy().flatten().tolist(),
85
+ [7, 7, 0, 0, 0, 0, 7, 7],
86
+ )
87
+
88
+ def test_serialization(self):
89
+ class TestModel(torch.nn.Module):
90
+
91
+ def forward(self, kv: kv_utils.KVCache) -> kv_utils.KVCache:
92
+ updated_kv_entries = [
93
+ kv_utils.KVCacheEntry(
94
+ torch.zeros_like(entry.k_cache), torch.zeros_like(entry.v_cache)
95
+ )
96
+ for entry in kv.caches
97
+ ]
98
+ return kv_utils.KVCache(updated_kv_entries)
99
+
100
+ N = 1
101
+ HEAD_DIM = 2
102
+ NUM_QG = 1
103
+ KV_LEN = 4
104
+ config = self._get_test_config(
105
+ num_layers=N,
106
+ head_dim=HEAD_DIM,
107
+ num_query_groups=NUM_QG,
108
+ kv_cache_max_len=KV_LEN,
109
+ )
110
+ kv = kv_utils.KVCache.from_model_config(config)
111
+ model = TestModel()
112
+ exported_program = torch.export.export(model, (kv,))
113
+ input_specs = exported_program.graph_signature.input_specs
114
+ self.assertEqual(len(input_specs), 2)
115
+ self.assertEqual(input_specs[0].arg.name, "kv_k_0")
116
+ self.assertEqual(input_specs[1].arg.name, "kv_v_0")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ googletest.main()
@@ -16,16 +16,16 @@
16
16
 
17
17
  import os
18
18
  import tempfile
19
- import unittest
20
19
 
20
+ from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
21
+ from ai_edge_torch.generative.utilities import loader as loading_utils
21
22
  import safetensors.torch
22
23
  import torch
23
24
 
24
- from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
25
- from ai_edge_torch.generative.utilities import loader as loading_utils
25
+ from absl.testing import absltest as googletest
26
26
 
27
27
 
28
- class TestLoader(unittest.TestCase):
28
+ class TestLoader(googletest.TestCase):
29
29
  """Unit tests that check weight loader."""
30
30
 
31
31
  def test_load_safetensors(self):
@@ -59,7 +59,9 @@ class TestLoader(unittest.TestCase):
59
59
  "model.layers.0.mlp.down_proj.weight": torch.randn((2048, 5632)),
60
60
  "model.layers.0.mlp.gate_proj.weight": torch.randn((5632, 2048)),
61
61
  "model.layers.0.mlp.up_proj.weight": torch.randn((5632, 2048)),
62
- "model.layers.0.post_attention_layernorm.weight": torch.randn((2048,)),
62
+ "model.layers.0.post_attention_layernorm.weight": torch.randn((
63
+ 2048,
64
+ )),
63
65
  "model.layers.0.self_attn.k_proj.weight": torch.randn((256, 2048)),
64
66
  "model.layers.0.self_attn.o_proj.weight": torch.randn((2048, 2048)),
65
67
  "model.layers.0.self_attn.q_proj.weight": torch.randn((2048, 2048)),
@@ -69,7 +71,7 @@ class TestLoader(unittest.TestCase):
69
71
  safetensors.torch.save_file(test_weights, file_path)
70
72
  cfg = tiny_llama.get_model_config()
71
73
  cfg.num_layers = 1
72
- model = tiny_llama.TinyLLamma(cfg)
74
+ model = tiny_llama.TinyLlama(cfg)
73
75
 
74
76
  loader = loading_utils.ModelLoader(file_path, tiny_llama.TENSOR_NAMES)
75
77
  # if returns successfully, it means all the tensors were initiallized.
@@ -77,4 +79,4 @@ class TestLoader(unittest.TestCase):
77
79
 
78
80
 
79
81
  if __name__ == "__main__":
80
- unittest.main()
82
+ googletest.main()
@@ -12,224 +12,160 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- # Testing model conversion for a few gen-ai models.
16
- import copy
17
- import os
18
- import tempfile
19
- import unittest
20
15
 
21
- import numpy as np
22
- import torch
16
+ """Testing model conversion for a few gen-ai models."""
23
17
 
24
18
  import ai_edge_torch
25
- from ai_edge_torch.generative.examples.gemma import gemma
26
- from ai_edge_torch.generative.examples.phi2 import phi2
27
- from ai_edge_torch.generative.examples.test_models import toy_model_with_kv_cache # NOQA
19
+ from ai_edge_torch import config as ai_edge_config
20
+ from ai_edge_torch.generative.examples.test_models import toy_model_with_kv_cache
28
21
  from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
29
- from ai_edge_torch.testing import model_coverage
22
+ from ai_edge_torch.generative.layers import kv_cache
23
+ from ai_edge_torch.generative.test import utils as test_utils
24
+ import numpy as np
25
+ import torch
30
26
 
27
+ from absl.testing import absltest as googletest
28
+ from ai_edge_litert import interpreter
31
29
 
32
- class TestModelConversion(unittest.TestCase):
30
+
31
+ class TestModelConversion(googletest.TestCase):
33
32
  """Unit tests that check for model conversion and correctness."""
34
33
 
35
- def test_toy_model_with_kv_cache(self):
36
- config = toy_model_with_kv_cache.get_model_config()
37
- pytorch_model = toy_model_with_kv_cache.ToyModelWithKV(config)
38
- idx, input_pos = torch.tensor([[1]], dtype=torch.long), torch.tensor(
39
- [10], dtype=torch.int64
34
+ def setUp(self):
35
+ super().setUp()
36
+ # Builder function for an Interpreter that supports custom ops.
37
+ self._interpreter_builder = (
38
+ lambda tflite_model: lambda: interpreter.InterpreterWithCustomOps(
39
+ custom_op_registerers=["GenAIOpsRegisterer"],
40
+ model_content=tflite_model,
41
+ experimental_default_delegate_latest_features=True,
42
+ )
40
43
  )
41
44
 
42
- edge_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
43
-
44
- # TODO(b/338288901): re-enable test to check output tensors.
45
- skip_output_check = True
46
- if skip_output_check is False:
47
- self.assertTrue(
48
- model_coverage.compare_tflite_torch(
49
- edge_model,
50
- pytorch_model,
51
- (idx, input_pos),
52
- num_valid_inputs=1,
53
- atol=1e-5,
54
- rtol=1e-5,
55
- )
56
- )
57
-
58
- def test_toy_model_with_multi_batches(self):
59
- config = toy_model_with_kv_cache.get_model_config()
60
- config.batch_size = 2
61
- pytorch_model = toy_model_with_kv_cache.ToyModelWithKV(config)
62
- idx, input_pos = torch.tensor([[1], [2]], dtype=torch.long), torch.tensor(
63
- [10], dtype=torch.int64
45
+ def _test_model_with_kv_cache(self, config, pytorch_model):
46
+ tokens, input_pos = torch.tensor([[1]], dtype=torch.int), torch.tensor(
47
+ [10], dtype=torch.int
48
+ )
49
+ kv = kv_cache.KVCache.from_model_config(config)
50
+
51
+ edge_model = ai_edge_torch.convert(
52
+ pytorch_model,
53
+ sample_kwargs={
54
+ "tokens": tokens,
55
+ "input_pos": input_pos,
56
+ "kv_cache": kv,
57
+ },
58
+ )
59
+ edge_model.set_interpreter_builder(
60
+ self._interpreter_builder(edge_model.tflite_model())
64
61
  )
65
62
 
66
- edge_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
67
-
68
- # TODO(b/338288901): re-enable test to check output tensors.
69
- skip_output_check = True
70
- if skip_output_check is False:
71
- self.assertTrue(
72
- model_coverage.compare_tflite_torch(
73
- edge_model,
74
- pytorch_model,
75
- (idx, input_pos),
76
- num_valid_inputs=1,
77
- atol=1e-5,
78
- rtol=1e-5,
79
- )
80
- )
63
+ self.assertTrue(
64
+ test_utils.compare_tflite_torch(
65
+ edge_model,
66
+ pytorch_model,
67
+ tokens,
68
+ input_pos,
69
+ kv,
70
+ signature_name="serving_default",
71
+ atol=1e-5,
72
+ rtol=1e-5,
73
+ )
74
+ )
75
+
76
+ @googletest.skipIf(
77
+ ai_edge_config.Config.use_torch_xla,
78
+ reason="tests with custom ops are not supported on oss",
79
+ )
80
+ def test_toy_model_with_kv_cache(self):
81
+ config = toy_model_with_kv_cache.get_model_config()
82
+ pytorch_model = toy_model_with_kv_cache.ToyModelWithKVCache(config).eval()
83
+ self._test_model_with_kv_cache(config, pytorch_model)
81
84
 
85
+ @googletest.skipIf(
86
+ ai_edge_config.Config.use_torch_xla,
87
+ reason="tests with custom ops are not supported on oss",
88
+ )
82
89
  def test_toy_model_with_kv_cache_with_hlfb(self):
83
90
  config = toy_model_with_kv_cache.get_model_config()
84
91
  config.enable_hlfb = True
85
- pytorch_model = toy_model_with_kv_cache.ToyModelWithKV(config)
86
- idx, input_pos = torch.tensor([[1]], dtype=torch.long), torch.tensor(
87
- [10], dtype=torch.int64
88
- )
89
-
90
- edge_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
91
-
92
- # TODO(b/338288901): re-enable test to check output tensors.
93
- skip_output_check = True
94
- if skip_output_check is False:
95
- self.assertTrue(
96
- model_coverage.compare_tflite_torch(
97
- edge_model,
98
- pytorch_model,
99
- (idx, input_pos),
100
- num_valid_inputs=1,
101
- atol=1e-5,
102
- rtol=1e-5,
103
- )
104
- )
105
-
106
- def test_tiny_llama(self):
107
- self.skipTest("b/338288901")
108
- config = tiny_llama.get_fake_model_config_for_test()
109
- pytorch_model = tiny_llama.TinyLLamma(config)
110
-
111
- idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
112
- tokens = torch.full((1, 10), 0, dtype=torch.long, device="cpu")
113
- tokens[0, :4] = idx
114
- input_pos = torch.arange(0, 10)
115
-
116
- edge_model = ai_edge_torch.convert(pytorch_model, (tokens, input_pos))
117
-
118
- # TODO(b/338288901): re-enable test to check output tensors.
119
- skip_output_check = True
120
- if skip_output_check is False:
121
- self.assertTrue(
122
- model_coverage.compare_tflite_torch(
123
- edge_model,
124
- pytorch_model,
125
- (tokens, input_pos),
126
- num_valid_inputs=1,
127
- atol=1e-5,
128
- rtol=1e-5,
129
- )
130
- )
131
-
132
- def test_tiny_llama_multisig(self):
133
- config = tiny_llama.get_fake_model_config_for_test()
134
- pytorch_model = tiny_llama.TinyLLamma(config)
92
+ pytorch_model = toy_model_with_kv_cache.ToyModelWithKVCache(config).eval()
93
+ self._test_model_with_kv_cache(config, pytorch_model)
135
94
 
95
+ def _test_multisig_model(self, config, pytorch_model, atol, rtol):
136
96
  # prefill
137
97
  seq_len = 10
138
- prefill_tokens = torch.full((1, seq_len), 0, dtype=torch.long, device="cpu")
98
+ prefill_tokens = torch.full((1, seq_len), 0, dtype=torch.int, device="cpu")
139
99
  prompt_token = torch.from_numpy(np.array([1, 2, 3, 4]))
140
100
  prefill_tokens[0, : len(prompt_token)] = prompt_token
141
- prefill_input_pos = torch.arange(0, seq_len)
101
+ prefill_input_pos = torch.arange(0, seq_len, dtype=torch.int)
142
102
 
143
103
  # decode
144
- decode_token = torch.tensor([[1]], dtype=torch.long)
145
- decode_input_pos = torch.tensor([5], dtype=torch.int64)
104
+ decode_token = torch.tensor([[1]], dtype=torch.int)
105
+ decode_input_pos = torch.tensor([5], dtype=torch.int)
106
+
107
+ kv = kv_cache.KVCache.from_model_config(config)
146
108
 
147
109
  edge_model = (
148
110
  ai_edge_torch.signature(
149
- "prefill", pytorch_model, (prefill_tokens, prefill_input_pos)
111
+ "prefill",
112
+ pytorch_model,
113
+ sample_kwargs={
114
+ "tokens": prefill_tokens,
115
+ "input_pos": prefill_input_pos,
116
+ "kv_cache": kv,
117
+ },
118
+ )
119
+ .signature(
120
+ "decode",
121
+ pytorch_model,
122
+ sample_kwargs={
123
+ "tokens": decode_token,
124
+ "input_pos": decode_input_pos,
125
+ "kv_cache": kv,
126
+ },
150
127
  )
151
- .signature("decode", pytorch_model, (decode_token, decode_input_pos))
152
128
  .convert()
153
129
  )
130
+ edge_model.set_interpreter_builder(
131
+ self._interpreter_builder(edge_model.tflite_model())
132
+ )
154
133
 
155
- # TODO(b/338288901): re-enable test to check output tensors.
156
- skip_output_check = True
157
- if skip_output_check is False:
158
- copied_model = copy.deepcopy(pytorch_model)
159
-
160
- self.assertTrue(
161
- model_coverage.compare_tflite_torch(
162
- edge_model,
163
- pytorch_model,
164
- (prefill_tokens, prefill_input_pos),
165
- signature_name="prefill",
166
- num_valid_inputs=1,
167
- )
168
- )
169
-
170
- self.assertTrue(
171
- model_coverage.compare_tflite_torch(
172
- edge_model,
173
- copied_model,
174
- (decode_token, decode_input_pos),
175
- signature_name="decode",
176
- num_valid_inputs=1,
177
- )
178
- )
179
-
180
- def test_gemma(self):
181
- self.skipTest("b/338288901")
182
- config = gemma.get_fake_model_config_2b_for_test()
183
- model = gemma.Gemma(config)
184
-
185
- idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
186
- tokens = torch.full((1, 10), 0, dtype=torch.long, device="cpu")
187
- tokens[0, :4] = idx
188
- input_pos = torch.arange(0, 10)
189
-
190
- edge_model = ai_edge_torch.convert(model, (tokens, input_pos))
191
-
192
- # TODO(b/338288901): re-enable test to check output tensors.
193
- skip_output_check = True
194
- if skip_output_check is False:
195
- # TODO(talumbau, haoliang): debug numerical diff.
196
- self.assertTrue(
197
- model_coverage.compare_tflite_torch(
198
- edge_model,
199
- model,
200
- (tokens, input_pos),
201
- num_valid_inputs=1,
202
- atol=1e-2,
203
- rtol=1e-5,
204
- )
205
- )
206
-
207
- def test_phi2(self):
208
- self.skipTest("b/338288901")
209
- config = phi2.get_fake_model_config_for_test()
210
- pytorch_model = phi2.Phi2(config)
211
-
212
- idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
213
- tokens = torch.full((1, 10), 0, dtype=torch.long, device="cpu")
214
- tokens[0, :4] = idx
215
- input_pos = torch.arange(0, 10)
216
-
217
- edge_model = ai_edge_torch.convert(pytorch_model, (tokens, input_pos))
218
-
219
- # TODO(b/338288901): re-enable test to check output tensors.
220
- skip_output_check = True
221
- if skip_output_check is False:
222
- self.assertTrue(
223
- model_coverage.compare_tflite_torch(
224
- edge_model,
225
- pytorch_model,
226
- (tokens, input_pos),
227
- num_valid_inputs=1,
228
- atol=1e-5,
229
- rtol=1e-5,
230
- )
231
- )
134
+ self.assertTrue(
135
+ test_utils.compare_tflite_torch(
136
+ edge_model,
137
+ pytorch_model,
138
+ prefill_tokens,
139
+ prefill_input_pos,
140
+ kv,
141
+ signature_name="prefill",
142
+ atol=atol,
143
+ rtol=atol,
144
+ )
145
+ )
146
+
147
+ self.assertTrue(
148
+ test_utils.compare_tflite_torch(
149
+ edge_model,
150
+ pytorch_model,
151
+ decode_token,
152
+ decode_input_pos,
153
+ kv,
154
+ signature_name="decode",
155
+ atol=atol,
156
+ rtol=atol,
157
+ )
158
+ )
159
+
160
+ @googletest.skipIf(
161
+ ai_edge_config.Config.use_torch_xla,
162
+ reason="tests with custom ops are not supported on oss",
163
+ )
164
+ def test_tiny_llama_multisig(self):
165
+ config = tiny_llama.get_fake_model_config()
166
+ pytorch_model = tiny_llama.TinyLlama(config).eval()
167
+ self._test_multisig_model(config, pytorch_model, atol=1e-5, rtol=1e-5)
232
168
 
233
169
 
234
170
  if __name__ == "__main__":
235
- unittest.main()
171
+ googletest.main()