ai-edge-quantizer-nightly 0.4.0.dev20250930__py3-none-any.whl → 0.4.0.dev20251002__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.
Files changed (22) hide show
  1. ai_edge_quantizer/algorithm_manager.py +40 -3
  2. ai_edge_quantizer/algorithms/uniform_quantize/common_quantize.py +28 -0
  3. ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation.py +77 -8
  4. ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation_test.py +69 -4
  5. ai_edge_quantizer/default_policy.py +4 -2
  6. ai_edge_quantizer/params_generator.py +1 -0
  7. ai_edge_quantizer/qtyping.py +5 -0
  8. ai_edge_quantizer/transformation_performer.py +5 -0
  9. ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation.py +291 -0
  10. ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation_test.py +244 -0
  11. ai_edge_quantizer/transformations/insert_hadamard_rotation.py +8 -31
  12. ai_edge_quantizer/transformations/quantize_tensor.py +11 -31
  13. ai_edge_quantizer/transformations/transformation_utils.py +66 -0
  14. ai_edge_quantizer/utils/constrained_ops_utils_test.py +1 -1
  15. ai_edge_quantizer/utils/tfl_flatbuffer_utils.py +1 -0
  16. ai_edge_quantizer/utils/validation_utils.py +29 -0
  17. ai_edge_quantizer/utils/validation_utils_test.py +24 -0
  18. {ai_edge_quantizer_nightly-0.4.0.dev20250930.dist-info → ai_edge_quantizer_nightly-0.4.0.dev20251002.dist-info}/METADATA +1 -1
  19. {ai_edge_quantizer_nightly-0.4.0.dev20250930.dist-info → ai_edge_quantizer_nightly-0.4.0.dev20251002.dist-info}/RECORD +22 -20
  20. {ai_edge_quantizer_nightly-0.4.0.dev20250930.dist-info → ai_edge_quantizer_nightly-0.4.0.dev20251002.dist-info}/LICENSE +0 -0
  21. {ai_edge_quantizer_nightly-0.4.0.dev20250930.dist-info → ai_edge_quantizer_nightly-0.4.0.dev20251002.dist-info}/WHEEL +0 -0
  22. {ai_edge_quantizer_nightly-0.4.0.dev20250930.dist-info → ai_edge_quantizer_nightly-0.4.0.dev20251002.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,291 @@
1
+ # Copyright 2024 The AI Edge Quantizer Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Hadamard rotation decomposed pattern transformation."""
17
+
18
+ from flatbuffers import flexbuffers
19
+ import numpy as np
20
+ from ai_edge_quantizer import qtyping
21
+ from ai_edge_quantizer.transformations import transformation_utils
22
+ from ai_edge_litert import schema_py_generated # pylint: disable=g-direct-tensorflow-import
23
+
24
+
25
+ def _to_flexbuffer(
26
+ hadamard_size: int,
27
+ random_binary_vector: list[np.int8],
28
+ ) -> bytes:
29
+ """Converts hadamard_size to flexbuffer."""
30
+ fbb = flexbuffers.Builder()
31
+ with fbb.Map():
32
+ fbb.Int('hadamard_size', hadamard_size)
33
+ fbb.VectorFromElements('random_binary_vector', random_binary_vector)
34
+ return fbb.Finish()
35
+
36
+
37
+ def _update_embedding_lookup_consumers(
38
+ transformation: transformation_utils.TransformationInput,
39
+ new_tensor_id: int,
40
+ ) -> bool:
41
+ """Updates the consumers of the embedding lookup op to use the new tensor.
42
+
43
+ Args:
44
+ transformation: The transformation input to update the consumers of.
45
+ new_tensor_id: The new tensor id to use as the input to the embedding lookup
46
+ consumers.
47
+ """
48
+ for consumer in transformation.consumers:
49
+ # If the consumer is a graph output and not an op, we can ignore it here
50
+ # since the graph output will be updated later.
51
+ if consumer == -1:
52
+ continue
53
+ consumer_op = transformation.subgraph.operators[consumer]
54
+ # Find the input that was attached to the insertion point, and replace it
55
+ # with the new tensor.
56
+ for i in range(len(consumer_op.inputs)):
57
+ if consumer_op.inputs[i] == transformation.tensor_id:
58
+ consumer_op.inputs[i] = new_tensor_id
59
+
60
+
61
+ def _update_fully_connected_consumers(
62
+ transformation: transformation_utils.TransformationInput,
63
+ new_tensor_id: int,
64
+ ) -> bool:
65
+ """Updates the fully connected op(s) to use the new tensor.
66
+
67
+ Since the new tensor is inserted to the fully_connected's input, we need to
68
+ scan each consumer (in case of multiple fully_connected ops), and update
69
+ the input tensor to the new tensor.
70
+
71
+ Args:
72
+ transformation: The transformation input to update the consumers of.
73
+ new_tensor_id: The new tensor id to use as the input to the fully connected
74
+ consumers.
75
+
76
+ Returns:
77
+ True if the fully connected op(s) were updated to use the new tensor.
78
+ """
79
+ updated = False
80
+ for consumer in transformation.consumers:
81
+ if (
82
+ transformation_utils.get_schema_op_id(transformation, consumer)
83
+ == schema_py_generated.BuiltinOperator.FULLY_CONNECTED
84
+ ):
85
+ transformation.subgraph.operators[consumer].inputs[0] = new_tensor_id
86
+ updated = True
87
+ return updated
88
+
89
+
90
+ def _make_hadamard_matrix(size: int):
91
+ """Generates a Hadamard matrix of the given size.
92
+
93
+ Args:
94
+ size: The size of the Hadamard matrix. Must be a power of 2. This represents
95
+ a single dimension. E.g. if size is 4, then the Hadamard matrix is a 4x4
96
+ matrix.
97
+
98
+ Returns:
99
+ The Hadamard matrix.
100
+
101
+ Raises:
102
+ ValueError: If the size is not a power of 2.
103
+ """
104
+ if size <= 0 or (size & (size - 1)) != 0:
105
+ raise ValueError('Hadamard matrix size must be a power of 2. ')
106
+ h = h2 = np.array([[1, 1], [1, -1]])
107
+ current_size = 2
108
+ while current_size < size:
109
+ h = np.kron(h, h2)
110
+ current_size *= 2
111
+ return h / np.sqrt(size)
112
+
113
+
114
+ def insert_decomposed_hadamard_rotation(
115
+ transformation_input: transformation_utils.TransformationInput,
116
+ ) -> qtyping.TransformationInfo:
117
+ """Inserts a decomposed pattern of Hadamard rotation on this tensor.
118
+
119
+ This function works for float32 tensors only. Instead of inserting a single
120
+ custom op (aeq.hadamard_rotation), this inserts the mathematical equivalent
121
+ expressed in built-in TFLite ops. The mathematical equivalent is:
122
+ x' = reshape(x, (-1, hadamard_size))
123
+ x' = x' @ H(hadamard_size)
124
+ x' = reshape(x, x.shape)
125
+ where H(n) is a Hadamard matrix of size n.
126
+
127
+ Args:
128
+ transformation_input: The transformation input to insert the ops on.
129
+
130
+ Returns:
131
+ The transformation info of the inserted ops.
132
+
133
+ Raises:
134
+ ValueError: If the transformation input is not a uniform quantization
135
+ transformation.
136
+ ValueError: If the Hadamard quantization params are not set.
137
+ ValueError: If the tensor is not a float32 tensor.
138
+ ValueError: If no supported ops were found as the tensor's producer or
139
+ consumers.
140
+ """
141
+ if not isinstance(
142
+ transformation_input.quant_params, qtyping.UniformQuantParams
143
+ ):
144
+ raise ValueError('Hadamard rotation supports uniform quantization only')
145
+
146
+ if transformation_input.quant_params.hadamard is None:
147
+ raise ValueError(
148
+ 'Hadamard rotation quantization params are not set but op insertion is'
149
+ ' requested.'
150
+ )
151
+
152
+ tensor = transformation_input.subgraph.tensors[transformation_input.tensor_id]
153
+ if tensor.type != schema_py_generated.TensorType.FLOAT32:
154
+ raise ValueError(
155
+ 'The Hadamard rotation op supports float32 tensors only. Got'
156
+ f' {tensor.type} tensor.'
157
+ )
158
+
159
+ # Insert x' = tfl.reshape to reshape x to (-1, hadamard_size)
160
+ hadamard_size = transformation_input.quant_params.hadamard.hadamard_size
161
+ tensor_size = np.prod(tensor.shape)
162
+ num_hadamard_blocks = tensor_size // hadamard_size
163
+ prerotate_shape = [num_hadamard_blocks, hadamard_size]
164
+ prerotate_shape_tensor_id = transformation_utils.add_new_constant_tensor(
165
+ tensor.name + b'_prerotate_shape',
166
+ np.array(prerotate_shape, dtype=np.int32),
167
+ schema_py_generated.TensorType.INT32,
168
+ transformation_input.subgraph,
169
+ transformation_input.buffers,
170
+ )
171
+ prerotate_reshape_output_tensor_id = (
172
+ transformation_utils.add_new_activation_tensor(
173
+ tensor.name + b'_prerotate_reshaped',
174
+ prerotate_shape,
175
+ schema_py_generated.TensorType.FLOAT32,
176
+ transformation_input.subgraph,
177
+ )
178
+ )
179
+
180
+ prerotate_reshape_op_code_idx = transformation_utils.add_op_code(
181
+ schema_py_generated.BuiltinOperator.RESHAPE,
182
+ transformation_input.op_codes,
183
+ 'RESHAPE',
184
+ )
185
+ prerorate_reshape_op = schema_py_generated.OperatorT()
186
+ prerorate_reshape_op.opcodeIndex = prerotate_reshape_op_code_idx
187
+ prerorate_reshape_op.inputs = [
188
+ transformation_input.tensor_id,
189
+ prerotate_shape_tensor_id,
190
+ ]
191
+ prerorate_reshape_op.outputs = [prerotate_reshape_output_tensor_id]
192
+
193
+ # Generate hadamard_matrix(hadamard_size).
194
+ # We could quantize this to INT4 for better memory efficiency, but for large
195
+ # models the memory overhead is not significant, and floating point
196
+ # computation does seem to result in better accuracy.
197
+ hadamard_matrix = _make_hadamard_matrix(hadamard_size)
198
+ hadamard_matrix_tensor_id = transformation_utils.add_new_constant_tensor(
199
+ tensor.name + b'_hadamard_matrix',
200
+ hadamard_matrix.astype(np.float32),
201
+ schema_py_generated.TensorType.FLOAT32,
202
+ transformation_input.subgraph,
203
+ transformation_input.buffers,
204
+ )
205
+
206
+ # Insert x' = tfl.fully_connected(x', hadamard_matrix)
207
+ fc_output_tensor_id = transformation_utils.add_new_activation_tensor(
208
+ tensor.name + b'_rotated',
209
+ prerotate_shape,
210
+ schema_py_generated.TensorType.FLOAT32,
211
+ transformation_input.subgraph,
212
+ )
213
+
214
+ fc_op_code_idx = transformation_utils.add_op_code(
215
+ schema_py_generated.BuiltinOperator.FULLY_CONNECTED,
216
+ transformation_input.op_codes,
217
+ 'FULLY_CONNECTED',
218
+ )
219
+ fc_op = schema_py_generated.OperatorT()
220
+ fc_op.opcodeIndex = fc_op_code_idx
221
+ fc_op.inputs = [prerotate_reshape_output_tensor_id, hadamard_matrix_tensor_id]
222
+ fc_op.outputs = [fc_output_tensor_id]
223
+
224
+ # Insert x' = tfl.reshape(x', x.shape)
225
+ post_reshape_op_code_idx = transformation_utils.add_op_code(
226
+ schema_py_generated.BuiltinOperator.RESHAPE,
227
+ transformation_input.op_codes,
228
+ 'RESHAPE',
229
+ )
230
+ post_reshape_op = schema_py_generated.OperatorT()
231
+ post_reshape_op.opcodeIndex = post_reshape_op_code_idx
232
+ post_reshape_shape_tensor_id = transformation_utils.add_new_constant_tensor(
233
+ tensor.name + b'_postrotate_shape',
234
+ np.array(tensor.shape, dtype=np.int32),
235
+ schema_py_generated.TensorType.INT32,
236
+ transformation_input.subgraph,
237
+ transformation_input.buffers,
238
+ )
239
+
240
+ post_reshape_output_tensor_id = (
241
+ transformation_utils.add_new_activation_tensor(
242
+ tensor.name + b'_postrotate_reshaped',
243
+ tensor.shape,
244
+ schema_py_generated.TensorType.FLOAT32,
245
+ transformation_input.subgraph,
246
+ )
247
+ )
248
+ post_reshape_op.inputs = [
249
+ fc_output_tensor_id,
250
+ post_reshape_shape_tensor_id,
251
+ ]
252
+ post_reshape_op.outputs = [post_reshape_output_tensor_id]
253
+
254
+ # Update the users of this tensor to use the new tensor.
255
+ if (
256
+ transformation_utils.get_producer_schema_op_id(transformation_input)
257
+ == schema_py_generated.BuiltinOperator.EMBEDDING_LOOKUP
258
+ ):
259
+ _update_embedding_lookup_consumers(
260
+ transformation_input, post_reshape_output_tensor_id
261
+ )
262
+ elif not _update_fully_connected_consumers(
263
+ transformation_input, post_reshape_output_tensor_id
264
+ ):
265
+ raise ValueError(
266
+ 'The Hadamard rotation op supports embedding lookup and fully connected'
267
+ ' ops only, but no such ops were found.'
268
+ )
269
+
270
+ # If the tensor is a graph output, we need to replace the tensor with the
271
+ # new tensor.
272
+ for i, output in enumerate(transformation_input.subgraph.outputs):
273
+ if output == transformation_input.tensor_id:
274
+ transformation_input.subgraph.outputs[i] = post_reshape_output_tensor_id
275
+
276
+ # Find the actual insertion point. The insertion point should be after the
277
+ # producer op and before the first consumer op. The max() operation ensures
278
+ # that we're not using -1 as the insertion point.
279
+ first_consumer_id = min(transformation_input.consumers)
280
+ op_id = max(transformation_input.producer + 1, first_consumer_id)
281
+
282
+ # Insert the new ops in the correct order.
283
+ transformation_input.subgraph.operators.insert(op_id, prerorate_reshape_op)
284
+ transformation_input.subgraph.operators.insert(op_id + 1, fc_op)
285
+ transformation_input.subgraph.operators.insert(op_id + 2, post_reshape_op)
286
+
287
+ return qtyping.TransformationInfo(
288
+ op_id=op_id,
289
+ num_ops_added=3,
290
+ output_tensor_id=post_reshape_output_tensor_id,
291
+ )
@@ -0,0 +1,244 @@
1
+ # Copyright 2024 The AI Edge Quantizer Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Test insertion of the Decomposed Hadamard rotation ops."""
17
+
18
+ import os
19
+ import numpy as np
20
+ from tensorflow.python.platform import googletest
21
+ from ai_edge_quantizer import qtyping
22
+ from ai_edge_quantizer.transformations import insert_decomposed_hadamard_rotation
23
+ from ai_edge_quantizer.transformations import transformation_utils
24
+ from ai_edge_quantizer.utils import test_utils
25
+ from ai_edge_quantizer.utils import tfl_flatbuffer_utils
26
+ from ai_edge_litert import schema_py_generated # pylint: disable=g-direct-tensorflow-import
27
+
28
+ _TEST_DATA_PREFIX_PATH = test_utils.get_path_to_datafile('..')
29
+
30
+
31
+ class InsertDecomposedHadamardRotationFullyConnectedTest(googletest.TestCase):
32
+
33
+ def setUp(self):
34
+ super().setUp()
35
+ model_path = os.path.join(
36
+ _TEST_DATA_PREFIX_PATH, 'tests/models/single_fc_bias.tflite'
37
+ )
38
+ self.model = tfl_flatbuffer_utils.read_model(model_path)
39
+ self.params = qtyping.UniformQuantParams(
40
+ num_bits=8,
41
+ quantized_dimension=None,
42
+ scale=np.ones(1),
43
+ zero_point=np.zeros(1),
44
+ hadamard=qtyping.UniformQuantParams.HadamardRotationParams(
45
+ random_binary_vector=np.ones(1),
46
+ hadamard_size=2,
47
+ ),
48
+ )
49
+
50
+ def test_raise_unsupported_qparams(self):
51
+ with self.assertRaisesWithPredicateMatch(
52
+ ValueError, lambda err: 'uniform quantization' in str(err)
53
+ ):
54
+ insert_decomposed_hadamard_rotation.insert_decomposed_hadamard_rotation(
55
+ transformation_utils.TransformationInput(
56
+ tensor_id=0,
57
+ op_codes=self.model.operatorCodes,
58
+ buffers=self.model.buffers,
59
+ subgraph=self.model.subgraphs[0],
60
+ producer=-1,
61
+ consumers=[-1],
62
+ quant_params=qtyping.NonLinearQuantParams(
63
+ num_bits=16, quantized_data=None
64
+ ),
65
+ )
66
+ )
67
+
68
+ def test_raise_missing_hadamard_data(self):
69
+ with self.assertRaisesWithPredicateMatch(
70
+ ValueError, lambda err: 'quantization params are not set' in str(err)
71
+ ):
72
+ insert_decomposed_hadamard_rotation.insert_decomposed_hadamard_rotation(
73
+ transformation_utils.TransformationInput(
74
+ tensor_id=0,
75
+ op_codes=self.model.operatorCodes,
76
+ buffers=self.model.buffers,
77
+ subgraph=self.model.subgraphs[0],
78
+ producer=-1,
79
+ consumers=[-1],
80
+ quant_params=qtyping.UniformQuantParams(
81
+ num_bits=8,
82
+ quantized_dimension=None,
83
+ scale=np.ones(1),
84
+ zero_point=np.zeros(1),
85
+ ),
86
+ )
87
+ )
88
+
89
+ def test_raise_non_float32_tensor(self):
90
+ self.model.subgraphs[0].tensors[
91
+ 0
92
+ ].type = schema_py_generated.TensorType.INT32
93
+ with self.assertRaisesWithPredicateMatch(
94
+ ValueError, lambda err: 'float32 tensors' in str(err)
95
+ ):
96
+ insert_decomposed_hadamard_rotation.insert_decomposed_hadamard_rotation(
97
+ transformation_utils.TransformationInput(
98
+ tensor_id=0,
99
+ op_codes=self.model.operatorCodes,
100
+ buffers=self.model.buffers,
101
+ subgraph=self.model.subgraphs[0],
102
+ producer=-1,
103
+ consumers=[-1],
104
+ quant_params=self.params,
105
+ ),
106
+ )
107
+
108
+ def test_insert_decomposed_ops(self):
109
+ # Insert Decomposed Hadamard ops before fully_connected
110
+ info = (
111
+ insert_decomposed_hadamard_rotation.insert_decomposed_hadamard_rotation(
112
+ transformation_utils.TransformationInput(
113
+ tensor_id=0,
114
+ op_codes=self.model.operatorCodes,
115
+ buffers=self.model.buffers,
116
+ subgraph=self.model.subgraphs[0],
117
+ producer=-1,
118
+ consumers=[0], # Consumer is the FC op
119
+ quant_params=self.params,
120
+ )
121
+ )
122
+ )
123
+ subgraph = self.model.subgraphs[0]
124
+ self.assertEqual(info.op_id, 0)
125
+ self.assertEqual(info.num_ops_added, 3)
126
+ # Model had 4 tensors, added 6 tensors (3 activations 3 constants).
127
+ self.assertEqual(info.output_tensor_id, 9)
128
+ self.assertLen(subgraph.tensors, 10)
129
+ # Model had 1 op code, added RESHAPE and FC.
130
+ self.assertLen(self.model.operatorCodes, 3)
131
+ self.assertEqual(
132
+ self.model.operatorCodes[1].builtinCode,
133
+ schema_py_generated.BuiltinOperator.RESHAPE,
134
+ )
135
+ self.assertEqual(
136
+ self.model.operatorCodes[2].builtinCode,
137
+ schema_py_generated.BuiltinOperator.FULLY_CONNECTED,
138
+ )
139
+
140
+ # Op 0: RESHAPE
141
+ reshape_op = subgraph.operators[0]
142
+ self.assertEqual(
143
+ self.model.operatorCodes[reshape_op.opcodeIndex].builtinCode,
144
+ schema_py_generated.BuiltinOperator.RESHAPE,
145
+ )
146
+ self.assertEqual(reshape_op.inputs[0], 0) # Graph input
147
+ self.assertEqual(reshape_op.outputs[0], 5) # Reshape output
148
+
149
+ # Op 1: FULLY_CONNECTED
150
+ fc_op = subgraph.operators[1]
151
+ self.assertEqual(
152
+ self.model.operatorCodes[fc_op.opcodeIndex].builtinCode,
153
+ schema_py_generated.BuiltinOperator.FULLY_CONNECTED,
154
+ )
155
+ self.assertEqual(fc_op.inputs[0], 5) # Reshape output
156
+ self.assertEqual(fc_op.inputs[1], 6) # Hadamard matrix tensor
157
+ self.assertEqual(fc_op.outputs[0], 7) # FC output
158
+
159
+ # Op 2: RESHAPE (post)
160
+ post_reshape_op = subgraph.operators[2]
161
+ self.assertEqual(
162
+ self.model.operatorCodes[post_reshape_op.opcodeIndex].builtinCode,
163
+ schema_py_generated.BuiltinOperator.RESHAPE,
164
+ )
165
+ self.assertEqual(post_reshape_op.inputs[0], 7) # FC output
166
+ self.assertEqual(post_reshape_op.outputs[0], 9) # Post Reshape output
167
+
168
+ # Op 3: Original FULLY_CONNECTED
169
+ orig_fc_op = subgraph.operators[3]
170
+ self.assertEqual(
171
+ self.model.operatorCodes[orig_fc_op.opcodeIndex].builtinCode,
172
+ schema_py_generated.BuiltinOperator.FULLY_CONNECTED,
173
+ )
174
+ # Input to the original FC is the post reshape output
175
+ self.assertEqual(orig_fc_op.inputs[0], 9)
176
+
177
+
178
+ class InsertDecomposedHadamardRotationEmbeddingLookupTest(googletest.TestCase):
179
+
180
+ def setUp(self):
181
+ super().setUp()
182
+ model_path = os.path.join(
183
+ _TEST_DATA_PREFIX_PATH, 'tests/models/embedding_lookup.tflite'
184
+ )
185
+ self.model = tfl_flatbuffer_utils.read_model(model_path)
186
+ self.params = qtyping.UniformQuantParams(
187
+ num_bits=8,
188
+ quantized_dimension=None,
189
+ scale=np.ones(1),
190
+ zero_point=np.zeros(1),
191
+ hadamard=qtyping.UniformQuantParams.HadamardRotationParams(
192
+ random_binary_vector=np.ones(1),
193
+ hadamard_size=2,
194
+ ),
195
+ )
196
+
197
+ def test_insert_decomposed_ops(self):
198
+ # Insert Decomposed Hadamard ops after embedding_lookup
199
+ info = (
200
+ insert_decomposed_hadamard_rotation.insert_decomposed_hadamard_rotation(
201
+ transformation_utils.TransformationInput(
202
+ tensor_id=2, # Output of embedding_lookup
203
+ op_codes=self.model.operatorCodes,
204
+ buffers=self.model.buffers,
205
+ subgraph=self.model.subgraphs[0],
206
+ producer=0,
207
+ consumers=[-1], # Output is a graph output
208
+ quant_params=self.params,
209
+ )
210
+ )
211
+ )
212
+ subgraph = self.model.subgraphs[0]
213
+ self.assertEqual(info.op_id, 1)
214
+ self.assertEqual(info.num_ops_added, 3)
215
+ # Model had 3 tensors, added 6 (3 activations 3 constants).
216
+ self.assertEqual(info.output_tensor_id, 8)
217
+ self.assertLen(subgraph.tensors, 9)
218
+ # Model had 1 op code, added RESHAPE and FC.
219
+ self.assertLen(self.model.operatorCodes, 3)
220
+
221
+ # Op 0: EMBEDDING_LOOKUP (Original)
222
+ # Op 1: RESHAPE
223
+ reshape_op = subgraph.operators[1]
224
+ self.assertEqual(reshape_op.inputs[0], 2) # Embedding lookup output
225
+ self.assertEqual(reshape_op.outputs[0], 4)
226
+
227
+ # Op 2: FULLY_CONNECTED
228
+ fc_op = subgraph.operators[2]
229
+ self.assertEqual(fc_op.inputs[0], 4)
230
+ self.assertEqual(fc_op.inputs[1], 5) # Hadamard matrix
231
+ self.assertEqual(fc_op.outputs[0], 6)
232
+
233
+ # Op 3: RESHAPE (post)
234
+ post_reshape_op = subgraph.operators[3]
235
+ self.assertEqual(post_reshape_op.inputs[0], 6)
236
+ self.assertEqual(post_reshape_op.outputs[0], 8)
237
+
238
+ # Check graph output
239
+ self.assertIn(8, subgraph.outputs)
240
+ self.assertNotIn(2, subgraph.outputs)
241
+
242
+
243
+ if __name__ == '__main__':
244
+ googletest.main()
@@ -34,35 +34,6 @@ def _to_flexbuffer(
34
34
  return fbb.Finish()
35
35
 
36
36
 
37
- def _is_producer_embedding_lookup(
38
- transformation: transformation_utils.TransformationInput,
39
- ) -> bool:
40
- """Checks if the tensor's producer is an embedding lookup op."""
41
- if transformation.producer == -1:
42
- return False
43
- else:
44
- return (
45
- transformation.op_codes[
46
- transformation.subgraph.operators[
47
- transformation.producer
48
- ].opcodeIndex
49
- ].builtinCode
50
- == schema_py_generated.BuiltinOperator.EMBEDDING_LOOKUP
51
- )
52
-
53
-
54
- def _is_fully_connected(
55
- transformation: transformation_utils.TransformationInput, op_id: int
56
- ) -> bool:
57
- """Checks if the any of the tensor's consumers is a fully connected op."""
58
- return (
59
- transformation.op_codes[
60
- transformation.subgraph.operators[op_id].opcodeIndex
61
- ].builtinCode
62
- == schema_py_generated.BuiltinOperator.FULLY_CONNECTED
63
- )
64
-
65
-
66
37
  def _update_embedding_lookup_consumers(
67
38
  transformation: transformation_utils.TransformationInput,
68
39
  new_tensor_id: int,
@@ -107,7 +78,10 @@ def _update_fully_connected_consumers(
107
78
  """
108
79
  updated = False
109
80
  for consumer in transformation.consumers:
110
- if _is_fully_connected(transformation, consumer):
81
+ if (
82
+ transformation_utils.get_schema_op_id(transformation, consumer)
83
+ == schema_py_generated.BuiltinOperator.FULLY_CONNECTED
84
+ ):
111
85
  transformation.subgraph.operators[consumer].inputs[0] = new_tensor_id
112
86
  updated = True
113
87
  return updated
@@ -177,7 +151,10 @@ def insert_hadamard_rotation(
177
151
  custom_op.outputs = [new_tensor_id]
178
152
 
179
153
  # Update the users of this tensor to use the new tensor.
180
- if _is_producer_embedding_lookup(transformation_input):
154
+ if (
155
+ transformation_utils.get_producer_schema_op_id(transformation_input)
156
+ == schema_py_generated.BuiltinOperator.EMBEDDING_LOOKUP
157
+ ):
181
158
  _update_embedding_lookup_consumers(transformation_input, new_tensor_id)
182
159
  elif not _update_fully_connected_consumers(
183
160
  transformation_input, new_tensor_id
@@ -68,29 +68,6 @@ def nonlinear_quant_params_to_tflite_type(
68
68
  raise ValueError(f"Unsupported nonlinear params: {bitwidth}")
69
69
 
70
70
 
71
- def _pack_data(bitwidth: int, flattened_data: np.ndarray) -> np.ndarray:
72
- """Pack the data to the corresponding bit width.
73
-
74
- Currently only support 4 bits. If no packing is needed, the original data is
75
- returned.
76
-
77
- Args:
78
- bitwidth: Bit width from NonLinearQuantParams.
79
- flattened_data: The data to be packed.
80
-
81
- Returns:
82
- Packed data.
83
- """
84
- if bitwidth == 4:
85
- even_data = flattened_data[::2] & 0x0F
86
- odd_data = np.left_shift(flattened_data[1::2], 4).astype(np.uint8)
87
- if odd_data.shape[0] == even_data.shape[0] - 1:
88
- odd_data = np.pad(odd_data, (0, 1), constant_values=0)
89
- return np.bitwise_or(even_data, odd_data)
90
- else:
91
- return flattened_data
92
-
93
-
94
71
  def _perform_channelwise_quantization(
95
72
  transformation_input: transformation_utils.TransformationInput,
96
73
  ) -> schema_py_generated.QuantizationParametersT():
@@ -180,14 +157,17 @@ def quantize_tensor(
180
157
  # is not provided.
181
158
  if tensor.buffer:
182
159
  if transformation_input.quant_params.quantized_data is not None:
183
- transformation_input.buffers[tensor.buffer].data = _pack_data(
184
- transformation_input.quant_params.num_bits,
185
- np.frombuffer(
186
- cast(
187
- np.ndarray, transformation_input.quant_params.quantized_data
188
- ).tobytes(),
189
- dtype=np.uint8,
190
- ).flatten(),
160
+ transformation_input.buffers[tensor.buffer].data = (
161
+ transformation_utils.pack_data(
162
+ transformation_input.quant_params.num_bits,
163
+ np.frombuffer(
164
+ cast(
165
+ np.ndarray,
166
+ transformation_input.quant_params.quantized_data,
167
+ ).tobytes(),
168
+ dtype=np.uint8,
169
+ ).flatten(),
170
+ )
191
171
  )
192
172
 
193
173
  if isinstance(transformation_input.quant_params, qtyping.UniformQuantParams):