ai-edge-torch-nightly 0.1.dev202405131930__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 (91) hide show
  1. ai_edge_torch/__init__.py +30 -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 +330 -0
  5. ai_edge_torch/convert/converter.py +171 -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 +192 -0
  9. ai_edge_torch/convert/fx_passes/build_upsample_bilinear2d_composite_pass.py +84 -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 +196 -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 +286 -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 +273 -0
  24. ai_edge_torch/convert/test/test_convert_composites.py +171 -0
  25. ai_edge_torch/convert/test/test_convert_multisig.py +139 -0
  26. ai_edge_torch/debug/__init__.py +16 -0
  27. ai_edge_torch/debug/culprit.py +423 -0
  28. ai_edge_torch/debug/test/__init__.py +14 -0
  29. ai_edge_torch/debug/test/test_culprit.py +133 -0
  30. ai_edge_torch/debug/utils.py +48 -0
  31. ai_edge_torch/experimental/__init__.py +14 -0
  32. ai_edge_torch/generative/__init__.py +14 -0
  33. ai_edge_torch/generative/examples/__init__.py +14 -0
  34. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  35. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +66 -0
  36. ai_edge_torch/generative/examples/gemma/gemma.py +174 -0
  37. ai_edge_torch/generative/examples/phi2/__init__.py +14 -0
  38. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +64 -0
  39. ai_edge_torch/generative/examples/phi2/phi2.py +164 -0
  40. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +135 -0
  42. ai_edge_torch/generative/examples/t5/t5.py +608 -0
  43. ai_edge_torch/generative/examples/t5/t5_attention.py +255 -0
  44. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  45. ai_edge_torch/generative/examples/test_models/toy_model.py +119 -0
  46. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +143 -0
  47. ai_edge_torch/generative/examples/tiny_llama/__init__.py +0 -0
  48. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +66 -0
  49. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +164 -0
  50. ai_edge_torch/generative/layers/__init__.py +14 -0
  51. ai_edge_torch/generative/layers/attention.py +288 -0
  52. ai_edge_torch/generative/layers/attention_utils.py +169 -0
  53. ai_edge_torch/generative/layers/builder.py +103 -0
  54. ai_edge_torch/generative/layers/feed_forward.py +95 -0
  55. ai_edge_torch/generative/layers/kv_cache.py +83 -0
  56. ai_edge_torch/generative/layers/model_config.py +135 -0
  57. ai_edge_torch/generative/layers/normalization.py +62 -0
  58. ai_edge_torch/generative/layers/rotary_position_embedding.py +36 -0
  59. ai_edge_torch/generative/quantize/__init__.py +14 -0
  60. ai_edge_torch/generative/quantize/example.py +45 -0
  61. ai_edge_torch/generative/quantize/quant_attrs.py +66 -0
  62. ai_edge_torch/generative/quantize/quant_recipe.py +106 -0
  63. ai_edge_torch/generative/quantize/quant_recipe_utils.py +51 -0
  64. ai_edge_torch/generative/quantize/quant_recipes.py +48 -0
  65. ai_edge_torch/generative/quantize/supported_schemes.py +31 -0
  66. ai_edge_torch/generative/test/__init__.py +14 -0
  67. ai_edge_torch/generative/test/test_model_conversion.py +201 -0
  68. ai_edge_torch/generative/test/test_quantize.py +109 -0
  69. ai_edge_torch/generative/utilities/__init__.py +15 -0
  70. ai_edge_torch/generative/utilities/loader.py +290 -0
  71. ai_edge_torch/generative/utilities/t5_loader.py +467 -0
  72. ai_edge_torch/hlfb/__init__.py +16 -0
  73. ai_edge_torch/hlfb/mark_pattern/__init__.py +139 -0
  74. ai_edge_torch/hlfb/mark_pattern/passes.py +42 -0
  75. ai_edge_torch/hlfb/mark_pattern/pattern.py +260 -0
  76. ai_edge_torch/hlfb/test/__init__.py +14 -0
  77. ai_edge_torch/hlfb/test/test_mark_pattern.py +133 -0
  78. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +270 -0
  79. ai_edge_torch/model.py +134 -0
  80. ai_edge_torch/quantize/__init__.py +16 -0
  81. ai_edge_torch/quantize/pt2e_quantizer.py +438 -0
  82. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1041 -0
  83. ai_edge_torch/quantize/quant_config.py +85 -0
  84. ai_edge_torch/testing/__init__.py +14 -0
  85. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  86. ai_edge_torch/testing/model_coverage/model_coverage.py +126 -0
  87. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/LICENSE +202 -0
  88. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/METADATA +38 -0
  89. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/RECORD +91 -0
  90. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/WHEEL +5 -0
  91. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/top_level.txt +1 -0
@@ -0,0 +1,103 @@
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
+ from torch import nn
17
+ import torch.nn.functional as F
18
+
19
+ import ai_edge_torch.generative.layers.feed_forward as feed_forward
20
+ import ai_edge_torch.generative.layers.model_config as cfg
21
+ import ai_edge_torch.generative.layers.normalization as normalization
22
+
23
+
24
+ def build_norm(dim: int, config: cfg.NormalizationConfig):
25
+ """Builder function for normalizers.
26
+
27
+ Args:
28
+ dim (int): dimension of the input tensor.
29
+ config (`NormalizationConfig` object): the normalization configuration.
30
+
31
+ Returns:
32
+ The constructed `nn.Module` normalization layer.
33
+
34
+ Raises:
35
+ ValueError: If config's `layer_norm_type` is not supported.
36
+ """
37
+ if config.type == cfg.NormalizationType.NONE:
38
+ return lambda x: x
39
+ elif config.type == cfg.NormalizationType.RMS_NORM:
40
+ return normalization.RMSNorm(
41
+ dim,
42
+ eps=config.epsilon,
43
+ zero_centered_gamma=config.zero_centered,
44
+ )
45
+ elif config.type == cfg.NormalizationType.LAYER_NORM:
46
+ return nn.LayerNorm(dim, eps=config.epsilon)
47
+ else:
48
+ raise ValueError("Unsupported norm type.")
49
+
50
+
51
+ def build_ff(dim: int, config: cfg.FeedForwardConfig):
52
+ """Builder function for Feed Forward. Supports `Sequential` and `Gated`.
53
+
54
+ Args:
55
+ dim (int): dimension of the input tensor.
56
+ config (`ModelConfig` object): the model configuration.
57
+
58
+ Returns:
59
+ The constructed `nn.Module` feedforward layer.
60
+
61
+ Raises:
62
+ ValueError: If config's `ff_type` is not supported.
63
+ """
64
+ ff_type = config.type
65
+ if ff_type == cfg.FeedForwardType.SEQUENTIAL:
66
+ ff_module = feed_forward.SequentialFeedForward
67
+ elif ff_type == cfg.FeedForwardType.GATED:
68
+ ff_module = feed_forward.GatedFeedForward
69
+ else:
70
+ raise ValueError("Unsupported feedforward type.")
71
+
72
+ activation = _get_activation(config.activation)
73
+
74
+ return ff_module(
75
+ dim=dim,
76
+ hidden_dim=config.intermediate_size,
77
+ activation=activation,
78
+ use_bias=config.use_bias,
79
+ )
80
+
81
+
82
+ def _get_activation(type_: cfg.ActivationType):
83
+ """Get pytorch callable activation from the name.
84
+
85
+ Args:
86
+ name (string): activation's name.
87
+
88
+ Returns:
89
+ Activation function.
90
+
91
+ Raises:
92
+ ValueError: If activation name is not supported.
93
+ """
94
+ if type_ == cfg.ActivationType.SILU:
95
+ return F.silu
96
+ elif type_ == cfg.ActivationType.GELU:
97
+ return F.gelu
98
+ elif type_ == cfg.ActivationType.GELU_TANH:
99
+ return lambda x: F.gelu(x, approximate="tanh")
100
+ elif type_ == cfg.ActivationType.RELU:
101
+ return F.relu
102
+ else:
103
+ 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,135 @@
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
+ RELU = enum.auto()
31
+
32
+
33
+ @enum.unique
34
+ class NormalizationType(enum.Enum):
35
+ """Different normalization functions"""
36
+
37
+ # No normalization is applied.
38
+ NONE = enum.auto()
39
+ RMS_NORM = enum.auto()
40
+ LAYER_NORM = enum.auto()
41
+
42
+
43
+ @enum.unique
44
+ class FeedForwardType(enum.Enum):
45
+ """Different variations of the Feed Forward module."""
46
+
47
+ # `output = linear(act(linear(x)))`.
48
+ SEQUENTIAL = enum.auto()
49
+ # `output = linear(act(linear(x)) * lienar(x))`.
50
+ GATED = enum.auto()
51
+
52
+
53
+ @dataclass
54
+ class AttentionConfig:
55
+ """Attention moduel's parameters."""
56
+
57
+ num_heads: int
58
+ # Used to determine number of groups in grouped query attention (GQA)
59
+ # https://arxiv.org/pdf/2305.13245.pdf
60
+ num_query_groups: Optional[int]
61
+ # Percentage of Rotary Positional Embedding added Q and K projections.
62
+ rotary_percentage: Optional[float] = None
63
+ # Whether to use bias with Query, Key, and Value projection.
64
+ qkv_use_bias: bool = False
65
+ # Whether to use bias with attention output projection.
66
+ output_proj_use_bias: bool = False
67
+ enable_kv_cache: bool = True
68
+ relative_attention_num_buckets: int = 0
69
+ relative_attention_max_distance: int = 0
70
+
71
+
72
+ @dataclass
73
+ class FeedForwardConfig:
74
+ """FeedForward module's parameters."""
75
+
76
+ type: FeedForwardType
77
+ activation: ActivationType
78
+ intermediate_size: int
79
+ use_bias: bool = False
80
+
81
+
82
+ @dataclass
83
+ class NormalizationConfig:
84
+ """Normalizater parameters."""
85
+
86
+ type: NormalizationType = NormalizationType.NONE
87
+ epsilon: float = 1e-5
88
+ zero_centered: bool = False
89
+
90
+
91
+ @dataclass
92
+ class ModelConfig:
93
+ """Base configurations for building a transformer architecture."""
94
+
95
+ vocab_size: int
96
+ num_layers: int
97
+ max_seq_len: int
98
+ embedding_dim: int
99
+
100
+ attn_config: AttentionConfig
101
+ ff_config: FeedForwardConfig
102
+ # The normalization applied to attention's input.
103
+ pre_attention_norm_config: NormalizationConfig = field(
104
+ default_factory=NormalizationConfig
105
+ )
106
+ # The normalization applied to feed forward's input.
107
+ pre_ff_norm_config: NormalizationConfig = field(default_factory=NormalizationConfig)
108
+ # The normalization applied before LM head.
109
+ final_norm_config: NormalizationConfig = field(default_factory=NormalizationConfig)
110
+
111
+ # If set to True, only pre_attention_norm is applied to the input and the
112
+ # decode's output is computed as `output = input + attn_out + ff_out` where
113
+ # attention and feed forward are called with pre_attention_norm's output.
114
+ parallel_residual: bool = False
115
+ # Use bias term within LLM's HEAD.
116
+ lm_head_use_bias: bool = False
117
+ # Whether to turn on high-level function boundary.
118
+ enable_hlfb: bool = False
119
+
120
+ # The maximum sequence length of the KV cache. Should not exceed max_seq_len.
121
+ kv_cache_max_len: int = 0
122
+
123
+ # The Attention computation will include relative positional bias.
124
+ relative_attention: bool = False
125
+
126
+ @property
127
+ def kv_cache_max(self) -> int:
128
+ if self.kv_cache_max_len > 0:
129
+ return self.kv_cache_max_len
130
+ else:
131
+ return self.max_seq_len
132
+
133
+ @property
134
+ def head_dim(self) -> int:
135
+ 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
@@ -0,0 +1,36 @@
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
+ # Implementation for Rotary Position embedding. https://arxiv.org/pdf/2104.09864.pdf
16
+ import torch
17
+
18
+
19
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
20
+ """Computes rotary positional embedding.
21
+
22
+ Args:
23
+ x(torch.Tensor): the input tensor.
24
+ cos(torch.Tensor): cosine value for the rope.
25
+ sin(torch.Tensor): sin value for the rope.
26
+
27
+ Returns:
28
+ output tensor of RoPE.
29
+ """
30
+ x = x.transpose(1, 2)
31
+ head_size = x.size(-1)
32
+ x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)
33
+ x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)
34
+ rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)
35
+ roped = (x * cos) + (rotated * sin)
36
+ return roped.transpose(1, 2).type_as(x)
@@ -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,45 @@
1
+ # Copyright 2024 The AI Edge Torch Authors. All Rights Reserved.
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 numpy as np
17
+ import torch
18
+
19
+ import ai_edge_torch
20
+ from ai_edge_torch.generative.examples.gemma import gemma
21
+ from ai_edge_torch.generative.quantize import quant_recipes
22
+
23
+
24
+ def main():
25
+ # Build a PyTorch model as usual
26
+ config = gemma.get_fake_model_config_2b_for_test()
27
+ model = gemma.Gemma(config)
28
+ idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
29
+ tokens = torch.full((1, 10), 0, dtype=torch.long, device="cpu")
30
+ tokens[0, :4] = idx
31
+ input_pos = torch.arange(0, 10)
32
+
33
+ # Create a quantization recipe to be applied to the model
34
+ quant_config = quant_recipes.full_linear_int8_dynamic_recipe()
35
+ print(quant_config)
36
+
37
+ # Convert with quantization
38
+ edge_model = ai_edge_torch.convert(
39
+ model, (tokens, input_pos), quant_config=quant_config
40
+ )
41
+ edge_model.export("/tmp/gemma_2b_quantized.tflite")
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -0,0 +1,66 @@
1
+ # Copyright 2024 The AI Edge Torch Authors. All Rights Reserved.
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 enum
17
+
18
+
19
+ @enum.unique
20
+ class Dtype(enum.Enum):
21
+ """Data types and precision of tensors."""
22
+
23
+ FP32 = enum.auto()
24
+ FP16 = enum.auto()
25
+ INT8 = enum.auto()
26
+
27
+
28
+ @enum.unique
29
+ class Algorithm(enum.Enum):
30
+ """Algorithm used to calculate quantization parameters.
31
+
32
+ Attributes:
33
+ MIN_MAX: Maps the min/max of floating point space to the min/max of
34
+ quantized space and quantize uniformly.
35
+ """
36
+
37
+ MIN_MAX = enum.auto()
38
+
39
+
40
+ @enum.unique
41
+ class Mode(enum.Enum):
42
+ """Mode of quantization.
43
+
44
+ Attributes:
45
+ DYNAMIC_RANGE: Quantize activations during runtime and weights statically to
46
+ perform computation in integers.
47
+ WEIGHT_ONLY: Quantize weights statically and dequantize during runtime to
48
+ perform computation in floating points.
49
+ """
50
+
51
+ DYNAMIC_RANGE = enum.auto()
52
+ WEIGHT_ONLY = enum.auto()
53
+
54
+
55
+ @enum.unique
56
+ class Granularity(enum.Enum):
57
+ """Granularity of quantization parameters.
58
+
59
+ Attributes:
60
+ NONE: Granularity not applicable to this quantization scheme.
61
+ CHANNELWISE: Or per-channel quantization. Each channel of relevant tensors
62
+ is quantized independently of one another.
63
+ """
64
+
65
+ NONE = enum.auto()
66
+ CHANNELWISE = enum.auto()