tf-models-nightly 2.17.0.dev20240603__py2.py3-none-any.whl → 2.17.0.dev20240605__py2.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.
@@ -0,0 +1,208 @@
1
+ # Copyright 2024 The TensorFlow 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
+ """Keras-based attention layers to support multi-query attention.
16
+
17
+ Based on https://arxiv.org/pdf/1911.02150.pdf and
18
+ https://arxiv.org/pdf/2305.13245.pdf.
19
+ """
20
+
21
+ import string
22
+ from typing import Optional, Sequence, Union
23
+
24
+ import tensorflow as tf, tf_keras
25
+
26
+ _CHR_IDX = string.ascii_lowercase
27
+
28
+
29
+ def _build_proj_equation(
30
+ free_dims: int, bound_dims: int, output_dims: int
31
+ ) -> ...:
32
+ """Builds an einsum equation for projections inside attention layer.
33
+
34
+ Args:
35
+ free_dims: The number of free dimensions which are copied from input to
36
+ output.
37
+ bound_dims: The number of bound dimensions part of input which are combined
38
+ with the kernel to produce output.
39
+ output_dims: The number of output dimensions.
40
+
41
+ Returns:
42
+ A tuple of einsum equation, bias axes and output rank.
43
+ """
44
+
45
+ input_str = ""
46
+ kernel_str = ""
47
+ output_str = ""
48
+ bias_axes = ""
49
+ letter_offset = 0
50
+ for i in range(free_dims):
51
+ char = _CHR_IDX[i + letter_offset]
52
+ input_str += char
53
+ output_str += char
54
+
55
+ letter_offset += free_dims
56
+ for i in range(bound_dims):
57
+ char = _CHR_IDX[i + letter_offset]
58
+ input_str += char
59
+ kernel_str += char
60
+
61
+ letter_offset += bound_dims
62
+ for i in range(output_dims):
63
+ char = _CHR_IDX[i + letter_offset]
64
+ kernel_str += char
65
+ output_str += char
66
+ bias_axes += char
67
+ equation = f"{input_str},{kernel_str}->{output_str}"
68
+
69
+ return equation, bias_axes, len(output_str)
70
+
71
+
72
+ def _get_output_shape(
73
+ output_rank: int, known_last_dims: Sequence[int]
74
+ ) -> list[Optional[int]]:
75
+ return [None] * (output_rank - len(known_last_dims)) + list(known_last_dims)
76
+
77
+
78
+ class MultiHeadAttention(tf_keras.layers.MultiHeadAttention):
79
+ """Multi-query attention layer."""
80
+
81
+ def __init__(self, num_kv_heads=None, **kwargs):
82
+ # num_kv_heads defines the number of key/value heads. A value of 1 means
83
+ # that the key/value heads are shared across all query heads. Any other
84
+ # value must be less than num_heads and must divide num_heads exactly. If
85
+ # num_kv_heads is greater than 1, query heads are split into groups of
86
+ # num_kv_heads.
87
+ super().__init__(**kwargs)
88
+ self._num_kv_heads = num_kv_heads or self._num_heads
89
+ assert (
90
+ self._num_kv_heads < self._num_heads
91
+ ), "num_kv_heads must be less than num_heads."
92
+ assert (
93
+ self._num_heads % self._num_kv_heads == 0
94
+ ), "num_kv_heads needs to divide num_heads exactly."
95
+
96
+ def _build_from_signature(
97
+ self,
98
+ query: Union[tf.Tensor, tf.TensorShape],
99
+ value: Union[tf.Tensor, tf.TensorShape],
100
+ key: Optional[Union[tf.Tensor, tf.TensorShape]] = None,
101
+ ):
102
+ """Builds layers and variables.
103
+
104
+ Once the method is called, self._built_from_signature will be set to
105
+ True.
106
+
107
+ Args:
108
+ query: Query tensor or TensorShape.
109
+ value: Value tensor or TensorShape.
110
+ key: Key tensor or TensorShape.
111
+ """
112
+ # pytype: disable=attribute-error
113
+ super()._build_from_signature(query=query, value=value, key=key)
114
+ # pytype: enable=attribute-error
115
+
116
+ with tf.init_scope():
117
+ # Key, value are shared across heads in multi-query attention.
118
+ # Overwrite the K, V projections, logits & attend einsum equations to
119
+ # remove the number of attention head dimension in K, V related tensors.
120
+ #
121
+ # The following capital letters are used to denote the tensor dimension
122
+ # parameters:
123
+ # B = batch size
124
+ # S = length of the key/value (source)
125
+ # T = length of the query (target)
126
+ # N = number of query attention heads
127
+ # K = number of key/value heads
128
+ # n = N // K
129
+ # H = dimensions of each attention head.
130
+ #
131
+ if self._num_kv_heads == 1:
132
+ output_dims = 1
133
+ key_last_dims = [self._key_dim]
134
+ value_last_dims = [self._value_dim]
135
+ self._dot_product_equation = "...SH,...TNH->...NTS"
136
+ self._combine_equation = "...NTS,...SH->...TNH"
137
+ else:
138
+ output_dims = 2
139
+ key_last_dims = [self._num_kv_heads, self._key_dim]
140
+ value_last_dims = [self._num_kv_heads, self._value_dim]
141
+ self._dot_product_equation = "...SKH,...TKnH->...nKTS"
142
+ self._combine_equation = "...nKTS,...SKH->...TnKH"
143
+
144
+ einsum_equation, bias_axes, output_rank = _build_proj_equation(
145
+ free_dims=self._key_shape.rank - 1,
146
+ bound_dims=1,
147
+ output_dims=output_dims,
148
+ )
149
+ self._key_dense = tf_keras.layers.EinsumDense(
150
+ einsum_equation,
151
+ output_shape=_get_output_shape(output_rank - 1, key_last_dims),
152
+ bias_axes=bias_axes if self._use_bias else None,
153
+ name="key",
154
+ **self._get_common_kwargs_for_sublayer(),
155
+ )
156
+ einsum_equation, bias_axes, output_rank = _build_proj_equation(
157
+ free_dims=self._value_shape.rank - 1,
158
+ bound_dims=1,
159
+ output_dims=output_dims,
160
+ )
161
+ self._value_dense = tf_keras.layers.EinsumDense(
162
+ einsum_equation,
163
+ output_shape=_get_output_shape(output_rank - 1, value_last_dims),
164
+ bias_axes=bias_axes if self._use_bias else None,
165
+ name="value",
166
+ **self._get_common_kwargs_for_sublayer(),
167
+ )
168
+
169
+ def _compute_attention(
170
+ self, query, key, value, attention_mask=None, training=None
171
+ ):
172
+ if self._num_kv_heads > 1:
173
+ query = tf.reshape(
174
+ query,
175
+ [
176
+ tf.shape(query)[0],
177
+ tf.shape(query)[1],
178
+ self._num_kv_heads,
179
+ self._num_heads // self._num_kv_heads,
180
+ tf.shape(query)[-1],
181
+ ],
182
+ )
183
+
184
+ # pytype: disable=attribute-error
185
+ attention_output, attention_scores = super()._compute_attention(
186
+ query, key, value, attention_mask=attention_mask, training=training
187
+ )
188
+ # pytype: enable=attribute-error
189
+ if self._num_kv_heads != 1:
190
+ attention_output = tf.reshape(
191
+ attention_output,
192
+ [
193
+ tf.shape(attention_output)[0],
194
+ tf.shape(attention_output)[1],
195
+ self._num_heads,
196
+ tf.shape(attention_output)[-1],
197
+ ],
198
+ )
199
+ attention_scores = tf.reshape(
200
+ attention_scores,
201
+ [
202
+ tf.shape(attention_scores)[0],
203
+ self._num_heads,
204
+ tf.shape(attention_scores)[-2],
205
+ tf.shape(attention_scores)[-1],
206
+ ],
207
+ )
208
+ return attention_output, attention_scores
@@ -0,0 +1,215 @@
1
+ # Copyright 2024 The TensorFlow 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
+ """Tests for multi-query attention layer."""
16
+
17
+ from absl.testing import parameterized
18
+ import numpy as np
19
+ import tensorflow as tf, tf_keras
20
+
21
+ from official.nlp.modeling.layers import multi_query_attention
22
+
23
+
24
+ class MultiQueryAttentionTest(tf.test.TestCase, parameterized.TestCase):
25
+
26
+ @parameterized.named_parameters(
27
+ ("key_value_same_proj_mqa", 1, None, None, [40, 80]),
28
+ ("key_value_different_proj_mqa", 1, 32, 60, [40, 60]),
29
+ ("key_value_same_proj_gqa", 3, None, None, [40, 80]),
30
+ ("key_value_different_proj_gqa", 3, 32, 60, [40, 60]),
31
+ )
32
+ def test_non_masked_attention(
33
+ self, num_kv_heads, value_dim, output_shape, output_dims
34
+ ):
35
+ """Test that the attention layer can be created without a mask tensor."""
36
+ test_layer = multi_query_attention.MultiHeadAttention(
37
+ num_heads=12,
38
+ num_kv_heads=num_kv_heads,
39
+ key_dim=64,
40
+ value_dim=value_dim,
41
+ output_shape=output_shape,
42
+ )
43
+ # Create a 3-dimensional input (the first dimension is implicit).
44
+ query = tf_keras.Input(shape=(40, 80))
45
+ value = tf_keras.Input(shape=(20, 80))
46
+ output = test_layer(query=query, value=value)
47
+ self.assertEqual(output.shape.as_list(), [None] + output_dims)
48
+
49
+ @parameterized.named_parameters(
50
+ ("_mqa", 1),
51
+ ("_gqa", 3),
52
+ )
53
+ def test_non_masked_self_attention(self, num_kv_heads):
54
+ """Test with one input (self-attenntion) and no mask tensor."""
55
+ test_layer = multi_query_attention.MultiHeadAttention(
56
+ num_heads=12, num_kv_heads=num_kv_heads, key_dim=64
57
+ )
58
+ # Create a 3-dimensional input (the first dimension is implicit).
59
+ query = tf_keras.Input(shape=(40, 80))
60
+ output = test_layer(query, query)
61
+ self.assertEqual(output.shape.as_list(), [None, 40, 80])
62
+
63
+ @parameterized.named_parameters(
64
+ ("_mqa", 1),
65
+ ("_gqa", 3),
66
+ )
67
+ def test_attention_scores(self, num_kv_heads):
68
+ """Test attention outputs with coefficients."""
69
+ test_layer = multi_query_attention.MultiHeadAttention(
70
+ num_heads=12, num_kv_heads=num_kv_heads, key_dim=64
71
+ )
72
+ # Create a 3-dimensional input (the first dimension is implicit).
73
+ query = tf_keras.Input(shape=(40, 80))
74
+ output, coef = test_layer(query, query, return_attention_scores=True)
75
+ self.assertEqual(output.shape.as_list(), [None, 40, 80])
76
+ self.assertEqual(coef.shape.as_list(), [None, 12, 40, 40])
77
+
78
+ @parameterized.named_parameters(
79
+ ("_mqa", 1),
80
+ ("_gqa", 3),
81
+ )
82
+ def test_attention_scores_with_values(self, num_kv_heads):
83
+ """Test attention outputs with coefficients."""
84
+ test_layer = multi_query_attention.MultiHeadAttention(
85
+ num_heads=12, num_kv_heads=num_kv_heads, key_dim=64
86
+ )
87
+ # Create a 3-dimensional input (the first dimension is implicit).
88
+ query = tf_keras.Input(shape=(40, 80))
89
+ value = tf_keras.Input(shape=(60, 80))
90
+ output, coef = test_layer(query, value, return_attention_scores=True)
91
+ self.assertEqual(output.shape.as_list(), [None, 40, 80])
92
+ self.assertEqual(coef.shape.as_list(), [None, 12, 40, 60])
93
+
94
+ @parameterized.named_parameters(
95
+ ("with_bias_mqa", 1, True),
96
+ ("no_bias_mqa", 1, False),
97
+ ("with_bias_gqa", 2, True),
98
+ ("no_bias_gqa", 2, False),
99
+ )
100
+ def test_masked_attention(self, num_kv_heads, use_bias):
101
+ """Test with a mask tensor."""
102
+ test_layer = multi_query_attention.MultiHeadAttention(
103
+ num_heads=4, num_kv_heads=num_kv_heads, key_dim=2, use_bias=use_bias
104
+ )
105
+ # Create a 3-dimensional input (the first dimension is implicit).
106
+ batch_size = 3
107
+ query = tf_keras.Input(shape=(4, 8))
108
+ value = tf_keras.Input(shape=(2, 8))
109
+ mask_tensor = tf_keras.Input(shape=(4, 2))
110
+ output = test_layer(query=query, value=value, attention_mask=mask_tensor)
111
+
112
+ # Create a model containing the test layer.
113
+ model = tf_keras.Model([query, value, mask_tensor], output)
114
+
115
+ # Generate data for the input (non-mask) tensors.
116
+ from_data = 10 * np.random.random_sample((batch_size, 4, 8))
117
+ to_data = 10 * np.random.random_sample((batch_size, 2, 8))
118
+
119
+ # Invoke the data with a random set of mask data. This should mask at
120
+ # least one element.
121
+ mask_data = np.random.randint(2, size=(batch_size, 4, 2))
122
+ masked_output_data = model.predict([from_data, to_data, mask_data])
123
+
124
+ # Invoke the same data, but with a null mask (where no elements are
125
+ # masked).
126
+ null_mask_data = np.ones((batch_size, 4, 2))
127
+ unmasked_output_data = model.predict([from_data, to_data, null_mask_data])
128
+
129
+ # Because one data is masked and one is not, the outputs should not be
130
+ # the same.
131
+ self.assertNotAllClose(masked_output_data, unmasked_output_data)
132
+
133
+ # Tests the layer with three inputs: Q, K, V.
134
+ key = tf_keras.Input(shape=(2, 8))
135
+ output = test_layer(
136
+ query, value=value, key=key, attention_mask=mask_tensor
137
+ )
138
+ model = tf_keras.Model([query, value, key, mask_tensor], output)
139
+
140
+ masked_output_data = model.predict(
141
+ [from_data, to_data, to_data, mask_data]
142
+ )
143
+ unmasked_output_data = model.predict(
144
+ [from_data, to_data, to_data, null_mask_data]
145
+ )
146
+ # Because one data is masked and one is not, the outputs should not be
147
+ # the same.
148
+ self.assertNotAllClose(masked_output_data, unmasked_output_data)
149
+
150
+ if use_bias:
151
+ self.assertLen(test_layer._query_dense.trainable_variables, 2)
152
+ self.assertLen(test_layer._output_dense.trainable_variables, 2)
153
+ else:
154
+ self.assertLen(test_layer._query_dense.trainable_variables, 1)
155
+ self.assertLen(test_layer._output_dense.trainable_variables, 1)
156
+
157
+ @parameterized.named_parameters(
158
+ ("_mqa", 1),
159
+ ("_gqa", 2),
160
+ )
161
+ def test_masked_attention_with_scores(self, num_kv_heads):
162
+ """Test with a mask tensor."""
163
+ test_layer = multi_query_attention.MultiHeadAttention(
164
+ num_heads=4, num_kv_heads=num_kv_heads, key_dim=2
165
+ )
166
+ # Create a 3-dimensional input (the first dimension is implicit).
167
+ batch_size = 3
168
+ query = tf_keras.Input(shape=(4, 8))
169
+ value = tf_keras.Input(shape=(2, 8))
170
+ mask_tensor = tf_keras.Input(shape=(4, 2))
171
+ output = test_layer(query=query, value=value, attention_mask=mask_tensor)
172
+
173
+ # Create a model containing the test layer.
174
+ model = tf_keras.Model([query, value, mask_tensor], output)
175
+
176
+ # Generate data for the input (non-mask) tensors.
177
+ from_data = 10 * np.random.random_sample((batch_size, 4, 8))
178
+ to_data = 10 * np.random.random_sample((batch_size, 2, 8))
179
+
180
+ # Invoke the data with a random set of mask data. This should mask at
181
+ # least one element.
182
+ mask_data = np.random.randint(2, size=(batch_size, 4, 2))
183
+ masked_output_data = model.predict([from_data, to_data, mask_data])
184
+
185
+ # Invoke the same data, but with a null mask (where no elements are
186
+ # masked).
187
+ null_mask_data = np.ones((batch_size, 4, 2))
188
+ unmasked_output_data = model.predict([from_data, to_data, null_mask_data])
189
+
190
+ # Because one data is masked and one is not, the outputs should not be
191
+ # the same.
192
+ self.assertNotAllClose(masked_output_data, unmasked_output_data)
193
+
194
+ # Create a model containing attention scores.
195
+ output, scores = test_layer(
196
+ query=query,
197
+ value=value,
198
+ attention_mask=mask_tensor,
199
+ return_attention_scores=True,
200
+ )
201
+ model = tf_keras.Model([query, value, mask_tensor], [output, scores])
202
+ masked_output_data_score, masked_score = model.predict(
203
+ [from_data, to_data, mask_data]
204
+ )
205
+ unmasked_output_data_score, unmasked_score = model.predict(
206
+ [from_data, to_data, null_mask_data]
207
+ )
208
+ self.assertNotAllClose(masked_output_data_score, unmasked_output_data_score)
209
+ self.assertAllClose(masked_output_data, masked_output_data_score)
210
+ self.assertAllClose(unmasked_output_data, unmasked_output_data_score)
211
+ self.assertNotAllClose(masked_score, unmasked_score)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ tf.test.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: tf-models-nightly
3
- Version: 2.17.0.dev20240603
3
+ Version: 2.17.0.dev20240605
4
4
  Summary: TensorFlow Official Models
5
5
  Home-page: https://github.com/tensorflow/models
6
6
  Author: Google Inc.
@@ -329,6 +329,8 @@ official/nlp/modeling/layers/moe.py,sha256=azoK1Cz5l-5yT-FOtb7VYSbePTxmoje-2XAcq
329
329
  official/nlp/modeling/layers/moe_test.py,sha256=sr4hys2su_fcf9-6t0awqOkico92pQ3I2ApVF2rvvf0,9414
330
330
  official/nlp/modeling/layers/multi_channel_attention.py,sha256=fInxZUAPrrgCoCkM62JylM_vf5Wp8D0uZAvd5yuooVU,7322
331
331
  official/nlp/modeling/layers/multi_channel_attention_test.py,sha256=KcKuq22gOOq8HBzxRs3gGCwDRhmJPzYxfzfnqorQ1fw,1922
332
+ official/nlp/modeling/layers/multi_query_attention.py,sha256=fFPBa9IBVj_O5x5OfGuHUFnJmiouNL6F1KsBCeHUqwM,6978
333
+ official/nlp/modeling/layers/multi_query_attention_test.py,sha256=3VFF2hz85YExWPwdbhYWaSrIaSOkC1x7axdGfXr0W90,8512
332
334
  official/nlp/modeling/layers/on_device_embedding.py,sha256=FgsHyRXf5TWVTyo4OeKImmrTnn4uOPJgS3AGKzKMWYY,4582
333
335
  official/nlp/modeling/layers/on_device_embedding_test.py,sha256=M-LUba4QXV37s9Cx7aH8LL3bz_YotC6qITmWRI7Fhjk,8589
334
336
  official/nlp/modeling/layers/pack_optimization.py,sha256=C2prsYZMSkL8FBjz6Syc_Tu4JgzppaeIHyGDDoWzs8c,10289
@@ -1208,9 +1210,9 @@ tensorflow_models/tensorflow_models_test.py,sha256=nc6A9K53OGqF25xN5St8EiWvdVbda
1208
1210
  tensorflow_models/nlp/__init__.py,sha256=4tA5Pf4qaFwT-fIFOpX7x7FHJpnyJT-5UgOeFYTyMlc,807
1209
1211
  tensorflow_models/uplift/__init__.py,sha256=mqfa55gweOdpKoaQyid4A_4u7xw__FcQeSIF0k_pYmI,999
1210
1212
  tensorflow_models/vision/__init__.py,sha256=zBorY_v5xva1uI-qxhZO3Qh-Dii-Suq6wEYh6hKHDfc,833
1211
- tf_models_nightly-2.17.0.dev20240603.dist-info/AUTHORS,sha256=1dG3fXVu9jlo7bul8xuix5F5vOnczMk7_yWn4y70uw0,337
1212
- tf_models_nightly-2.17.0.dev20240603.dist-info/LICENSE,sha256=WxeBS_DejPZQabxtfMOM_xn8qoZNJDQjrT7z2wG1I4U,11512
1213
- tf_models_nightly-2.17.0.dev20240603.dist-info/METADATA,sha256=Fj0mx457IcSQcHiYjc70O0DG5eMD0AN70cXGWQ1eTnI,1432
1214
- tf_models_nightly-2.17.0.dev20240603.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
1215
- tf_models_nightly-2.17.0.dev20240603.dist-info/top_level.txt,sha256=gum2FfO5R4cvjl2-QtP-S1aNmsvIZaFFT6VFzU0f4-g,33
1216
- tf_models_nightly-2.17.0.dev20240603.dist-info/RECORD,,
1213
+ tf_models_nightly-2.17.0.dev20240605.dist-info/AUTHORS,sha256=1dG3fXVu9jlo7bul8xuix5F5vOnczMk7_yWn4y70uw0,337
1214
+ tf_models_nightly-2.17.0.dev20240605.dist-info/LICENSE,sha256=WxeBS_DejPZQabxtfMOM_xn8qoZNJDQjrT7z2wG1I4U,11512
1215
+ tf_models_nightly-2.17.0.dev20240605.dist-info/METADATA,sha256=labvP0g3N3RnTA_JolA4bI7gFsP8pdUUp9TNvaBJIgk,1432
1216
+ tf_models_nightly-2.17.0.dev20240605.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
1217
+ tf_models_nightly-2.17.0.dev20240605.dist-info/top_level.txt,sha256=gum2FfO5R4cvjl2-QtP-S1aNmsvIZaFFT6VFzU0f4-g,33
1218
+ tf_models_nightly-2.17.0.dev20240605.dist-info/RECORD,,