ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ai-edge-torch-nightly might be problematic. Click here for more details.

Files changed (121) hide show
  1. ai_edge_torch/__init__.py +31 -0
  2. ai_edge_torch/convert/__init__.py +14 -0
  3. ai_edge_torch/convert/conversion.py +117 -0
  4. ai_edge_torch/convert/conversion_utils.py +400 -0
  5. ai_edge_torch/convert/converter.py +202 -0
  6. ai_edge_torch/convert/fx_passes/__init__.py +59 -0
  7. ai_edge_torch/convert/fx_passes/_pass_base.py +49 -0
  8. ai_edge_torch/convert/fx_passes/build_aten_composite_pass.py +225 -0
  9. ai_edge_torch/convert/fx_passes/build_interpolate_composite_pass.py +123 -0
  10. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +37 -0
  11. ai_edge_torch/convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
  12. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
  13. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +215 -0
  14. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +48 -0
  15. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +17 -0
  16. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +59 -0
  17. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +215 -0
  18. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +400 -0
  19. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
  20. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +293 -0
  21. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/utils.py +62 -0
  22. ai_edge_torch/convert/test/__init__.py +14 -0
  23. ai_edge_torch/convert/test/test_convert.py +311 -0
  24. ai_edge_torch/convert/test/test_convert_composites.py +192 -0
  25. ai_edge_torch/convert/test/test_convert_multisig.py +139 -0
  26. ai_edge_torch/convert/test/test_to_channel_last_io.py +96 -0
  27. ai_edge_torch/convert/to_channel_last_io.py +85 -0
  28. ai_edge_torch/debug/__init__.py +17 -0
  29. ai_edge_torch/debug/culprit.py +464 -0
  30. ai_edge_torch/debug/test/__init__.py +14 -0
  31. ai_edge_torch/debug/test/test_culprit.py +133 -0
  32. ai_edge_torch/debug/test/test_search_model.py +50 -0
  33. ai_edge_torch/debug/utils.py +48 -0
  34. ai_edge_torch/experimental/__init__.py +14 -0
  35. ai_edge_torch/generative/__init__.py +14 -0
  36. ai_edge_torch/generative/examples/__init__.py +14 -0
  37. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  38. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +66 -0
  39. ai_edge_torch/generative/examples/gemma/gemma.py +174 -0
  40. ai_edge_torch/generative/examples/phi2/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +64 -0
  42. ai_edge_torch/generative/examples/phi2/phi2.py +164 -0
  43. ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
  44. ai_edge_torch/generative/examples/stable_diffusion/attention.py +106 -0
  45. ai_edge_torch/generative/examples/stable_diffusion/clip.py +115 -0
  46. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +142 -0
  47. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +317 -0
  48. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +573 -0
  49. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +118 -0
  50. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +222 -0
  51. ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
  52. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +61 -0
  53. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +65 -0
  54. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +73 -0
  55. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +38 -0
  56. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +108 -0
  57. ai_edge_torch/generative/examples/stable_diffusion/util.py +71 -0
  58. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  59. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +135 -0
  60. ai_edge_torch/generative/examples/t5/t5.py +608 -0
  61. ai_edge_torch/generative/examples/t5/t5_attention.py +231 -0
  62. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  63. ai_edge_torch/generative/examples/test_models/toy_model.py +122 -0
  64. ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +161 -0
  65. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +143 -0
  66. ai_edge_torch/generative/examples/tiny_llama/__init__.py +0 -0
  67. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +66 -0
  68. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +164 -0
  69. ai_edge_torch/generative/fx_passes/__init__.py +31 -0
  70. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +47 -0
  71. ai_edge_torch/generative/layers/__init__.py +14 -0
  72. ai_edge_torch/generative/layers/attention.py +354 -0
  73. ai_edge_torch/generative/layers/attention_utils.py +169 -0
  74. ai_edge_torch/generative/layers/builder.py +131 -0
  75. ai_edge_torch/generative/layers/feed_forward.py +95 -0
  76. ai_edge_torch/generative/layers/kv_cache.py +83 -0
  77. ai_edge_torch/generative/layers/model_config.py +158 -0
  78. ai_edge_torch/generative/layers/normalization.py +62 -0
  79. ai_edge_torch/generative/layers/rotary_position_embedding.py +36 -0
  80. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +117 -0
  81. ai_edge_torch/generative/layers/unet/__init__.py +14 -0
  82. ai_edge_torch/generative/layers/unet/blocks_2d.py +711 -0
  83. ai_edge_torch/generative/layers/unet/builder.py +47 -0
  84. ai_edge_torch/generative/layers/unet/model_config.py +269 -0
  85. ai_edge_torch/generative/quantize/__init__.py +14 -0
  86. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
  87. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/translate_recipe.py +148 -0
  88. ai_edge_torch/generative/quantize/example.py +45 -0
  89. ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
  90. ai_edge_torch/generative/quantize/quant_recipe.py +151 -0
  91. ai_edge_torch/generative/quantize/quant_recipe_utils.py +51 -0
  92. ai_edge_torch/generative/quantize/quant_recipes.py +48 -0
  93. ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
  94. ai_edge_torch/generative/test/__init__.py +14 -0
  95. ai_edge_torch/generative/test/loader_test.py +80 -0
  96. ai_edge_torch/generative/test/test_model_conversion.py +235 -0
  97. ai_edge_torch/generative/test/test_quantize.py +162 -0
  98. ai_edge_torch/generative/utilities/__init__.py +15 -0
  99. ai_edge_torch/generative/utilities/loader.py +328 -0
  100. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +924 -0
  101. ai_edge_torch/generative/utilities/t5_loader.py +483 -0
  102. ai_edge_torch/hlfb/__init__.py +16 -0
  103. ai_edge_torch/hlfb/mark_pattern/__init__.py +139 -0
  104. ai_edge_torch/hlfb/mark_pattern/passes.py +42 -0
  105. ai_edge_torch/hlfb/mark_pattern/pattern.py +273 -0
  106. ai_edge_torch/hlfb/test/__init__.py +14 -0
  107. ai_edge_torch/hlfb/test/test_mark_pattern.py +133 -0
  108. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +270 -0
  109. ai_edge_torch/model.py +142 -0
  110. ai_edge_torch/quantize/__init__.py +16 -0
  111. ai_edge_torch/quantize/pt2e_quantizer.py +438 -0
  112. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1041 -0
  113. ai_edge_torch/quantize/quant_config.py +81 -0
  114. ai_edge_torch/testing/__init__.py +14 -0
  115. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  116. ai_edge_torch/testing/model_coverage/model_coverage.py +132 -0
  117. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/LICENSE +202 -0
  118. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/METADATA +38 -0
  119. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +121 -0
  120. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/WHEEL +5 -0
  121. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/top_level.txt +1 -0
@@ -0,0 +1,66 @@
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
+ import os
17
+ from pathlib import Path
18
+
19
+ import torch
20
+
21
+ import ai_edge_torch
22
+ from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
23
+ from ai_edge_torch.generative.quantize import quant_recipes
24
+
25
+
26
+ def convert_tiny_llama_to_tflite(
27
+ checkpoint_path: str,
28
+ prefill_seq_len: int = 512,
29
+ kv_cache_max_len: int = 1024,
30
+ quantize: bool = True,
31
+ ):
32
+ """An example method for converting TinyLlama model to multi-signature
33
+ tflite model.
34
+
35
+ Args:
36
+ checkpoint_path (str): The filepath to the model checkpoint, or directory holding the checkpoint.
37
+ prefill_seq_len (int, optional): The maximum size of prefill input tensor.
38
+ Defaults to 512.
39
+ kv_cache_max_len (int, optional): The maximum size of KV cache buffer,
40
+ including both prefill and decode. Defaults to 1024.
41
+ quantize (bool, optional): Whether the model should be quanized.
42
+ Defaults to True.
43
+ """
44
+ pytorch_model = tiny_llama.build_model(
45
+ checkpoint_path, kv_cache_max_len=kv_cache_max_len
46
+ )
47
+ # Tensors used to trace the model graph during conversion.
48
+ prefill_tokens = torch.full((1, prefill_seq_len), 0, dtype=torch.long)
49
+ prefill_input_pos = torch.arange(0, prefill_seq_len)
50
+ decode_token = torch.tensor([[0]], dtype=torch.long)
51
+ decode_input_pos = torch.tensor([0], dtype=torch.int64)
52
+
53
+ quant_config = quant_recipes.full_int8_dynamic_recipe() if quantize else None
54
+ edge_model = (
55
+ ai_edge_torch.signature(
56
+ 'prefill', pytorch_model, (prefill_tokens, prefill_input_pos)
57
+ )
58
+ .signature('decode', pytorch_model, (decode_token, decode_input_pos))
59
+ .convert(quant_config=quant_config)
60
+ )
61
+ edge_model.export(f'/tmp/tiny_llama_seq{prefill_seq_len}_kv{kv_cache_max_len}.tflite')
62
+
63
+
64
+ if __name__ == '__main__':
65
+ checkpoint_path = os.path.join(Path.home(), 'Downloads/llm_data/tiny_llama')
66
+ convert_tiny_llama_to_tflite(checkpoint_path)
@@ -0,0 +1,164 @@
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
+ # Example of building a TinyLlama model from the Edge Generative API layers.
16
+
17
+ import os
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from ai_edge_torch.generative.layers.attention import TransformerBlock
25
+ import ai_edge_torch.generative.layers.attention_utils as attn_utils
26
+ import ai_edge_torch.generative.layers.builder as builder
27
+ import ai_edge_torch.generative.layers.model_config as cfg
28
+ import ai_edge_torch.generative.utilities.loader as loading_utils
29
+
30
+ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
31
+ ff_up_proj="model.layers.{}.mlp.up_proj",
32
+ ff_down_proj="model.layers.{}.mlp.down_proj",
33
+ ff_gate_proj="model.layers.{}.mlp.gate_proj",
34
+ attn_query_proj="model.layers.{}.self_attn.q_proj",
35
+ attn_key_proj="model.layers.{}.self_attn.k_proj",
36
+ attn_value_proj="model.layers.{}.self_attn.v_proj",
37
+ attn_output_proj="model.layers.{}.self_attn.o_proj",
38
+ pre_attn_norm="model.layers.{}.input_layernorm",
39
+ pre_ff_norm="model.layers.{}.post_attention_layernorm",
40
+ embedding="model.embed_tokens",
41
+ final_norm="model.norm",
42
+ lm_head="lm_head",
43
+ )
44
+
45
+
46
+ class TinyLLamma(nn.Module):
47
+
48
+ def __init__(self, config: cfg.ModelConfig):
49
+ super().__init__()
50
+
51
+ self.config = config
52
+ # Construct model layers.
53
+ self.lm_head = nn.Linear(
54
+ config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
55
+ )
56
+ self.tok_embedding = nn.Embedding(
57
+ config.vocab_size, config.embedding_dim, padding_idx=0
58
+ )
59
+ self.transformer_blocks = nn.ModuleList(
60
+ TransformerBlock(config) for _ in range(config.num_layers)
61
+ )
62
+ self.final_norm = builder.build_norm(
63
+ config.embedding_dim,
64
+ config.final_norm_config,
65
+ )
66
+ self.rope_cache = attn_utils.build_rope_cache(
67
+ size=config.kv_cache_max,
68
+ dim=int(config.attn_config.rotary_percentage * config.head_dim),
69
+ base=10_000,
70
+ condense_ratio=1,
71
+ dtype=torch.float32,
72
+ device=torch.device("cpu"),
73
+ )
74
+ self.mask_cache = attn_utils.build_causal_mask_cache(
75
+ size=config.kv_cache_max, dtype=torch.float32, device=torch.device("cpu")
76
+ )
77
+ self.config = config
78
+
79
+ # The model's forward function takes in additional k/v cache tensors
80
+ # and returns the updated k/v cache tensors to the caller.
81
+ # This can be eliminated if we handle k/v cache updates inside the model itself.
82
+ @torch.inference_mode
83
+ def forward(self, idx: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
84
+ B, T = idx.size()
85
+ assert (
86
+ self.config.max_seq_len >= T
87
+ ), f"Cannot forward sequence of length {T}, max seq length is only {self.config.max_seq_len}"
88
+
89
+ cos, sin = self.rope_cache
90
+ cos = cos.index_select(0, input_pos)
91
+ sin = sin.index_select(0, input_pos)
92
+ mask = self.mask_cache.index_select(2, input_pos)
93
+ mask = mask[:, :, :, : self.config.kv_cache_max]
94
+
95
+ # forward the model itself
96
+ x = self.tok_embedding(idx) # token embeddings of shape (b, t, n_embd)
97
+
98
+ for i, block in enumerate(self.transformer_blocks):
99
+ x = block(x, (cos, sin), mask, input_pos)
100
+
101
+ x = self.final_norm(x)
102
+
103
+ res = self.lm_head(x) # (b, t, vocab_size)
104
+ return res
105
+
106
+
107
+ def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
108
+ attn_config = cfg.AttentionConfig(
109
+ num_heads=32,
110
+ num_query_groups=4,
111
+ rotary_percentage=1.0,
112
+ )
113
+ ff_config = cfg.FeedForwardConfig(
114
+ type=cfg.FeedForwardType.GATED,
115
+ activation=cfg.ActivationConfig(cfg.ActivationType.SILU),
116
+ intermediate_size=5632,
117
+ )
118
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
119
+ config = cfg.ModelConfig(
120
+ vocab_size=32000,
121
+ num_layers=22,
122
+ max_seq_len=2048,
123
+ embedding_dim=2048,
124
+ kv_cache_max_len=kv_cache_max_len,
125
+ attn_config=attn_config,
126
+ ff_config=ff_config,
127
+ pre_attention_norm_config=norm_config,
128
+ pre_ff_norm_config=norm_config,
129
+ final_norm_config=norm_config,
130
+ enable_hlfb=True,
131
+ )
132
+ return config
133
+
134
+
135
+ def get_fake_model_config_for_test() -> cfg.ModelConfig:
136
+ config = get_model_config()
137
+ config.vocab_size = 128
138
+ config.num_layers = 2
139
+ config.ff_config.intermediate_size = 256
140
+ return config
141
+
142
+
143
+ def build_model(checkpoint_path, **kwargs) -> nn.Module:
144
+ config = get_model_config(**kwargs)
145
+ model = TinyLLamma(config)
146
+ loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
147
+ loader.load(model)
148
+ return model
149
+
150
+
151
+ def define_and_run() -> None:
152
+ kv_cache_max_len = 1024
153
+ checkpoint_path = os.path.join(Path.home(), "Downloads/llm_data/tiny_llama")
154
+ model = build_model(checkpoint_path, kv_cache_max_len=kv_cache_max_len)
155
+ idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
156
+ tokens = torch.full((1, kv_cache_max_len), 0, dtype=torch.long, device="cpu")
157
+ tokens[0, :4] = idx
158
+ input_pos = torch.arange(0, kv_cache_max_len)
159
+ print("running an inference")
160
+ print(model.forward(tokens, input_pos))
161
+
162
+
163
+ if __name__ == "__main__":
164
+ define_and_run()
@@ -0,0 +1,31 @@
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
+ import torch
16
+
17
+ from ai_edge_torch.convert.fx_passes import CanonicalizePass
18
+ from ai_edge_torch.convert.fx_passes import run_passes
19
+ from ai_edge_torch.generative.fx_passes.remove_sdpa_zero_mask_pass import RemoveSDPACompositeZeroMaskPass # NOQA
20
+
21
+
22
+ def run_generative_passes(
23
+ exported_program: torch.export.ExportedProgram,
24
+ ) -> torch.export.ExportedProgram:
25
+ return run_passes(
26
+ exported_program,
27
+ [
28
+ RemoveSDPACompositeZeroMaskPass(),
29
+ CanonicalizePass(),
30
+ ],
31
+ )
@@ -0,0 +1,47 @@
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
+ import torch
16
+
17
+ from ai_edge_torch.convert.fx_passes._pass_base import ExportedProgramPassBase
18
+ from ai_edge_torch.convert.fx_passes._pass_base import ExportedProgramPassResult # NOQA
19
+
20
+
21
+ class RemoveSDPACompositeZeroMaskPass(ExportedProgramPassBase):
22
+
23
+ def is_zero_tensor_node(self, node: torch.fx.Node):
24
+ return node.target == torch.ops.aten.zeros.default
25
+
26
+ def call(self, exported_program: torch.export.ExportedProgram):
27
+ graph = exported_program.graph_module.graph
28
+ for node in graph.nodes:
29
+ if not (
30
+ node.op == "call_function"
31
+ and node.target == torch.ops.xla.mark_tensor.default
32
+ ):
33
+ continue
34
+
35
+ source, name, io_position, id, is_input = node.args[:5]
36
+ # Composite info:
37
+ # - name: odml.scaled_dot_product_attention
38
+ # - inputs: q, k, v, mask
39
+ if name == "odml.scaled_dot_product_attention" and is_input and io_position == 3:
40
+ if self.is_zero_tensor_node(source):
41
+ # Remove the mark_tensor call on the mask input by
42
+ # replacing the target with an identity function.
43
+ node.target = lambda *args, **kwargs: torch.zeros_like(args[0])
44
+
45
+ exported_program.graph_module.graph.lint()
46
+ exported_program.graph_module.recompile()
47
+ return ExportedProgramPassResult(exported_program, True)
@@ -0,0 +1,14 @@
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
+ # ==============================================================================
@@ -0,0 +1,354 @@
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
+ # Common building blocks for Attention layer.
16
+
17
+ from typing import Optional, Tuple
18
+
19
+ import torch
20
+ from torch import nn
21
+ import torch.nn.functional as F
22
+
23
+ import ai_edge_torch.generative.layers.builder as builder
24
+ from ai_edge_torch.generative.layers.kv_cache import KVCache
25
+ import ai_edge_torch.generative.layers.model_config as cfg
26
+ import ai_edge_torch.generative.layers.rotary_position_embedding as rotary_pos_emb
27
+ from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention # NOQA
28
+ from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention_with_hlfb # NOQA
29
+
30
+
31
+ def _embed_rope(
32
+ q: torch.Tensor,
33
+ k: torch.Tensor,
34
+ n_elem: int,
35
+ rope: Tuple[torch.Tensor, torch.Tensor],
36
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
37
+ """Embed rotary positional embedding for query and key.
38
+
39
+ Args:
40
+ q (torch.Tensor): query tensor.
41
+ k (torch.Tensor): key tensor.
42
+ n_elem (int): number of elements to embed rotarty positional embedding.
43
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
44
+ """
45
+ if n_elem > 0:
46
+ cos, sin = rope
47
+ q_roped = rotary_pos_emb.apply_rope(
48
+ q[..., :n_elem], cos.repeat(1, 2), sin.repeat(1, 2)
49
+ )
50
+ k_roped = rotary_pos_emb.apply_rope(
51
+ k[..., :n_elem], cos.repeat(1, 2), sin.repeat(1, 2)
52
+ )
53
+ q = torch.cat((q_roped, q[..., n_elem:]), dim=-1)
54
+ k = torch.cat((k_roped, k[..., n_elem:]), dim=-1)
55
+ return q, k
56
+
57
+
58
+ class TransformerBlock(nn.Module):
59
+
60
+ def __init__(self, config: cfg.ModelConfig) -> None:
61
+ """Initialize an instance of the TransformerBlock.
62
+
63
+ Args:
64
+ config (cfg.ModelConfig): the configuration object
65
+ for this transformer block.
66
+ """
67
+
68
+ super().__init__()
69
+ self.pre_atten_norm = builder.build_norm(
70
+ config.embedding_dim, config.pre_attention_norm_config
71
+ )
72
+ self.atten_func = CausalSelfAttention(
73
+ config.batch_size,
74
+ config.embedding_dim,
75
+ config.attn_config,
76
+ config.kv_cache_max,
77
+ config.enable_hlfb,
78
+ )
79
+ self.pre_ff_norm = builder.build_norm(
80
+ config.embedding_dim, config.pre_ff_norm_config
81
+ )
82
+ self.ff = builder.build_ff(config.embedding_dim, config.ff_config)
83
+ self.config = config
84
+
85
+ def forward(
86
+ self,
87
+ x: torch.Tensor,
88
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
89
+ mask: Optional[torch.Tensor] = None,
90
+ input_pos: Optional[torch.Tensor] = None,
91
+ ) -> torch.Tensor:
92
+ """Forward function of the TransformerBlock.
93
+
94
+ Args:
95
+ x (torch.Tensor): the input tensor.
96
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
97
+ mask (torch.Tensor): the optional mask tensor.
98
+ input_pos (torch.Tensor): the optional input position tensor.
99
+
100
+ Returns:
101
+ output activation from this transformer block.
102
+ """
103
+
104
+ if self.config.parallel_residual:
105
+ x_norm = self.pre_atten_norm(x)
106
+ attn_out = self.atten_func(x_norm, rope, mask, input_pos)
107
+ ff_out = self.ff(x_norm)
108
+ output = x + attn_out + ff_out
109
+ else:
110
+ x_norm = self.pre_atten_norm(x)
111
+ attn_out = self.atten_func(x_norm, rope, mask, input_pos)
112
+ x = x + attn_out
113
+ x_norm = self.pre_ff_norm(x)
114
+ output = x + self.ff(x_norm)
115
+
116
+ return output
117
+
118
+
119
+ class CausalSelfAttention(nn.Module):
120
+
121
+ def __init__(
122
+ self,
123
+ batch_size: int,
124
+ dim: int,
125
+ config: cfg.AttentionConfig,
126
+ kv_cache_max: int,
127
+ enable_hlfb: bool,
128
+ ) -> None:
129
+ """Initialize an instance of CausalSelfAttention.
130
+
131
+ Args:
132
+ batch_size (int): batch size of the input tensor.
133
+ dim (int): causal attention's input/output dimmension.
134
+ config (cfg.AttentionConfig): attention specific configurations.
135
+ kv_cache_max (int): determines the size of the KV Cache buffer, if enabled.
136
+ enable_hlfb (bool): whether hlfb is enabled or not.
137
+ """
138
+ super().__init__()
139
+ self.head_dim = dim // config.num_heads
140
+ shape = (config.num_heads + 2 * config.num_query_groups) * self.head_dim
141
+ # Key, query, value projections for all heads.
142
+ self.qkv_projection = nn.Linear(dim, shape, bias=config.qkv_use_bias)
143
+ self.output_projection = nn.Linear(dim, dim, bias=config.output_proj_use_bias)
144
+ self.config = config
145
+ self.kv_cache = None
146
+ self.batch_size = batch_size
147
+
148
+ # Build a k/v cache with size (batch_size, kv_cache_max, n_heads, head_dim).
149
+ if config.enable_kv_cache:
150
+ self.kv_cache = KVCache(
151
+ batch_size,
152
+ kv_cache_max,
153
+ config.num_query_groups,
154
+ self.head_dim,
155
+ enable_hlfb,
156
+ )
157
+
158
+ if enable_hlfb:
159
+ self.sdpa_func = scaled_dot_product_attention_with_hlfb
160
+ else:
161
+ self.sdpa_func = scaled_dot_product_attention
162
+
163
+ def forward(
164
+ self,
165
+ x: torch.Tensor,
166
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
167
+ mask: Optional[torch.Tensor] = None,
168
+ input_pos: Optional[torch.Tensor] = None,
169
+ ) -> torch.Tensor:
170
+ """Forward function of the CausalSelfAttention layer, which can support
171
+ MQA, GQA and MHA.
172
+
173
+ Args:
174
+ x (torch.Tensor): the input tensor.
175
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
176
+ mask (torch.Tensor): the optional mask tensor.
177
+ input_pos (torch.Tensor): the optional input position tensor.
178
+
179
+ Returns:
180
+ output activation from this self attention layer.
181
+ """
182
+ # Batch size, sequence length, embedding dimensionality.
183
+ B, T, E = x.size()
184
+ assert (
185
+ B == self.batch_size
186
+ ), "batch size of input tensor must match with the batch size specified in the model configuration."
187
+
188
+ qkv = self.qkv_projection(x)
189
+
190
+ # Assemble into a number of query groups to support MHA, MQA and GQA.
191
+ q_per_kv = self.config.num_heads // self.config.num_query_groups
192
+ # Each group has >=1 queries, 1 key, and 1 value.
193
+ if self.config.qkv_transpose_before_split:
194
+ qkv = qkv.view(B, T, -1, self.head_dim)
195
+ q, k, v = qkv.split(
196
+ (
197
+ q_per_kv * self.config.num_query_groups,
198
+ self.config.num_query_groups,
199
+ self.config.num_query_groups,
200
+ ),
201
+ dim=-2,
202
+ )
203
+ else:
204
+ qkv = qkv.view(B, T, self.config.num_query_groups, -1)
205
+ q, k, v = qkv.split(
206
+ (q_per_kv * self.head_dim, self.head_dim, self.head_dim), dim=-1
207
+ )
208
+
209
+ q = q.reshape(B, T, -1, self.head_dim)
210
+ k = k.reshape(B, T, -1, self.head_dim)
211
+ v = v.reshape(B, T, -1, self.head_dim)
212
+
213
+ # Compute rotary positional embedding for query and key.
214
+ n_elem = int(self.config.rotary_percentage * self.head_dim)
215
+ q, k = _embed_rope(q, k, n_elem, rope)
216
+
217
+ if self.kv_cache is not None:
218
+ # TODO(haoliang): Handle when execeeding max sequence length.
219
+ k, v = self.kv_cache.update_cache(input_pos, k, v)
220
+
221
+ y = self.sdpa_func(q, k, v, self.head_dim, mask=mask)
222
+ y = y.reshape(B, T, E)
223
+
224
+ # Compute the output projection.
225
+ y = self.output_projection(y)
226
+ return y
227
+
228
+
229
+ class SelfAttention(CausalSelfAttention):
230
+ """Non-causal Self Attention module, which is equivalent to CausalSelfAttention without mask."""
231
+
232
+ def forward(
233
+ self,
234
+ x: torch.Tensor,
235
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
236
+ input_pos: Optional[torch.Tensor] = None,
237
+ ) -> torch.Tensor:
238
+ """Forward function of the SelfAttention layer, which can support MQA, GQA and MHA.
239
+
240
+ Args:
241
+ x (torch.Tensor): the input tensor.
242
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
243
+ input_pos (torch.Tensor): the optional input position tensor.
244
+
245
+ Returns:
246
+ output activation from this self attention layer.
247
+ """
248
+ B, T, _ = x.size()
249
+ return super().forward(
250
+ x,
251
+ rope=rope,
252
+ mask=torch.zeros((B, 1, T, T), dtype=torch.float32),
253
+ input_pos=input_pos,
254
+ )
255
+
256
+
257
+ class CrossAttention(nn.Module):
258
+
259
+ def __init__(
260
+ self,
261
+ batch_size: int,
262
+ query_dim: int,
263
+ cross_dim: int,
264
+ config: cfg.AttentionConfig,
265
+ kv_cache_max: int,
266
+ enable_hlfb: bool,
267
+ ) -> None:
268
+ """Initialize an instance of CrossAttention.
269
+
270
+ Args:
271
+ batch_size (int): batch size of the input tensor.
272
+ query_dim (int): query tensor's dimension.
273
+ cross_dim (int): cross attention's dimensions, for key and value tensors.
274
+ config (cfg.AttentionConfig): attention specific configurations.
275
+ kv_cache_max (int): determines the size of the KV Cache buffer, if enabled.
276
+ enable_hlfb (bool): whether hlfb is enabled or not.
277
+ """
278
+ super().__init__()
279
+ self.config = config
280
+ self.head_dim = query_dim // config.num_heads
281
+ self.n_heads = config.num_heads
282
+ self.q_projection = nn.Linear(query_dim, query_dim, bias=config.qkv_use_bias)
283
+ self.k_projection = nn.Linear(cross_dim, query_dim, bias=config.qkv_use_bias)
284
+ self.v_projection = nn.Linear(cross_dim, query_dim, bias=config.qkv_use_bias)
285
+ self.output_projection = nn.Linear(
286
+ query_dim, query_dim, bias=config.output_proj_use_bias
287
+ )
288
+
289
+ self.kv_cache = None
290
+ # Build a k/v cache with size (batch_size, kv_cache_max, n_heads, head_dim).
291
+ if config.enable_kv_cache:
292
+ self.kv_cache = KVCache(
293
+ batch_size,
294
+ kv_cache_max,
295
+ config.num_query_groups,
296
+ self.head_dim,
297
+ enable_hlfb,
298
+ )
299
+
300
+ if enable_hlfb:
301
+ self.sdpa_func = scaled_dot_product_attention_with_hlfb
302
+ else:
303
+ self.sdpa_func = scaled_dot_product_attention
304
+
305
+ def forward(
306
+ self,
307
+ x: torch.Tensor,
308
+ y: torch.Tensor,
309
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
310
+ mask: Optional[torch.Tensor] = None,
311
+ input_pos: Optional[torch.Tensor] = None,
312
+ ):
313
+ """Forward function of the CrossAttention layer.
314
+
315
+ Args:
316
+ x (torch.Tensor): the target tensor, with shape [B, target_seq_len, ...].
317
+ y (torch.Tensor): the source tensor, with shape [B, source_seq_len, ...].
318
+ rope (Tuple[torch.Tensor, torch.Tensor]): the optional input rope tensor.
319
+ mask (torch.Tensor): the optional mask tensor can be broadcaseted to shape [B, n_heads, target_seq_len, source_seq_len].
320
+ input_pos (torch.Tensor): the optional input position tensor.
321
+
322
+ Returns:
323
+ output activation from this cross attention layer.
324
+ """
325
+ batch_size = x.size()[0]
326
+ target_seq_len = x.size()[1]
327
+ source_seq_len = y.size()[1]
328
+
329
+ q = self.q_projection(x)
330
+ k = self.k_projection(y)
331
+ v = self.v_projection(y)
332
+
333
+ interim_shape = (batch_size, -1, self.n_heads, self.head_dim)
334
+ q = q.view(interim_shape)
335
+ k = k.view(interim_shape)
336
+ v = v.view(interim_shape)
337
+
338
+ # Compute rotary positional embedding for query and key.
339
+ n_elem = int(self.config.rotary_percentage * self.head_dim)
340
+ q, k = _embed_rope(q, k, n_elem, rope)
341
+
342
+ if self.kv_cache is not None:
343
+ # TODO(haoliang): Handle when execeeding max sequence length.
344
+ k, v = self.kv_cache.update_cache(input_pos, k, v)
345
+ if mask is None:
346
+ mask = torch.zeros(
347
+ (batch_size, 1, target_seq_len, source_seq_len), dtype=torch.float32
348
+ )
349
+ y = self.sdpa_func(q, k, v, self.head_dim, mask=mask)
350
+ y = y.reshape(batch_size, target_seq_len, -1)
351
+
352
+ # Compute the output projection.
353
+ y = self.output_projection(y)
354
+ return y