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
@@ -14,11 +14,10 @@
14
14
  # ==============================================================================
15
15
  # Common building blocks for FeedForward layers.
16
16
 
17
- from typing import Callable
17
+ from typing import Callable, Optional
18
18
 
19
19
  import torch
20
20
  from torch import nn
21
- import torch.nn.functional as F
22
21
 
23
22
 
24
23
  class SequentialFeedForward(nn.Module):
@@ -30,19 +29,30 @@ class SequentialFeedForward(nn.Module):
30
29
  hidden_dim: int,
31
30
  activation: Callable[[torch.Tensor], torch.Tensor],
32
31
  use_bias=False,
32
+ use_glu=False,
33
+ pre_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
34
+ post_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
33
35
  ):
34
36
  """Init function for feedforward layer.
35
37
 
36
38
  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.
39
+ dim (int): embedding size.
40
+ hidden_dim (int): hidden dim size of the feedforward layer.
41
+ activation (Callable): activation function used in this block.
42
+ use_bias (Boolean): whether to use bias. Default is false.
43
+ use_glu (Boolean): whether to use glu in activation. Default is false.
44
+ pre_ff_norm (Callable): pre feedforward norm. Default is None.
45
+ post_ff_norm (Callable): post feedforward norm. Default is None.
41
46
  """
42
47
  super().__init__()
43
48
  self.act = activation
44
- self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
49
+ if use_glu:
50
+ self.w1 = nn.Linear(dim, hidden_dim * 2, bias=use_bias)
51
+ else:
52
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
45
53
  self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
54
+ self.pre_ff_norm = pre_ff_norm if pre_ff_norm else lambda x: x
55
+ self.post_ff_norm = post_ff_norm if post_ff_norm else lambda x: x
46
56
 
47
57
  def forward(self, x):
48
58
  """Forward pass for Feedforward layer.
@@ -53,7 +63,9 @@ class SequentialFeedForward(nn.Module):
53
63
  Returns:
54
64
  torch.Tensor: output tensor after feedforward.
55
65
  """
56
- return self.w2(self.act(self.w1(x)))
66
+ x_norm = self.pre_ff_norm(x)
67
+ out = self.w2(self.act(self.w1(x_norm)))
68
+ return self.post_ff_norm(out)
57
69
 
58
70
 
59
71
  class GatedFeedForward(nn.Module):
@@ -68,20 +80,31 @@ class GatedFeedForward(nn.Module):
68
80
  hidden_dim: int,
69
81
  activation: Callable[[torch.Tensor], torch.Tensor],
70
82
  use_bias=False,
83
+ use_glu=False,
84
+ pre_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
85
+ post_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
71
86
  ):
72
87
  """Init function for feedforward layer.
73
88
 
74
89
  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.
90
+ dim (int): embedding size.
91
+ hidden_dim (int): hidden dim size of the feedforward layer.
92
+ activation (Callable): activation function used in this block.
93
+ use_bias (Boolean): whether to use bias. Default is false.
94
+ use_glu (Boolean): whether to use glu in activation. Default is false.
95
+ pre_ff_norm (Callable): pre feedforward norm. Default is None.
96
+ post_ff_norm (Callable): post feedforward norm. Default is None.
79
97
  """
80
98
  super().__init__()
81
99
  self.act = activation
82
- self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
100
+ if use_glu:
101
+ self.w1 = nn.Linear(dim, hidden_dim * 2, bias=use_bias)
102
+ else:
103
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
83
104
  self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
84
105
  self.w3 = nn.Linear(dim, hidden_dim, bias=use_bias)
106
+ self.pre_ff_norm = pre_ff_norm if pre_ff_norm else lambda x: x
107
+ self.post_ff_norm = post_ff_norm if post_ff_norm else lambda x: x
85
108
 
86
109
  def forward(self, x):
87
110
  """Forward pass for Feedforward layer.
@@ -92,4 +115,6 @@ class GatedFeedForward(nn.Module):
92
115
  Returns:
93
116
  torch.Tensor: output tensor after feedforward.
94
117
  """
95
- return self.w2(self.act(self.w1(x)) * self.w3(x))
118
+ x_norm = self.pre_ff_norm(x)
119
+ out = self.w2(self.act(self.w1(x_norm)) * self.w3(x_norm))
120
+ return self.post_ff_norm(out)
@@ -12,72 +12,184 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- # `nn.Module` which implements a KV cache.
16
15
 
16
+ """Utility functions for externalized KV Cache."""
17
+
18
+ import dataclasses
19
+ from typing import List, Tuple
20
+
21
+ from ai_edge_torch import hlfb
22
+ from ai_edge_torch.generative.layers import model_config
17
23
  import torch
18
- from torch import nn
19
- import torch_xla
24
+ import torch.utils._pytree as pytree
20
25
 
21
- from ai_edge_torch.hlfb import StableHLOCompositeBuilder
26
+ BATCH_SIZE = 1
22
27
 
23
28
 
24
- class KVCache(nn.Module):
29
+ @dataclasses.dataclass
30
+ class KVCacheEntry:
31
+ """A single cache entry that includes K and V caches.
25
32
 
26
- def __init__(self, batch_size, kv_cache_max, n_heads, head_dim, enable_hlfb=False):
27
- """Initializes the KVCache layer.
33
+ The chaches are built based on the provided config with the shape of
34
+ (batch_size=1, kv_cache_max, num_query_groups, head_dim).
35
+ """
28
36
 
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
37
+ k_cache: torch.Tensor
38
+ v_cache: torch.Tensor
42
39
 
43
- def update_cache(self, input_pos, k_val, v_val):
44
- """Update an entry in the KV cache.
40
+ @classmethod
41
+ def from_model_config(
42
+ cls,
43
+ kv_cache_max: int,
44
+ config: model_config.AttentionConfig,
45
+ dtype: torch.dtype = torch.float32,
46
+ device: torch.device = None,
47
+ ) -> "KVCacheEntry":
48
+ """Build an instance of the class based on model config."""
49
+ shape = (BATCH_SIZE, kv_cache_max, config.num_query_groups, config.head_dim)
50
+ k = torch.zeros(shape, dtype=dtype, device=device)
51
+ v = torch.zeros(shape, dtype=dtype, device=device)
52
+ obj = cls(k_cache=k, v_cache=v)
53
+ return obj
45
54
 
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
55
 
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
+ @dataclasses.dataclass
57
+ class KVCache:
58
+ """A utility class for holding KV cache entries per layer."""
56
59
 
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)
60
+ caches: Tuple[KVCacheEntry, ...]
61
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.
62
+ @classmethod
63
+ def from_model_config(
64
+ cls,
65
+ config: model_config.ModelConfig,
66
+ dtype: torch.dtype = torch.float32,
67
+ device: torch.device = None,
68
+ ) -> "KVCache":
69
+ """Build an instance of the class based on model config.
64
70
 
65
71
  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.
72
+ config (ModelConfig): Model config used for building the cache.
73
+ dtype (torch.dtype, optional): The data type of the cache tensor.
74
+ Defaults to torch.float32.
75
+ device (torch.device, optional): The device placement of the cache
76
+ tensors. Defaults to None.
69
77
 
70
78
  Returns:
71
- The updated key and value tensor.
79
+ KVCache: The created cache object.
72
80
  """
81
+ caches = [
82
+ KVCacheEntry.from_model_config(
83
+ config.kv_cache_max,
84
+ config.block_config(idx).attn_config,
85
+ dtype,
86
+ device,
87
+ )
88
+ for idx in range(config.num_layers)
89
+ ]
90
+ obj = cls(caches=tuple(caches))
91
+ return obj
73
92
 
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
93
+ def flatten(self) -> List[torch.Tensor]:
94
+ """Flatten the cache entries into a list of tensors with order k_i, v_i."""
95
+ flattened, _ = _flatten_kvc(self)
96
+ return flattened
97
+
98
+
99
+ def _flatten_kvc(kvc: KVCache) -> Tuple[List[str], List[str]]:
100
+ flattened = []
101
+ flat_names = []
102
+ none_names = []
103
+ for i, kv_entry in enumerate(kvc.caches):
104
+ flattened.append(kv_entry.k_cache)
105
+ flat_names.append(f"k_{i}")
106
+ flattened.append(kv_entry.v_cache)
107
+ flat_names.append(f"v_{i}")
108
+ return flattened, [flat_names, none_names]
109
+
110
+
111
+ def _flatten_kvc_with_keys(kvc: KVCache) -> Tuple[List, List]:
112
+ flattened, (flat_names, none_names) = _flatten_kvc(kvc)
113
+ return [
114
+ (pytree.MappingKey(k), v) for k, v in zip(flat_names, flattened)
115
+ ], flat_names
116
+
117
+
118
+ def _unflatten_kvc(
119
+ values: List[torch.Tensor], context: Tuple[List, List]
120
+ ) -> KVCache:
121
+ assert len(values) % 2 == 0, "Found odd number of K and V entries."
122
+ num_layers = len(values) // 2
123
+ flat_names = context[0]
124
+ kv_entries = []
125
+ for i in range(num_layers):
126
+ k_cache_idx = flat_names.index(f"k_{i}")
127
+ v_cache_idx = flat_names.index(f"v_{i}")
128
+ kv_entries.append(
129
+ KVCacheEntry(k_cache=values[k_cache_idx], v_cache=values[v_cache_idx])
79
130
  )
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
131
+ obj = KVCache(tuple(kv_entries))
132
+ return obj
133
+
134
+
135
+ pytree.register_pytree_node(
136
+ KVCache,
137
+ _flatten_kvc,
138
+ _unflatten_kvc,
139
+ flatten_with_keys_fn=_flatten_kvc_with_keys,
140
+ serialized_type_name="",
141
+ )
142
+
143
+
144
+ def update(
145
+ cache: KVCacheEntry,
146
+ input_pos: torch.Tensor,
147
+ k_slice: torch.Tensor,
148
+ v_slice: torch.Tensor,
149
+ enable_hlfb: bool = True,
150
+ ) -> KVCacheEntry:
151
+ """Out of place update of Cache buffer.
152
+
153
+ Args:
154
+ cache (KVCacheEntry): The original cache buffer.
155
+ input_pos (torch.Tensor): The update slice positions.
156
+ k_slice (torch.Tensor): The K slice to be updated in the new cache.
157
+ v_slice (torch.Tensor): The V slice to be updated in the new cache.
158
+ enable_hlfb (bool, optional): Whether the op is annotated for export with
159
+ High Level Function Boundary. Defaults to True.
160
+
161
+ Returns:
162
+ KVCacheEntry: The updated KVCache entry based on the passed inputs.
163
+ """
164
+ update_func = _update_kv_hlfb_impl if enable_hlfb else _update_kv_base_impl
165
+ return update_func(cache, input_pos, k_slice, v_slice)
166
+
167
+
168
+ def _update_kv_base_impl(
169
+ cache: KVCacheEntry,
170
+ input_pos: torch.Tensor,
171
+ k_slice: torch.Tensor,
172
+ v_slice: torch.Tensor,
173
+ ) -> KVCacheEntry:
174
+ """Update the cache buffer without High Level Function Boundary annotation."""
175
+ k = cache.k_cache.index_copy(1, input_pos.to(torch.long), k_slice)
176
+ v = cache.v_cache.index_copy(1, input_pos.to(torch.long), v_slice)
177
+ updated_cache = KVCacheEntry(k, v)
178
+ return updated_cache
179
+
180
+
181
+ def _update_kv_hlfb_impl(
182
+ cache: KVCacheEntry,
183
+ input_pos: torch.Tensor,
184
+ k_slice: torch.Tensor,
185
+ v_slice: torch.Tensor,
186
+ ) -> KVCacheEntry:
187
+ """Update the cache buffer with High Level Function Boundary annotation."""
188
+ builder = hlfb.StableHLOCompositeBuilder(name="odml.update_external_kv_cache")
189
+ k_cache, v_cache, input_pos, k_slice, v_slice = builder.mark_inputs(
190
+ cache.k_cache, cache.v_cache, input_pos, k_slice, v_slice
191
+ )
192
+ k = k_cache.index_copy(1, input_pos.to(torch.long), k_slice)
193
+ v = v_cache.index_copy(1, input_pos.to(torch.long), v_slice)
194
+ k, v = builder.mark_outputs(k, v)
195
+ return KVCacheEntry(k, v)
@@ -16,7 +16,7 @@
16
16
  from dataclasses import dataclass
17
17
  from dataclasses import field
18
18
  import enum
19
- from typing import Optional
19
+ from typing import Optional, Sequence, Union
20
20
 
21
21
 
22
22
  @enum.unique
@@ -30,6 +30,7 @@ class ActivationType(enum.Enum):
30
30
  GELU_QUICK = enum.auto()
31
31
  GE_GLU = enum.auto()
32
32
  RELU = enum.auto()
33
+ SILU_GLU = enum.auto()
33
34
 
34
35
 
35
36
  @enum.unique
@@ -53,11 +54,32 @@ class FeedForwardType(enum.Enum):
53
54
  GATED = enum.auto()
54
55
 
55
56
 
57
+ class AttentionType(enum.Enum):
58
+ GLOBAL = enum.auto()
59
+ LOCAL_SLIDING = enum.auto()
60
+
61
+
62
+ @dataclass
63
+ class NormalizationConfig:
64
+ """Normalizater parameters."""
65
+
66
+ type: NormalizationType = NormalizationType.NONE
67
+ enable_hlfb: bool = False
68
+ epsilon: float = 1e-5
69
+ zero_centered: bool = False
70
+ # Number of groups used in group normalization.
71
+ group_num: Optional[float] = None
72
+ # Whether to use the input shape to determine the dimension of normalization
73
+ # when type is LAYER_NORM.
74
+ use_input_shape: bool = True
75
+
76
+
56
77
  @dataclass
57
78
  class AttentionConfig:
58
- """Attention moduel's parameters."""
79
+ """Attention model's parameters."""
59
80
 
60
81
  num_heads: int
82
+ head_dim: int
61
83
  # Used to determine number of groups in grouped query attention (GQA)
62
84
  # https://arxiv.org/pdf/2305.13245.pdf
63
85
  num_query_groups: Optional[int]
@@ -75,8 +97,22 @@ class AttentionConfig:
75
97
  # Whether to use bias with attention output projection.
76
98
  output_proj_use_bias: bool = False
77
99
  enable_kv_cache: bool = True
100
+ # The normalization applied to query projection's output.
101
+ query_norm_config: NormalizationConfig = field(
102
+ default_factory=NormalizationConfig
103
+ )
104
+ # The normalization applied to key projection's output.
105
+ key_norm_config: NormalizationConfig = field(
106
+ default_factory=NormalizationConfig
107
+ )
78
108
  relative_attention_num_buckets: int = 0
79
109
  relative_attention_max_distance: int = 0
110
+ # Softcap on the output logits.
111
+ logit_softcap: Optional[float] = None
112
+ # The type of attention.
113
+ attn_type: Optional[AttentionType] = None
114
+ # The size of the sliding window used for local attention.
115
+ sliding_window_size: Optional[int] = None
80
116
 
81
117
 
82
118
  @dataclass
@@ -95,17 +131,37 @@ class FeedForwardConfig:
95
131
  activation: ActivationConfig
96
132
  intermediate_size: int
97
133
  use_bias: bool = False
134
+ # The normalization applied to feed forward's input.
135
+ pre_ff_norm_config: NormalizationConfig = field(
136
+ default_factory=NormalizationConfig
137
+ )
138
+ # The normalization applied to feed forward's output.
139
+ post_ff_norm_config: NormalizationConfig = field(
140
+ default_factory=NormalizationConfig
141
+ )
98
142
 
99
143
 
100
144
  @dataclass
101
- class NormalizationConfig:
102
- """Normalizater parameters."""
145
+ class TransformerBlockConfig:
146
+ """TransformerBlock module's parameters."""
103
147
 
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
148
+ attn_config: AttentionConfig
149
+ ff_config: FeedForwardConfig
150
+ # The normalization applied to attention's input.
151
+ pre_attention_norm_config: NormalizationConfig = field(
152
+ default_factory=NormalizationConfig
153
+ )
154
+ # The normalization applied to attentions's output.
155
+ post_attention_norm_config: NormalizationConfig = field(
156
+ default_factory=NormalizationConfig
157
+ )
158
+ # If set to True, only attn_config.pre_attention_norm is applied to the input
159
+ # and the decode's output is computed as `output = input + attn_out + ff_out`
160
+ # where attention and feed forward are called with pre_attention_norm's
161
+ # output.
162
+ parallel_residual: bool = False
163
+ # The Attention computation will include relative positional bias.
164
+ relative_attention: bool = False
109
165
 
110
166
 
111
167
  @dataclass
@@ -117,21 +173,15 @@ class ModelConfig:
117
173
  max_seq_len: int
118
174
  embedding_dim: int
119
175
 
120
- attn_config: AttentionConfig
121
- ff_config: FeedForwardConfig
122
- # The normalization applied to attention's input.
123
- pre_attention_norm_config: NormalizationConfig = field(
176
+ # TransformerBlockConfig for each layer block. If a single
177
+ # TransformerBlockConfig is provided, it will be used for all layers.
178
+ block_configs: Union[TransformerBlockConfig, Sequence[TransformerBlockConfig]]
179
+
180
+ # The normalization applied before LM head.
181
+ final_norm_config: NormalizationConfig = field(
124
182
  default_factory=NormalizationConfig
125
183
  )
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
184
 
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
185
  # Use bias term within LLM's HEAD.
136
186
  lm_head_use_bias: bool = False
137
187
  # Whether to turn on high-level function boundary.
@@ -140,19 +190,23 @@ class ModelConfig:
140
190
  # The maximum sequence length of the KV cache. Should not exceed max_seq_len.
141
191
  kv_cache_max_len: int = 0
142
192
 
143
- # The Attention computation will include relative positional bias.
144
- relative_attention: bool = False
145
-
146
193
  # Default batch size of the exported model. Default value is 1.
147
194
  batch_size: int = 1
148
195
 
196
+ # Softcap on the model output logits.
197
+ final_logit_softcap: Optional[float] = None
198
+
149
199
  @property
150
200
  def kv_cache_max(self) -> int:
151
201
  if self.kv_cache_max_len > 0:
152
202
  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
203
+ return self.max_seq_len
204
+
205
+ def block_config(self, idx: int) -> TransformerBlockConfig:
206
+ if isinstance(self.block_configs, TransformerBlockConfig):
207
+ return self.block_configs
208
+ if idx < 0 or idx >= len(self.block_configs):
209
+ raise ValueError(
210
+ f"Index {idx} is out of range for layer configs: {self.block_configs}"
211
+ )
212
+ return self.block_configs[idx]