ai-edge-quantizer-nightly 0.0.1.dev20250302__py3-none-any.whl → 0.5.0.dev20260103__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.
- ai_edge_quantizer/algorithm_manager.py +224 -0
- ai_edge_quantizer/algorithm_manager_api_test.py +7 -0
- ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting_test.py +2 -2
- ai_edge_quantizer/algorithms/uniform_quantize/common_quantize.py +643 -20
- ai_edge_quantizer/algorithms/uniform_quantize/common_quantize_test.py +29 -2
- ai_edge_quantizer/algorithms/uniform_quantize/dequantized_weight_recovery.py +29 -35
- ai_edge_quantizer/algorithms/uniform_quantize/dequantized_weight_recovery_test.py +35 -12
- ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation.py +414 -0
- ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation_test.py +440 -0
- ai_edge_quantizer/algorithms/uniform_quantize/mse.py +127 -0
- ai_edge_quantizer/algorithms/uniform_quantize/mse_test.py +195 -0
- ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize.py +54 -168
- ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize_test.py +54 -17
- ai_edge_quantizer/algorithms/uniform_quantize/octav.py +188 -0
- ai_edge_quantizer/algorithms/uniform_quantize/octav_test.py +240 -0
- ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor.py +260 -13
- ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor_test.py +152 -5
- ai_edge_quantizer/algorithms/utils/common_utils.py +142 -54
- ai_edge_quantizer/calibrator.py +58 -94
- ai_edge_quantizer/calibrator_test.py +5 -74
- ai_edge_quantizer/default_policy.py +108 -16
- ai_edge_quantizer/model_modifier.py +132 -8
- ai_edge_quantizer/model_modifier_test.py +81 -1
- ai_edge_quantizer/model_validator.py +38 -10
- ai_edge_quantizer/model_validator_test.py +2 -1
- ai_edge_quantizer/params_generator.py +230 -47
- ai_edge_quantizer/params_generator_test.py +366 -261
- ai_edge_quantizer/qtyping.py +92 -6
- ai_edge_quantizer/quantizer.py +167 -23
- ai_edge_quantizer/quantizer_test.py +288 -26
- ai_edge_quantizer/recipe.py +156 -21
- ai_edge_quantizer/recipe_manager.py +158 -1
- ai_edge_quantizer/recipe_manager_test.py +146 -32
- ai_edge_quantizer/recipe_test.py +93 -17
- ai_edge_quantizer/transformation_instruction_generator.py +313 -46
- ai_edge_quantizer/transformation_instruction_generator_test.py +449 -27
- ai_edge_quantizer/transformation_performer.py +112 -58
- ai_edge_quantizer/transformation_performer_test.py +176 -4
- ai_edge_quantizer/transformations/duplicate_buffer.py +46 -0
- ai_edge_quantizer/transformations/duplicate_buffer_test.py +106 -0
- ai_edge_quantizer/transformations/duplicate_tensor.py +62 -0
- ai_edge_quantizer/transformations/duplicate_tensor_test.py +131 -0
- ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation.py +299 -0
- ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation_test.py +244 -0
- ai_edge_quantizer/transformations/insert_hadamard_rotation.py +186 -0
- ai_edge_quantizer/transformations/insert_hadamard_rotation_test.py +200 -0
- ai_edge_quantizer/transformations/quantize_tensor.py +24 -44
- ai_edge_quantizer/transformations/quantize_tensor_test.py +3 -2
- ai_edge_quantizer/transformations/transformation_utils.py +157 -11
- ai_edge_quantizer/transformations/transformation_utils_test.py +96 -2
- ai_edge_quantizer/utils/calibration_utils.py +263 -1
- ai_edge_quantizer/utils/calibration_utils_test.py +173 -3
- ai_edge_quantizer/utils/constrained_ops_utils.py +111 -0
- ai_edge_quantizer/utils/constrained_ops_utils_test.py +50 -0
- ai_edge_quantizer/utils/test_utils.py +191 -58
- ai_edge_quantizer/utils/tfl_flatbuffer_utils.py +96 -50
- ai_edge_quantizer/utils/tfl_flatbuffer_utils_test.py +20 -0
- ai_edge_quantizer/utils/tfl_interpreter_utils.py +138 -5
- ai_edge_quantizer/utils/tfl_interpreter_utils_test.py +29 -2
- ai_edge_quantizer/utils/validation_utils.py +114 -4
- ai_edge_quantizer/utils/validation_utils_test.py +80 -0
- {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/METADATA +13 -3
- ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info/RECORD +81 -0
- {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/WHEEL +1 -1
- ai_edge_quantizer/transformations/emulated_subchannel.py +0 -363
- ai_edge_quantizer/transformations/emulated_subchannel_test.py +0 -212
- ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info/RECORD +0 -67
- {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info/licenses}/LICENSE +0 -0
- {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
"""Duplicate tensor transformation."""
|
|
17
|
+
|
|
18
|
+
from ai_edge_quantizer import qtyping
|
|
19
|
+
from ai_edge_quantizer.transformations import transformation_utils
|
|
20
|
+
from ai_edge_quantizer.utils import tfl_flatbuffer_utils
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def duplicate_tensor(
|
|
24
|
+
transformation_input: transformation_utils.TransformationInput,
|
|
25
|
+
) -> qtyping.TransformationInfo:
|
|
26
|
+
"""Duplicates the tensor."""
|
|
27
|
+
tensor_id = transformation_input.tensor_id
|
|
28
|
+
subgraph = transformation_input.subgraph
|
|
29
|
+
tensor = subgraph.tensors[tensor_id]
|
|
30
|
+
tensor_name = tfl_flatbuffer_utils.get_tensor_name(tensor)
|
|
31
|
+
buffer_data = transformation_input.buffers[tensor.buffer].data
|
|
32
|
+
if buffer_data is None:
|
|
33
|
+
raise ValueError(
|
|
34
|
+
'Duplicate Tensor transformation supports only constant tensors.'
|
|
35
|
+
f' Tensor {tensor_name} is not constant.'
|
|
36
|
+
)
|
|
37
|
+
new_tensor_id = transformation_utils.add_new_constant_tensor(
|
|
38
|
+
tensor_name=f'{tensor_name}_duplicated',
|
|
39
|
+
data=buffer_data,
|
|
40
|
+
tensor_type=tensor.type,
|
|
41
|
+
tensor_shape=tensor.shape,
|
|
42
|
+
subgraph=subgraph,
|
|
43
|
+
buffers=transformation_input.buffers,
|
|
44
|
+
force_duplicate_buffer=True,
|
|
45
|
+
)
|
|
46
|
+
# Update the tensor name to avoid name collision in case when tensor is
|
|
47
|
+
# duplicated mulitple times.
|
|
48
|
+
subgraph.tensors[new_tensor_id].name += f'_{new_tensor_id}'
|
|
49
|
+
|
|
50
|
+
# Update the consumers' input tensor id to the duplicated tensor id.
|
|
51
|
+
# Assuming transformation_input to contain all and only consumers that are
|
|
52
|
+
# supposed to use this new duplicated tensor.
|
|
53
|
+
for consumer in transformation_input.consumers:
|
|
54
|
+
consumer_inputs = subgraph.operators[consumer].inputs
|
|
55
|
+
for i in range(len(consumer_inputs)):
|
|
56
|
+
if consumer_inputs[i] == tensor_id:
|
|
57
|
+
consumer_inputs[i] = new_tensor_id
|
|
58
|
+
break
|
|
59
|
+
|
|
60
|
+
return qtyping.TransformationInfo(
|
|
61
|
+
op_id=0, num_ops_added=0, output_tensor_id=new_tensor_id
|
|
62
|
+
)
|
|
@@ -0,0 +1,131 @@
|
|
|
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
|
+
import os
|
|
17
|
+
import numpy as np
|
|
18
|
+
from tensorflow.python.platform import googletest
|
|
19
|
+
from ai_edge_quantizer import qtyping
|
|
20
|
+
from ai_edge_quantizer.transformations import duplicate_tensor
|
|
21
|
+
from ai_edge_quantizer.transformations import transformation_utils
|
|
22
|
+
from ai_edge_quantizer.utils import test_utils
|
|
23
|
+
from ai_edge_quantizer.utils import tfl_flatbuffer_utils
|
|
24
|
+
|
|
25
|
+
TEST_DATA_PREFIX_PATH = test_utils.get_path_to_datafile('..')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DuplicateTensorTest(googletest.TestCase):
|
|
29
|
+
|
|
30
|
+
def setUp(self):
|
|
31
|
+
super().setUp()
|
|
32
|
+
model_path = os.path.join(
|
|
33
|
+
TEST_DATA_PREFIX_PATH, 'tests/models/weight_sharing_fcs.tflite'
|
|
34
|
+
)
|
|
35
|
+
self.model = tfl_flatbuffer_utils.read_model(model_path)
|
|
36
|
+
|
|
37
|
+
def _get_transformation_input(
|
|
38
|
+
self,
|
|
39
|
+
subgraph_idx: int,
|
|
40
|
+
tensor_idx: int,
|
|
41
|
+
consumers: list[int],
|
|
42
|
+
) -> transformation_utils.TransformationInput:
|
|
43
|
+
return transformation_utils.TransformationInput(
|
|
44
|
+
tensor_id=tensor_idx,
|
|
45
|
+
buffers=self.model.buffers,
|
|
46
|
+
consumers=consumers,
|
|
47
|
+
# Dummy params below.
|
|
48
|
+
op_codes=self.model.operatorCodes,
|
|
49
|
+
subgraph=self.model.subgraphs[subgraph_idx],
|
|
50
|
+
producer=-1,
|
|
51
|
+
quant_params=qtyping.UniformQuantParams(
|
|
52
|
+
num_bits=8,
|
|
53
|
+
quantized_dimension=None,
|
|
54
|
+
scale=np.ones(1),
|
|
55
|
+
zero_point=np.zeros(1),
|
|
56
|
+
),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def test_constant_tensor_is_correctly_duplicated(self):
|
|
60
|
+
# Duplicate the FC weight tensor in the second subgraph for the first FC.
|
|
61
|
+
subgraph_idx = 1
|
|
62
|
+
fc1_op_idx = 0
|
|
63
|
+
prev_weight_tensor_idx = 1
|
|
64
|
+
subgraph = self.model.subgraphs[subgraph_idx]
|
|
65
|
+
weight_idx_in_op_inputs = list(subgraph.operators[fc1_op_idx].inputs).index(
|
|
66
|
+
prev_weight_tensor_idx
|
|
67
|
+
)
|
|
68
|
+
prev_num_tensors = len(subgraph.tensors)
|
|
69
|
+
prev_buffer_id = subgraph.tensors[prev_weight_tensor_idx].buffer
|
|
70
|
+
prev_num_buffers = len(self.model.buffers)
|
|
71
|
+
transformation_input = self._get_transformation_input(
|
|
72
|
+
subgraph_idx, prev_weight_tensor_idx, consumers=[fc1_op_idx]
|
|
73
|
+
)
|
|
74
|
+
transformation_info = duplicate_tensor.duplicate_tensor(
|
|
75
|
+
transformation_input
|
|
76
|
+
)
|
|
77
|
+
self.assertEqual(transformation_info.op_id, 0)
|
|
78
|
+
self.assertEqual(transformation_info.num_ops_added, 0)
|
|
79
|
+
# Check that a new tensor and buffer were added.
|
|
80
|
+
self.assertLen(subgraph.tensors, prev_num_tensors + 1)
|
|
81
|
+
self.assertLen(self.model.buffers, prev_num_buffers + 1)
|
|
82
|
+
# Check that the duplicated tensor is the last tensor in the subgraph.
|
|
83
|
+
weight_tensor_idx = transformation_info.output_tensor_id
|
|
84
|
+
self.assertEqual(weight_tensor_idx, len(subgraph.tensors) - 1)
|
|
85
|
+
# Compare tensors.
|
|
86
|
+
original_tensor = subgraph.tensors[prev_weight_tensor_idx]
|
|
87
|
+
original_tensor_name = tfl_flatbuffer_utils.get_tensor_name(original_tensor)
|
|
88
|
+
duplicated_tensor = subgraph.tensors[weight_tensor_idx]
|
|
89
|
+
self.assertEqual(
|
|
90
|
+
duplicated_tensor.name,
|
|
91
|
+
f'{original_tensor_name}_duplicated_{weight_tensor_idx}',
|
|
92
|
+
)
|
|
93
|
+
self.assertEqual(duplicated_tensor.type, original_tensor.type)
|
|
94
|
+
self.assertTrue(np.all(duplicated_tensor.shape == original_tensor.shape))
|
|
95
|
+
# Check that the new buffer is used by the duplicated tensor.
|
|
96
|
+
new_buffer_id = len(self.model.buffers) - 1
|
|
97
|
+
self.assertEqual(duplicated_tensor.buffer, new_buffer_id)
|
|
98
|
+
# Check that the new buffer has the same data as the original one.
|
|
99
|
+
self.assertTrue(
|
|
100
|
+
np.all(
|
|
101
|
+
np.frombuffer(
|
|
102
|
+
self.model.buffers[new_buffer_id].data,
|
|
103
|
+
dtype=np.float32,
|
|
104
|
+
)
|
|
105
|
+
== np.frombuffer(
|
|
106
|
+
self.model.buffers[prev_buffer_id].data,
|
|
107
|
+
dtype=np.float32,
|
|
108
|
+
)
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
# Check that first FC input tensor id was updated.
|
|
112
|
+
self.assertEqual(
|
|
113
|
+
subgraph.operators[fc1_op_idx].inputs[weight_idx_in_op_inputs],
|
|
114
|
+
weight_tensor_idx,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def test_duplicate_tensor_raises_error_when_tensor_is_not_constant(self):
|
|
118
|
+
# Duplicate the FC input tensor in the second subgraph.
|
|
119
|
+
subgraph_idx = 1
|
|
120
|
+
input_tensor_idx = 0
|
|
121
|
+
transformation_input = self._get_transformation_input(
|
|
122
|
+
subgraph_idx, input_tensor_idx, consumers=[0]
|
|
123
|
+
)
|
|
124
|
+
with self.assertRaisesRegex(
|
|
125
|
+
ValueError,
|
|
126
|
+
'Duplicate Tensor transformation supports only constant tensors.',
|
|
127
|
+
):
|
|
128
|
+
duplicate_tensor.duplicate_tensor(transformation_input)
|
|
129
|
+
|
|
130
|
+
if __name__ == '__main__':
|
|
131
|
+
googletest.main()
|
|
@@ -0,0 +1,299 @@
|
|
|
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
|
+
fc_options = schema_py_generated.FullyConnectedOptionsT()
|
|
224
|
+
fc_options.fusedActivationFunction = (
|
|
225
|
+
schema_py_generated.ActivationFunctionType.NONE
|
|
226
|
+
)
|
|
227
|
+
fc_op.builtinOptionsType = (
|
|
228
|
+
schema_py_generated.BuiltinOptions.FullyConnectedOptions
|
|
229
|
+
)
|
|
230
|
+
fc_op.builtinOptions = fc_options
|
|
231
|
+
|
|
232
|
+
# Insert x' = tfl.reshape(x', x.shape)
|
|
233
|
+
post_reshape_op_code_idx = transformation_utils.add_op_code(
|
|
234
|
+
schema_py_generated.BuiltinOperator.RESHAPE,
|
|
235
|
+
transformation_input.op_codes,
|
|
236
|
+
'RESHAPE',
|
|
237
|
+
)
|
|
238
|
+
post_reshape_op = schema_py_generated.OperatorT()
|
|
239
|
+
post_reshape_op.opcodeIndex = post_reshape_op_code_idx
|
|
240
|
+
post_reshape_shape_tensor_id = transformation_utils.add_new_constant_tensor(
|
|
241
|
+
tensor.name + b'_postrotate_shape',
|
|
242
|
+
np.array(tensor.shape, dtype=np.int32),
|
|
243
|
+
schema_py_generated.TensorType.INT32,
|
|
244
|
+
transformation_input.subgraph,
|
|
245
|
+
transformation_input.buffers,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
post_reshape_output_tensor_id = (
|
|
249
|
+
transformation_utils.add_new_activation_tensor(
|
|
250
|
+
tensor.name + b'_postrotate_reshaped',
|
|
251
|
+
tensor.shape,
|
|
252
|
+
schema_py_generated.TensorType.FLOAT32,
|
|
253
|
+
transformation_input.subgraph,
|
|
254
|
+
)
|
|
255
|
+
)
|
|
256
|
+
post_reshape_op.inputs = [
|
|
257
|
+
fc_output_tensor_id,
|
|
258
|
+
post_reshape_shape_tensor_id,
|
|
259
|
+
]
|
|
260
|
+
post_reshape_op.outputs = [post_reshape_output_tensor_id]
|
|
261
|
+
|
|
262
|
+
# Update the users of this tensor to use the new tensor.
|
|
263
|
+
if (
|
|
264
|
+
transformation_utils.get_producer_schema_op_id(transformation_input)
|
|
265
|
+
== schema_py_generated.BuiltinOperator.EMBEDDING_LOOKUP
|
|
266
|
+
):
|
|
267
|
+
_update_embedding_lookup_consumers(
|
|
268
|
+
transformation_input, post_reshape_output_tensor_id
|
|
269
|
+
)
|
|
270
|
+
elif not _update_fully_connected_consumers(
|
|
271
|
+
transformation_input, post_reshape_output_tensor_id
|
|
272
|
+
):
|
|
273
|
+
raise ValueError(
|
|
274
|
+
'The Hadamard rotation op supports embedding lookup and fully connected'
|
|
275
|
+
' ops only, but no such ops were found.'
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
# If the tensor is a graph output, we need to replace the tensor with the
|
|
279
|
+
# new tensor.
|
|
280
|
+
for i, output in enumerate(transformation_input.subgraph.outputs):
|
|
281
|
+
if output == transformation_input.tensor_id:
|
|
282
|
+
transformation_input.subgraph.outputs[i] = post_reshape_output_tensor_id
|
|
283
|
+
|
|
284
|
+
# Find the actual insertion point. The insertion point should be after the
|
|
285
|
+
# producer op and before the first consumer op. The max() operation ensures
|
|
286
|
+
# that we're not using -1 as the insertion point.
|
|
287
|
+
first_consumer_id = min(transformation_input.consumers)
|
|
288
|
+
op_id = max(transformation_input.producer + 1, first_consumer_id)
|
|
289
|
+
|
|
290
|
+
# Insert the new ops in the correct order.
|
|
291
|
+
transformation_input.subgraph.operators.insert(op_id, prerorate_reshape_op)
|
|
292
|
+
transformation_input.subgraph.operators.insert(op_id + 1, fc_op)
|
|
293
|
+
transformation_input.subgraph.operators.insert(op_id + 2, post_reshape_op)
|
|
294
|
+
|
|
295
|
+
return qtyping.TransformationInfo(
|
|
296
|
+
op_id=op_id,
|
|
297
|
+
num_ops_added=3,
|
|
298
|
+
output_tensor_id=post_reshape_output_tensor_id,
|
|
299
|
+
)
|