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,169 @@
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 utility functions used with attention module.
16
+
17
+ import math
18
+ from typing import Tuple
19
+
20
+ import torch
21
+
22
+
23
+ def build_rope_cache(
24
+ size: int,
25
+ dim: int,
26
+ base: int = 10000,
27
+ condense_ratio: int = 1,
28
+ dtype: torch.dtype = torch.float32,
29
+ device: torch.device = None,
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """Precompute Rotary Positional Embedding Sin and Cos values for quick lookups
32
+ during the inference.
33
+
34
+ Args:
35
+ size (int): The size of the built cache.
36
+ dim (int): Each sequence's dimmension.
37
+ base (int, optional): Rope base value. Defaults to 10000.
38
+ condense_ratio (int, optional): The ratio by which sequence indicies are
39
+ condensed. Defaults to 1.
40
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
41
+ torch.float32.
42
+ device (torch.device, optional): Output tensor's data type. Defaults to
43
+ None in which case "cpu" is used.
44
+
45
+ Returns:
46
+ Tuple[torch.Tensor, torch.Tensor]: Rope's Cosine and Sine waves.
47
+ """
48
+ if device is None:
49
+ device = torch.device('cpu')
50
+ theta = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
51
+ seq_idx = torch.arange(size) / condense_ratio
52
+ idx_theta = torch.outer(seq_idx, theta)
53
+ cos = torch.cos(idx_theta).to(dtype=dtype, device=device)
54
+ sin = torch.sin(idx_theta).to(dtype=dtype, device=device)
55
+ return cos, sin
56
+
57
+
58
+ def build_causal_mask_cache(
59
+ size: int,
60
+ dtype: torch.dtype = torch.float32,
61
+ device: torch.device = None,
62
+ ) -> torch.Tensor:
63
+ """Build a cache for causal attention mask.
64
+
65
+ Args:
66
+ size (int): The size of the built mask cache.
67
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
68
+ torch.float32.
69
+ device (torch.device, optional): Output tensor's data type. Defaults to
70
+ None in which case "cpu" is used.
71
+
72
+ Returns:
73
+ torch.Tensor: Causal attention mask.
74
+ """
75
+ if device is None:
76
+ device = torch.device('cpu')
77
+ mask = torch.full((size, size), float('-inf'), dtype=dtype, device=device)
78
+ return torch.triu(mask, diagonal=1).unsqueeze(0).unsqueeze(0)
79
+
80
+
81
+ def relative_position_bucket(
82
+ relative_position: torch.Tensor,
83
+ bidirectional: bool,
84
+ num_buckets: int,
85
+ max_distance: int,
86
+ ) -> torch.Tensor:
87
+ """
88
+ Adapted from Mesh Tensorflow:
89
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
90
+
91
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
92
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
93
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
94
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
95
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
96
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
97
+
98
+ Args:
99
+ relative_position: an int32 Tensor
100
+ bidirectional: a boolean - whether the attention is bidirectional
101
+ num_buckets: an integer for number of buckets.
102
+ max_distance: an integer for max distance.
103
+
104
+ Returns:
105
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
106
+ """
107
+ relative_buckets = 0
108
+ if bidirectional:
109
+ num_buckets //= 2
110
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
111
+ relative_position = torch.abs(relative_position)
112
+ else:
113
+ relative_position = -torch.min(
114
+ relative_position, torch.zeros_like(relative_position)
115
+ )
116
+ # now relative_position is in the range [0, inf)
117
+
118
+ # half of the buckets are for exact increments in positions
119
+ max_exact = num_buckets // 2
120
+ is_small = relative_position < max_exact
121
+
122
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
123
+ relative_position_if_large = max_exact + (
124
+ torch.log(relative_position.float() / max_exact)
125
+ / math.log(max_distance / max_exact)
126
+ * (num_buckets - max_exact)
127
+ ).to(torch.long)
128
+ relative_position_if_large = torch.min(
129
+ relative_position_if_large,
130
+ torch.full_like(relative_position_if_large, num_buckets - 1),
131
+ )
132
+
133
+ relative_buckets += torch.where(
134
+ is_small, relative_position, relative_position_if_large
135
+ )
136
+ return relative_buckets
137
+
138
+
139
+ def build_relative_position_buckets(
140
+ query_length: int,
141
+ key_length: int,
142
+ bidirectional: bool = True,
143
+ num_buckets: int = 32,
144
+ max_distance: int = 128,
145
+ ) -> torch.Tensor:
146
+ """Relative position buckets for computing bias.
147
+
148
+ Args:
149
+ query_length: an integer of length of current query tensor.
150
+ key_length: an integer of length of current key tensor.
151
+ bidirectional: a boolean - whether the attention is bidirectional, default is True.
152
+ num_buckets: an integer for number of buckets, default is 32.
153
+ max_distance: an integer for max distance, default is 128.
154
+
155
+ Returns:
156
+ A torch.Tensor of computed relative position buckets.
157
+ """
158
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
159
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
160
+ relative_position = (
161
+ memory_position - context_position
162
+ ) # shape (query_length, key_length)
163
+ rel_pos_bucket = relative_position_bucket(
164
+ relative_position, # shape (query_length, key_length)
165
+ bidirectional=bidirectional,
166
+ num_buckets=num_buckets,
167
+ max_distance=max_distance,
168
+ )
169
+ return rel_pos_bucket.unsqueeze(0).unsqueeze(0)
@@ -0,0 +1,131 @@
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
+ # Builder class for individual components.
16
+ import torch
17
+ from torch import nn
18
+ import torch.nn.functional as F
19
+
20
+ import ai_edge_torch.generative.layers.feed_forward as feed_forward
21
+ import ai_edge_torch.generative.layers.model_config as cfg
22
+ import ai_edge_torch.generative.layers.normalization as normalization
23
+
24
+
25
+ class GeGLU(nn.Module):
26
+ """GeGLU is an activation function which is a variant of GELU.
27
+
28
+ GeGLU(x) = (xW+b) * GELU(xV+c)
29
+ See: https://arxiv.org/abs/2002.05202v1
30
+
31
+ """
32
+
33
+ def __init__(self, d_in: int, d_out: int):
34
+ super().__init__()
35
+ self.proj = nn.Linear(d_in, d_out * 2)
36
+
37
+ def forward(self, x: torch.Tensor):
38
+ x, gate = self.proj(x).chunk(2, dim=-1)
39
+ return x * F.gelu(gate)
40
+
41
+
42
+ def build_norm(dim: int, config: cfg.NormalizationConfig):
43
+ """Builder function for normalizers.
44
+
45
+ Args:
46
+ dim (int): dimension of the input tensor.
47
+ config (`NormalizationConfig` object): the normalization configuration.
48
+
49
+ Returns:
50
+ The constructed `nn.Module` normalization layer.
51
+
52
+ Raises:
53
+ ValueError: If config's `layer_norm_type` is not supported.
54
+ """
55
+ if config.type == cfg.NormalizationType.NONE:
56
+ return lambda x: x
57
+ elif config.type == cfg.NormalizationType.RMS_NORM:
58
+ return normalization.RMSNorm(
59
+ dim,
60
+ eps=config.epsilon,
61
+ zero_centered_gamma=config.zero_centered,
62
+ )
63
+ elif config.type == cfg.NormalizationType.LAYER_NORM:
64
+ return nn.LayerNorm(dim, eps=config.epsilon)
65
+ elif config.type == cfg.NormalizationType.GROUP_NORM:
66
+ return nn.GroupNorm(config.group_num, dim, config.epsilon)
67
+ else:
68
+ raise ValueError("Unsupported norm type.")
69
+
70
+
71
+ def build_ff(dim: int, config: cfg.FeedForwardConfig):
72
+ """Builder function for Feed Forward. Supports `Sequential` and `Gated`.
73
+
74
+ Args:
75
+ dim (int): dimension of the input tensor.
76
+ config (`ModelConfig` object): the model configuration.
77
+
78
+ Returns:
79
+ The constructed `nn.Module` feedforward layer.
80
+
81
+ Raises:
82
+ ValueError: If config's `ff_type` is not supported.
83
+ """
84
+ ff_type = config.type
85
+ if ff_type == cfg.FeedForwardType.SEQUENTIAL:
86
+ ff_module = feed_forward.SequentialFeedForward
87
+ elif ff_type == cfg.FeedForwardType.GATED:
88
+ ff_module = feed_forward.GatedFeedForward
89
+ else:
90
+ raise ValueError("Unsupported feedforward type.")
91
+
92
+ activation = get_activation(config.activation)
93
+
94
+ return ff_module(
95
+ dim=dim,
96
+ hidden_dim=config.intermediate_size,
97
+ activation=activation,
98
+ use_bias=config.use_bias,
99
+ )
100
+
101
+
102
+ def get_activation(config: cfg.ActivationConfig):
103
+ """Get pytorch callable activation from the activation config.
104
+
105
+ Args:
106
+ config (cfg.ActivationConfig): activation config.
107
+
108
+ Returns:
109
+ Activation function.
110
+
111
+ Raises:
112
+ ValueError: If activation config is not supported.
113
+ """
114
+ if config.type == cfg.ActivationType.LINEAR:
115
+ return lambda x: x
116
+ elif config.type == cfg.ActivationType.SILU:
117
+ return F.silu
118
+ elif config.type == cfg.ActivationType.GELU:
119
+ return F.gelu
120
+ elif config.type == cfg.ActivationType.GELU_TANH:
121
+ return lambda x: F.gelu(x, approximate="tanh")
122
+ elif config.type == cfg.ActivationType.GELU_QUICK:
123
+ # GELU approximation that is fast but somewhat inaccurate.
124
+ # See: https://github.com/hendrycks/GELUs
125
+ return lambda x: x * F.sigmoid(1.702 * x)
126
+ elif config.type == cfg.ActivationType.GE_GLU:
127
+ return GeGLU(config.dim_in, config.dim_out)
128
+ elif config.type == cfg.ActivationType.RELU:
129
+ return F.relu
130
+ else:
131
+ raise ValueError("Unsupported activation type.")
@@ -0,0 +1,95 @@
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 FeedForward layers.
16
+
17
+ from typing import Callable
18
+
19
+ import torch
20
+ from torch import nn
21
+ import torch.nn.functional as F
22
+
23
+
24
+ class SequentialFeedForward(nn.Module):
25
+ """Vanilla sequential Feedforward with customizable activation."""
26
+
27
+ def __init__(
28
+ self,
29
+ dim: int,
30
+ hidden_dim: int,
31
+ activation: Callable[[torch.Tensor], torch.Tensor],
32
+ use_bias=False,
33
+ ):
34
+ """Init function for feedforward layer.
35
+
36
+ Args:
37
+ dim(int): embedding size.
38
+ hidden_dim(int): hidden dim size of the feedforward layer.
39
+ activation(Callable): activation function used in this block.
40
+ use_bias(Boolean): whether to use bias. Default is false.
41
+ """
42
+ super().__init__()
43
+ self.act = activation
44
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
45
+ self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
46
+
47
+ def forward(self, x):
48
+ """Forward pass for Feedforward layer.
49
+
50
+ Args:
51
+ x (torch.Tensor): the input tensor.
52
+
53
+ Returns:
54
+ torch.Tensor: output tensor after feedforward.
55
+ """
56
+ return self.w2(self.act(self.w1(x)))
57
+
58
+
59
+ class GatedFeedForward(nn.Module):
60
+ """Gated Feedforward with customizable activation.
61
+
62
+ https://arxiv.org/pdf/2002.05202v1.pdf
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ dim: int,
68
+ hidden_dim: int,
69
+ activation: Callable[[torch.Tensor], torch.Tensor],
70
+ use_bias=False,
71
+ ):
72
+ """Init function for feedforward layer.
73
+
74
+ Args:
75
+ dim(int): embedding size.
76
+ hidden_dim(int): hidden dim size of the feedforward layer.
77
+ activation(Callable): activation function used in this block.
78
+ use_bias(Boolean): whether to use bias. Default is false.
79
+ """
80
+ super().__init__()
81
+ self.act = activation
82
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
83
+ self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
84
+ self.w3 = nn.Linear(dim, hidden_dim, bias=use_bias)
85
+
86
+ def forward(self, x):
87
+ """Forward pass for Feedforward layer.
88
+
89
+ Args:
90
+ x (torch.Tensor): the input tensor.
91
+
92
+ Returns:
93
+ torch.Tensor: output tensor after feedforward.
94
+ """
95
+ return self.w2(self.act(self.w1(x)) * self.w3(x))
@@ -0,0 +1,83 @@
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
+ # `nn.Module` which implements a KV cache.
16
+
17
+ import torch
18
+ from torch import nn
19
+ import torch_xla
20
+
21
+ from ai_edge_torch.hlfb import StableHLOCompositeBuilder
22
+
23
+
24
+ class KVCache(nn.Module):
25
+
26
+ def __init__(self, batch_size, kv_cache_max, n_heads, head_dim, enable_hlfb=False):
27
+ """Initializes the KVCache layer.
28
+
29
+ Args:
30
+ batch_size (int): batch size. Currently only batch size 1 is supported.
31
+ kv_cache_max (int): the max length of KV cache.
32
+ n_heads (int): number of kv heads.
33
+ head_dim (int): the head dimension size.
34
+ enable_hlfb (bool): whether hlfb is enabled or not.
35
+ """
36
+ super().__init__()
37
+ cache_shape = (batch_size, kv_cache_max, n_heads, head_dim)
38
+ self.register_buffer("k_cache", torch.zeros(cache_shape), persistent=False)
39
+ self.register_buffer("v_cache", torch.zeros(cache_shape), persistent=False)
40
+ self.enable_hlfb = enable_hlfb
41
+ self.kv_cache_max = kv_cache_max
42
+
43
+ def update_cache(self, input_pos, k_val, v_val):
44
+ """Update an entry in the KV cache.
45
+
46
+ Args:
47
+ input_pos (torch.Tensor): the input position.
48
+ k_val (torch.Tensor): the new `key` value.
49
+ v_val (torch.Tensor): the new `value` value.
50
+
51
+ Returns:
52
+ The updated key and value tensor.
53
+ """
54
+ if self.enable_hlfb:
55
+ return self.update_cache_with_hlfb(input_pos, k_val, v_val)
56
+
57
+ updated_k = self.k_cache.index_copy_(1, input_pos, k_val)
58
+ updated_v = self.v_cache.index_copy_(1, input_pos, v_val)
59
+ # Here we need a clone otherwise dynamo export will fail.
60
+ return torch.clone(updated_k), torch.clone(updated_v)
61
+
62
+ def update_cache_with_hlfb(self, input_pos, k_val, v_val):
63
+ """Update an entry in the KV cache and enable high-level function boundary.
64
+
65
+ Args:
66
+ input_pos (torch.Tensor): the input position.
67
+ k_val (torch.Tensor): the new `key` value.
68
+ v_val (torch.Tensor): the new `value` value.
69
+
70
+ Returns:
71
+ The updated key and value tensor.
72
+ """
73
+
74
+ builder = StableHLOCompositeBuilder(
75
+ name="odml.update_kv_cache", attr={"kv_cache_max": self.kv_cache_max}
76
+ )
77
+ k_cache, v_cache, input_pos, k_val, v_val = builder.mark_inputs(
78
+ self.k_cache, self.v_cache, input_pos, k_val, v_val
79
+ )
80
+ updated_k = k_cache.index_copy_(1, input_pos, k_val)
81
+ updated_v = v_cache.index_copy_(1, input_pos, v_val)
82
+ updated_k, updated_v = builder.mark_outputs(updated_k, updated_v)
83
+ return updated_k, updated_v
@@ -0,0 +1,158 @@
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
+ # Model configuration class.
16
+ from dataclasses import dataclass
17
+ from dataclasses import field
18
+ import enum
19
+ from typing import Optional
20
+
21
+
22
+ @enum.unique
23
+ class ActivationType(enum.Enum):
24
+ """Different activation functions supported by the default builder."""
25
+
26
+ LINEAR = enum.auto()
27
+ SILU = enum.auto()
28
+ GELU = enum.auto()
29
+ GELU_TANH = enum.auto()
30
+ GELU_QUICK = enum.auto()
31
+ GE_GLU = enum.auto()
32
+ RELU = enum.auto()
33
+
34
+
35
+ @enum.unique
36
+ class NormalizationType(enum.Enum):
37
+ """Different normalization functions"""
38
+
39
+ # No normalization is applied.
40
+ NONE = enum.auto()
41
+ RMS_NORM = enum.auto()
42
+ LAYER_NORM = enum.auto()
43
+ GROUP_NORM = enum.auto()
44
+
45
+
46
+ @enum.unique
47
+ class FeedForwardType(enum.Enum):
48
+ """Different variations of the Feed Forward module."""
49
+
50
+ # `output = linear(act(linear(x)))`.
51
+ SEQUENTIAL = enum.auto()
52
+ # `output = linear_2(act(linear_1(x)) * lienar_3(x))`.
53
+ GATED = enum.auto()
54
+
55
+
56
+ @dataclass
57
+ class AttentionConfig:
58
+ """Attention moduel's parameters."""
59
+
60
+ num_heads: int
61
+ # Used to determine number of groups in grouped query attention (GQA)
62
+ # https://arxiv.org/pdf/2305.13245.pdf
63
+ num_query_groups: Optional[int]
64
+ # Percentage of Rotary Positional Embedding added Q and K projections.
65
+ rotary_percentage: Optional[float] = None
66
+ # Whether to transpose the query groups of qkv bundled tensor before
67
+ # splitting into separated tensors.
68
+ qkv_transpose_before_split: bool = False
69
+ # Whether to use bias with Query, Key, and Value projection.
70
+ qkv_use_bias: bool = False
71
+ # Whether the fused q, k, v projection weights interleaves q, k, v heads.
72
+ # If True, the projection weights are in format [q_head_0, k_head_0, v_head_0, q_head_1, k_head_1, v_head_1, ...]
73
+ # If False, the projection weights are in format [q_head_0, q_head_1, ..., k_head_0, k_head_1, ... v_head_0, v_head_1, ...]
74
+ qkv_fused_interleaved: bool = True
75
+ # Whether to use bias with attention output projection.
76
+ output_proj_use_bias: bool = False
77
+ enable_kv_cache: bool = True
78
+ relative_attention_num_buckets: int = 0
79
+ relative_attention_max_distance: int = 0
80
+
81
+
82
+ @dataclass
83
+ class ActivationConfig:
84
+ type: ActivationType = ActivationType.LINEAR
85
+ # Dimension of input and output, used in GeGLU.
86
+ dim_in: Optional[int] = None
87
+ dim_out: Optional[int] = None
88
+
89
+
90
+ @dataclass
91
+ class FeedForwardConfig:
92
+ """FeedForward module's parameters."""
93
+
94
+ type: FeedForwardType
95
+ activation: ActivationConfig
96
+ intermediate_size: int
97
+ use_bias: bool = False
98
+
99
+
100
+ @dataclass
101
+ class NormalizationConfig:
102
+ """Normalizater parameters."""
103
+
104
+ type: NormalizationType = NormalizationType.NONE
105
+ epsilon: float = 1e-5
106
+ zero_centered: bool = False
107
+ # Number of groups used in group normalization.
108
+ group_num: Optional[float] = None
109
+
110
+
111
+ @dataclass
112
+ class ModelConfig:
113
+ """Base configurations for building a transformer architecture."""
114
+
115
+ vocab_size: int
116
+ num_layers: int
117
+ max_seq_len: int
118
+ embedding_dim: int
119
+
120
+ attn_config: AttentionConfig
121
+ ff_config: FeedForwardConfig
122
+ # The normalization applied to attention's input.
123
+ pre_attention_norm_config: NormalizationConfig = field(
124
+ default_factory=NormalizationConfig
125
+ )
126
+ # The normalization applied to feed forward's input.
127
+ pre_ff_norm_config: NormalizationConfig = field(default_factory=NormalizationConfig)
128
+ # The normalization applied before LM head.
129
+ final_norm_config: NormalizationConfig = field(default_factory=NormalizationConfig)
130
+
131
+ # If set to True, only pre_attention_norm is applied to the input and the
132
+ # decode's output is computed as `output = input + attn_out + ff_out` where
133
+ # attention and feed forward are called with pre_attention_norm's output.
134
+ parallel_residual: bool = False
135
+ # Use bias term within LLM's HEAD.
136
+ lm_head_use_bias: bool = False
137
+ # Whether to turn on high-level function boundary.
138
+ enable_hlfb: bool = False
139
+
140
+ # The maximum sequence length of the KV cache. Should not exceed max_seq_len.
141
+ kv_cache_max_len: int = 0
142
+
143
+ # The Attention computation will include relative positional bias.
144
+ relative_attention: bool = False
145
+
146
+ # Default batch size of the exported model. Default value is 1.
147
+ batch_size: int = 1
148
+
149
+ @property
150
+ def kv_cache_max(self) -> int:
151
+ if self.kv_cache_max_len > 0:
152
+ return self.kv_cache_max_len
153
+ else:
154
+ return self.max_seq_len
155
+
156
+ @property
157
+ def head_dim(self) -> int:
158
+ return self.embedding_dim // self.attn_config.num_heads
@@ -0,0 +1,62 @@
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 normalization layers.
16
+
17
+ import torch
18
+
19
+
20
+ # Implementation for RMSNorm from: https://arxiv.org/abs/1910.07467
21
+ class RMSNorm(torch.nn.Module):
22
+
23
+ def __init__(self, dim: int, eps: float = 1e-6, zero_centered_gamma=False):
24
+ """
25
+ Initialize the RMSNorm layer.
26
+
27
+ Args:
28
+ dim (int): dimension of the input tensor.
29
+ eps (float): A small float value to ensure numerical stability (default: 1e-6).
30
+ """
31
+ super().__init__()
32
+ self.eps = eps
33
+ self.weight = torch.nn.Parameter(torch.ones(dim))
34
+ self.zero_centered_gamma = zero_centered_gamma
35
+
36
+ def _norm(self, x):
37
+ """
38
+ Apply RMSNorm normalization.
39
+
40
+ Args:
41
+ x (torch.Tensor): input tensor.
42
+
43
+ Returns:
44
+ torch.Tensor: The normalized output tensor.
45
+ """
46
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
47
+
48
+ def forward(self, x):
49
+ """
50
+ Running the forward pass of RMSNorm layer.
51
+
52
+ Args:
53
+ x (torch.Tensor): input tensor.
54
+
55
+ Returns:
56
+ torch.Tensor: output tensor after applying RMSNorm.
57
+ """
58
+ output = self._norm(x.float()).type_as(x)
59
+ if self.zero_centered_gamma:
60
+ return output * (1 + self.weight)
61
+ else:
62
+ return output * self.weight