keras-hub-nightly 0.20.0.dev202503160355__py3-none-any.whl → 0.20.0.dev202503180354__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.
- keras_hub/api/models/__init__.py +18 -0
- keras_hub/api/tokenizers/__init__.py +4 -0
- keras_hub/src/layers/preprocessing/image_converter.py +5 -2
- keras_hub/src/models/qwen/__init__.py +1 -0
- keras_hub/src/models/qwen/qwen_attention.py +358 -0
- keras_hub/src/models/qwen/qwen_backbone.py +327 -0
- keras_hub/src/models/qwen/qwen_causal_lm.py +300 -0
- keras_hub/src/models/qwen/qwen_causal_lm_preprocessor.py +18 -0
- keras_hub/src/models/qwen/qwen_decoder.py +311 -0
- keras_hub/src/models/qwen/qwen_layernorm.py +32 -0
- keras_hub/src/models/qwen/qwen_tokenizer.py +51 -0
- keras_hub/src/utils/transformers/convert_qwen.py +148 -0
- keras_hub/src/utils/transformers/preset_loader.py +3 -0
- keras_hub/src/version_utils.py +1 -1
- {keras_hub_nightly-0.20.0.dev202503160355.dist-info → keras_hub_nightly-0.20.0.dev202503180354.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.20.0.dev202503160355.dist-info → keras_hub_nightly-0.20.0.dev202503180354.dist-info}/RECORD +18 -9
- {keras_hub_nightly-0.20.0.dev202503160355.dist-info → keras_hub_nightly-0.20.0.dev202503180354.dist-info}/WHEEL +1 -1
- {keras_hub_nightly-0.20.0.dev202503160355.dist-info → keras_hub_nightly-0.20.0.dev202503180354.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,327 @@
|
|
1
|
+
import keras
|
2
|
+
from keras import ops
|
3
|
+
|
4
|
+
from keras_hub.src.api_export import keras_hub_export
|
5
|
+
from keras_hub.src.layers.modeling.reversible_embedding import (
|
6
|
+
ReversibleEmbedding,
|
7
|
+
)
|
8
|
+
from keras_hub.src.models.backbone import Backbone
|
9
|
+
from keras_hub.src.models.qwen.qwen_decoder import QwenTransformerDecoder
|
10
|
+
from keras_hub.src.models.qwen.qwen_layernorm import QwenLayerNorm
|
11
|
+
|
12
|
+
|
13
|
+
def _qwen_kernel_initializer(stddev=0.02):
|
14
|
+
return keras.initializers.RandomNormal(stddev=stddev)
|
15
|
+
|
16
|
+
|
17
|
+
@keras_hub_export(
|
18
|
+
[
|
19
|
+
"keras_hub.models.QwenBackbone",
|
20
|
+
"keras_hub.models.Qwen2Backbone",
|
21
|
+
]
|
22
|
+
)
|
23
|
+
class QwenBackbone(Backbone):
|
24
|
+
"""
|
25
|
+
The Qwen Transformer core architecture with hyperparameters.
|
26
|
+
|
27
|
+
This network implements a Transformer-based decoder network,
|
28
|
+
Qwen, as described in the Qwen model architecture.
|
29
|
+
It includes the embedding lookups and transformer layers.
|
30
|
+
|
31
|
+
The default constructor gives a fully customizable, randomly initialized
|
32
|
+
Qwen model with any number of layers, heads, and embedding
|
33
|
+
dimensions. To load preset architectures and weights, use the `from_preset`
|
34
|
+
constructor.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
vocabulary_size (int): The size of the token vocabulary.
|
38
|
+
num_layers (int): The number of transformer layers.
|
39
|
+
num_query_heads (int): The number of query attention heads for
|
40
|
+
each transformer.
|
41
|
+
hidden_dim (int): The size of the transformer encoding and pooling
|
42
|
+
layers.
|
43
|
+
intermediate_dim (int): The output dimension of the first Dense layer in
|
44
|
+
a three-layer feedforward network for each transformer.
|
45
|
+
num_key_value_heads (int): The number of key and value attention heads
|
46
|
+
for each transformer.
|
47
|
+
rope_max_wavelength (int, optional): The maximum angular wavelength of
|
48
|
+
the sine/cosine curves, for rotary embeddings. Defaults to `10000`.
|
49
|
+
rope_scaling_factor (float, optional): The scaling factor for
|
50
|
+
calculation of rotary embedding. Defaults to `1.0`.
|
51
|
+
layer_norm_epsilon (float, optional): Epsilon for the layer
|
52
|
+
normalization layers in the transformer decoder. Defaults to `1e-6`.
|
53
|
+
dropout (float, optional): Dropout rate for attention and hidden layers.
|
54
|
+
Defaults to `0`.
|
55
|
+
dtype: string or `keras.mixed_precision.DTypePolicy`. The dtype to use
|
56
|
+
for model computations and weights. Note that some computations,
|
57
|
+
such as softmax and layer normalization, will always be done at
|
58
|
+
float32 precision regardless of dtype.
|
59
|
+
tie_word_embeddings (bool, optional): Whether to tie input and output
|
60
|
+
embeddings. Defaults to `True`.
|
61
|
+
use_sliding_window_attention (bool, optional): Whether to use sliding
|
62
|
+
window attention for efficient processing of long sequences.
|
63
|
+
Defaults to `False`.
|
64
|
+
sliding_window_size (int, optional): Size of the sliding window for
|
65
|
+
attention when enabled. Defaults to `32768`.
|
66
|
+
|
67
|
+
Examples:
|
68
|
+
|
69
|
+
```python
|
70
|
+
input_data = {
|
71
|
+
"token_ids": np.ones(shape=(1, 12), dtype="int32"),
|
72
|
+
"padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]),
|
73
|
+
}
|
74
|
+
|
75
|
+
# Pretrained Qwen decoder.
|
76
|
+
model = keras_hub.models.QwenBackbone.from_preset("qwen2.5_0.5b_en")
|
77
|
+
model(input_data)
|
78
|
+
|
79
|
+
# Randomly initialized Qwen decoder with custom config.
|
80
|
+
model = keras_hub.models.QwenBackbone(
|
81
|
+
vocabulary_size=10,
|
82
|
+
hidden_dim=512,
|
83
|
+
num_layers=2,
|
84
|
+
num_query_heads=32,
|
85
|
+
num_key_value_heads=8,
|
86
|
+
intermediate_dim=1024,
|
87
|
+
layer_norm_epsilon=1e-6,
|
88
|
+
dtype="float32"
|
89
|
+
)
|
90
|
+
model(input_data)
|
91
|
+
```
|
92
|
+
"""
|
93
|
+
|
94
|
+
def __init__(
|
95
|
+
self,
|
96
|
+
vocabulary_size,
|
97
|
+
num_layers,
|
98
|
+
num_query_heads,
|
99
|
+
num_key_value_heads,
|
100
|
+
hidden_dim,
|
101
|
+
intermediate_dim,
|
102
|
+
rope_max_wavelength=10000,
|
103
|
+
rope_scaling_factor=1.0,
|
104
|
+
layer_norm_epsilon=1e-6,
|
105
|
+
dropout=0,
|
106
|
+
dtype=None,
|
107
|
+
tie_word_embeddings=True,
|
108
|
+
use_sliding_window_attention=False,
|
109
|
+
sliding_window_size=32768,
|
110
|
+
**kwargs,
|
111
|
+
):
|
112
|
+
# === Layers ===
|
113
|
+
self.token_embedding = ReversibleEmbedding(
|
114
|
+
input_dim=vocabulary_size,
|
115
|
+
output_dim=hidden_dim,
|
116
|
+
tie_weights=tie_word_embeddings,
|
117
|
+
embeddings_initializer=_qwen_kernel_initializer(stddev=0.01),
|
118
|
+
dtype=dtype,
|
119
|
+
name="token_embedding",
|
120
|
+
)
|
121
|
+
self.transformer_layers = []
|
122
|
+
for i in range(num_layers):
|
123
|
+
layer = QwenTransformerDecoder(
|
124
|
+
intermediate_dim=intermediate_dim,
|
125
|
+
num_query_heads=num_query_heads,
|
126
|
+
num_key_value_heads=num_key_value_heads,
|
127
|
+
rope_max_wavelength=rope_max_wavelength,
|
128
|
+
rope_scaling_factor=rope_scaling_factor,
|
129
|
+
layer_norm_epsilon=layer_norm_epsilon,
|
130
|
+
activation=ops.silu,
|
131
|
+
kernel_initializer=_qwen_kernel_initializer(stddev=0.02),
|
132
|
+
dropout=dropout,
|
133
|
+
dtype=dtype,
|
134
|
+
use_sliding_window_attention=use_sliding_window_attention,
|
135
|
+
sliding_window_size=sliding_window_size,
|
136
|
+
name=f"transformer_layer_{i}",
|
137
|
+
)
|
138
|
+
self.transformer_layers.append(layer)
|
139
|
+
self.layer_norm = QwenLayerNorm(
|
140
|
+
epsilon=layer_norm_epsilon,
|
141
|
+
dtype=dtype,
|
142
|
+
name="sequence_output_layernorm",
|
143
|
+
)
|
144
|
+
|
145
|
+
# === Functional Model ===
|
146
|
+
token_id_input = keras.Input(
|
147
|
+
shape=(None,), dtype="int32", name="token_ids"
|
148
|
+
)
|
149
|
+
padding_mask_input = keras.Input(
|
150
|
+
shape=(None,), dtype="int32", name="padding_mask"
|
151
|
+
)
|
152
|
+
x = self.token_embedding(token_id_input)
|
153
|
+
for transformer_layer in self.transformer_layers:
|
154
|
+
x = transformer_layer(x, decoder_padding_mask=padding_mask_input)
|
155
|
+
sequence_output = self.layer_norm(x)
|
156
|
+
super().__init__(
|
157
|
+
inputs={
|
158
|
+
"token_ids": token_id_input,
|
159
|
+
"padding_mask": padding_mask_input,
|
160
|
+
},
|
161
|
+
outputs=sequence_output,
|
162
|
+
dtype=dtype,
|
163
|
+
**kwargs,
|
164
|
+
)
|
165
|
+
|
166
|
+
# === Config ===
|
167
|
+
self.vocabulary_size = vocabulary_size
|
168
|
+
self.num_layers = num_layers
|
169
|
+
self.num_query_heads = num_query_heads
|
170
|
+
self.hidden_dim = hidden_dim
|
171
|
+
self.intermediate_dim = intermediate_dim
|
172
|
+
self.rope_max_wavelength = rope_max_wavelength
|
173
|
+
self.num_key_value_heads = num_key_value_heads
|
174
|
+
self.rope_scaling_factor = rope_scaling_factor
|
175
|
+
self.layer_norm_epsilon = layer_norm_epsilon
|
176
|
+
self.dropout = dropout
|
177
|
+
self.tie_word_embeddings = tie_word_embeddings
|
178
|
+
self.use_sliding_window_attention = (use_sliding_window_attention,)
|
179
|
+
self.sliding_window_size = sliding_window_size
|
180
|
+
|
181
|
+
def get_config(self):
|
182
|
+
config = super().get_config()
|
183
|
+
config.update(
|
184
|
+
{
|
185
|
+
"vocabulary_size": self.vocabulary_size,
|
186
|
+
"num_layers": self.num_layers,
|
187
|
+
"num_query_heads": self.num_query_heads,
|
188
|
+
"hidden_dim": self.hidden_dim,
|
189
|
+
"intermediate_dim": self.intermediate_dim,
|
190
|
+
"rope_max_wavelength": self.rope_max_wavelength,
|
191
|
+
"rope_scaling_factor": self.rope_scaling_factor,
|
192
|
+
"num_key_value_heads": self.num_key_value_heads,
|
193
|
+
"layer_norm_epsilon": self.layer_norm_epsilon,
|
194
|
+
"dropout": self.dropout,
|
195
|
+
"tie_word_embeddings": self.tie_word_embeddings,
|
196
|
+
"use_sliding_window_attention": (
|
197
|
+
self.use_sliding_window_attention
|
198
|
+
),
|
199
|
+
"sliding_window_size": self.sliding_window_size,
|
200
|
+
}
|
201
|
+
)
|
202
|
+
return config
|
203
|
+
|
204
|
+
@staticmethod
|
205
|
+
def get_layout_map(
|
206
|
+
device_mesh,
|
207
|
+
model_parallel_dim_name="model",
|
208
|
+
data_parallel_dim_name="batch",
|
209
|
+
):
|
210
|
+
"""Get a `keras.distribution.LayoutMap` for model parallel distribution.
|
211
|
+
|
212
|
+
The returned `LayoutMap` contains the sharding spec for the Qwen
|
213
|
+
backbone weights, so that you can use it to distribute weights across
|
214
|
+
the accelerators.
|
215
|
+
|
216
|
+
Example:
|
217
|
+
```
|
218
|
+
# Feel free to change the mesh shape to balance data and model
|
219
|
+
# parallelism
|
220
|
+
mesh = keras.distribution.DeviceMesh(
|
221
|
+
shape=(1, 8),
|
222
|
+
axis_names=('batch', 'model'),
|
223
|
+
devices=keras.distribution.list_devices(),
|
224
|
+
)
|
225
|
+
layout_map = QwenBackbone.get_layout_map(
|
226
|
+
mesh,
|
227
|
+
model_parallel_dim_name="model",
|
228
|
+
)
|
229
|
+
|
230
|
+
distribution = keras.distribution.ModelParallel(
|
231
|
+
layout_map=layout_map,
|
232
|
+
batch_dim_name='batch',
|
233
|
+
)
|
234
|
+
|
235
|
+
with distribution.scope():
|
236
|
+
qwen_model = keras_hub.models.QwenBackbone.from_preset()
|
237
|
+
```
|
238
|
+
|
239
|
+
To see how the layout map was applied, load the model then run
|
240
|
+
(for one decoder block):
|
241
|
+
```
|
242
|
+
embedding_layer = qwen_model.backbone.get_layer("token_embedding")
|
243
|
+
decoder_block_1 = qwen_model.backbone.get_layer('transformer_layer_0')
|
244
|
+
for variable in embedding_layer.weights + decoder_block_1.weights:
|
245
|
+
print(
|
246
|
+
f'{variable.path:<58} {str(variable.shape):<16} '
|
247
|
+
f'{str(variable.value.sharding.spec)}'
|
248
|
+
)
|
249
|
+
```
|
250
|
+
|
251
|
+
Args:
|
252
|
+
device_mesh: The `keras.distribution.DeviceMesh` instance for
|
253
|
+
distribution.
|
254
|
+
model_parallel_dim_name: The axis name of the device mesh, where
|
255
|
+
the weights should be partition on.
|
256
|
+
data_parallel_dim_name: The axis name of the device mesh, where
|
257
|
+
the data should be partition on.
|
258
|
+
Return:
|
259
|
+
`keras.distribution.LayoutMap` that contains the sharding spec
|
260
|
+
for all the model weights.
|
261
|
+
"""
|
262
|
+
# The weight path and shape of the Llama backbone is like below
|
263
|
+
# token_embedding/embeddings (128256, 2048)
|
264
|
+
# repeat block for decoder
|
265
|
+
# transformer_layer_0/self_attention/query/kernel (2048, 32, 64)
|
266
|
+
# transformer_layer_0/self_attention/key/kernel (2048, 8, 64)
|
267
|
+
# transformer_layer_0/self_attention/value/kernel (2048, 8, 64)
|
268
|
+
# transformer_layer_0/self_attention/attention_output/kernel
|
269
|
+
# (32, 64, 2048)
|
270
|
+
# transformer_layer_0/self_attention_layernorm/scale (2048,)
|
271
|
+
# transformer_layer_0/feedforward_intermediate_dense/kernel
|
272
|
+
# (2048, 8192)
|
273
|
+
# transformer_layer_0/feedforward_gate_dense/kernel (2048, 8192)
|
274
|
+
# transformer_layer_0/feedforward_output_dense/kerne (8192, 2048)
|
275
|
+
# transformer_layer_0/feedforward_layernorm/scale (2048,)
|
276
|
+
|
277
|
+
if not isinstance(device_mesh, keras.distribution.DeviceMesh):
|
278
|
+
raise ValueError(
|
279
|
+
"Invalid device_mesh type. Expected "
|
280
|
+
f"`keras.distribution.Device`, got {type(device_mesh)}"
|
281
|
+
)
|
282
|
+
if model_parallel_dim_name not in device_mesh.axis_names:
|
283
|
+
raise ValueError(
|
284
|
+
f"{model_parallel_dim_name} is not found in the "
|
285
|
+
f"device_mesh.axis_names. {device_mesh.axis_name=}"
|
286
|
+
)
|
287
|
+
if data_parallel_dim_name not in device_mesh.axis_names:
|
288
|
+
raise ValueError(
|
289
|
+
f"{data_parallel_dim_name} is not found in the "
|
290
|
+
f"device_mesh.axis_names. {device_mesh.axis_name=}"
|
291
|
+
)
|
292
|
+
# Note that it is possible to further config the mesh to be 3D, eg
|
293
|
+
# (data, seq, model). We leave it as 2D for now for simplicity.
|
294
|
+
data_dim = data_parallel_dim_name
|
295
|
+
model_dim = model_parallel_dim_name
|
296
|
+
# The sharding config is based on the Gemma team training config.
|
297
|
+
# See https://arxiv.org/abs/2403.08295
|
298
|
+
layout_map = keras.distribution.LayoutMap(device_mesh)
|
299
|
+
layout_map["token_embedding/embeddings"] = (model_dim, data_dim)
|
300
|
+
layout_map[
|
301
|
+
"transformer_layer.*self_attention.*(query|key|value).kernel"
|
302
|
+
] = (
|
303
|
+
model_dim,
|
304
|
+
data_dim,
|
305
|
+
None,
|
306
|
+
)
|
307
|
+
layout_map["transformer_layer.*attention_output.kernel"] = (
|
308
|
+
model_dim,
|
309
|
+
None,
|
310
|
+
data_dim,
|
311
|
+
)
|
312
|
+
layout_map[
|
313
|
+
"transformer_layer.*feedforward_intermediate_dense.kernel"
|
314
|
+
] = (
|
315
|
+
data_dim,
|
316
|
+
model_dim,
|
317
|
+
)
|
318
|
+
layout_map["transformer_layer.*feedforward_gate_dense.kernel"] = (
|
319
|
+
data_dim,
|
320
|
+
model_dim,
|
321
|
+
)
|
322
|
+
layout_map["transformer_layer.*feedforward_output_dense.kernel"] = (
|
323
|
+
model_dim,
|
324
|
+
data_dim,
|
325
|
+
)
|
326
|
+
|
327
|
+
return layout_map
|
@@ -0,0 +1,300 @@
|
|
1
|
+
import keras
|
2
|
+
from keras import ops
|
3
|
+
|
4
|
+
from keras_hub.src.api_export import keras_hub_export
|
5
|
+
from keras_hub.src.models.causal_lm import CausalLM
|
6
|
+
from keras_hub.src.models.qwen.qwen_backbone import QwenBackbone
|
7
|
+
from keras_hub.src.models.qwen.qwen_causal_lm_preprocessor import (
|
8
|
+
QwenCausalLMPreprocessor,
|
9
|
+
)
|
10
|
+
from keras_hub.src.utils.tensor_utils import any_equal
|
11
|
+
|
12
|
+
|
13
|
+
@keras_hub_export(
|
14
|
+
[
|
15
|
+
"keras_hub.models.QwenCausalLM",
|
16
|
+
"keras_hub.models.Qwen2CausalLM",
|
17
|
+
]
|
18
|
+
)
|
19
|
+
class QwenCausalLM(CausalLM):
|
20
|
+
backbone_cls = QwenBackbone
|
21
|
+
preprocessor_cls = QwenCausalLMPreprocessor
|
22
|
+
|
23
|
+
def __init__(self, backbone, preprocessor=None, **kwargs):
|
24
|
+
# === Layers ===
|
25
|
+
self.backbone = backbone
|
26
|
+
self.preprocessor = preprocessor
|
27
|
+
|
28
|
+
# === Functional Model ===
|
29
|
+
# This must be "backbone.input" i.e. the full input structure,
|
30
|
+
# rather than "backbone.inputs" which is the flattened list of inputs.
|
31
|
+
inputs = backbone.input
|
32
|
+
hidden_states = backbone(inputs)
|
33
|
+
outputs = backbone.token_embedding(hidden_states, reverse=True)
|
34
|
+
super().__init__(
|
35
|
+
inputs=inputs,
|
36
|
+
outputs=outputs,
|
37
|
+
**kwargs,
|
38
|
+
)
|
39
|
+
|
40
|
+
def call_with_cache(
|
41
|
+
self,
|
42
|
+
token_ids,
|
43
|
+
cache,
|
44
|
+
cache_update_index,
|
45
|
+
):
|
46
|
+
"""Forward pass of `QwenCausalLM` with cache.
|
47
|
+
|
48
|
+
`call_with_cache` adds an additional forward pass for the model for
|
49
|
+
autoregressive inference. Unlike calling the model directly, this method
|
50
|
+
allows caching previous key/value Tensors in multi-head attention layer,
|
51
|
+
and avoids recomputing the outputs of seen tokens.
|
52
|
+
|
53
|
+
Args:
|
54
|
+
token_ids: a dense int Tensor with shape `(batch_size, max_length)`.
|
55
|
+
cache: a dense float Tensor, the cache of key and value.
|
56
|
+
cache_update_index: int, or int Tensor. The index of current inputs
|
57
|
+
in the whole sequence.
|
58
|
+
|
59
|
+
Returns:
|
60
|
+
A (logits, hidden_states, cache) tuple. Where `logits` is the
|
61
|
+
language model logits for the input token_ids, `hidden_states` is
|
62
|
+
the final hidden representation of the input tokens, and `cache` is
|
63
|
+
the decoding cache.
|
64
|
+
"""
|
65
|
+
x = self.backbone.token_embedding(token_ids)
|
66
|
+
# Each decoder layer has a cache; we update them separately.
|
67
|
+
updated_cache = []
|
68
|
+
for i in range(self.backbone.num_layers):
|
69
|
+
current_cache = cache[:, i, ...]
|
70
|
+
x, next_cache = self.backbone.transformer_layers[i](
|
71
|
+
x,
|
72
|
+
self_attention_cache=current_cache,
|
73
|
+
self_attention_cache_update_index=cache_update_index,
|
74
|
+
)
|
75
|
+
updated_cache.append(next_cache)
|
76
|
+
cache = ops.stack(updated_cache, axis=1)
|
77
|
+
hidden_states = x = self.backbone.layer_norm(x)
|
78
|
+
logits = self.backbone.token_embedding(x, reverse=True)
|
79
|
+
return logits, hidden_states, cache
|
80
|
+
|
81
|
+
def _build_cache(self, token_ids):
|
82
|
+
"""Build an empty cache for use with `call_with_cache()`."""
|
83
|
+
batch_size = ops.shape(token_ids)[0]
|
84
|
+
max_length = ops.shape(token_ids)[1]
|
85
|
+
num_layers = self.backbone.num_layers
|
86
|
+
num_key_value_heads = self.backbone.num_key_value_heads
|
87
|
+
head_dim = self.backbone.hidden_dim // self.backbone.num_query_heads
|
88
|
+
shape = [
|
89
|
+
batch_size,
|
90
|
+
num_layers,
|
91
|
+
2,
|
92
|
+
max_length,
|
93
|
+
num_key_value_heads,
|
94
|
+
head_dim,
|
95
|
+
]
|
96
|
+
cache = ops.zeros(shape, dtype=self.compute_dtype)
|
97
|
+
# Seed the cache.
|
98
|
+
_, hidden_states, cache = self.call_with_cache(token_ids, cache, 0)
|
99
|
+
return hidden_states, cache
|
100
|
+
|
101
|
+
def generate_step(
|
102
|
+
self,
|
103
|
+
inputs,
|
104
|
+
stop_token_ids=None,
|
105
|
+
):
|
106
|
+
"""A compilable generation function for a single batch of inputs.
|
107
|
+
|
108
|
+
This function represents the inner, XLA-compilable, generation function
|
109
|
+
for a single batch of inputs. Inputs should have the same structure as
|
110
|
+
model inputs, a dictionary with keys `"token_ids"` and `"padding_mask"`.
|
111
|
+
|
112
|
+
Args:
|
113
|
+
inputs: A dictionary with two keys `"token_ids"` and
|
114
|
+
`"padding_mask"` and batched tensor values.
|
115
|
+
stop_token_ids: Tuple of id's of the end token to stop on. If all
|
116
|
+
sequences have produced a new stop token, generation
|
117
|
+
will stop.
|
118
|
+
"""
|
119
|
+
token_ids, padding_mask = inputs["token_ids"], inputs["padding_mask"]
|
120
|
+
# Create and seed cache with a single forward pass.
|
121
|
+
hidden_states, cache = self._build_cache(token_ids)
|
122
|
+
# Compute the lengths of all user inputted tokens ids.
|
123
|
+
row_lengths = ops.sum(ops.cast(padding_mask, "int32"), axis=-1)
|
124
|
+
# Start at the first index that has no user inputted id.
|
125
|
+
index = ops.min(row_lengths)
|
126
|
+
|
127
|
+
def next(prompt, cache, index):
|
128
|
+
# The cache index is the index of our previous token.
|
129
|
+
cache_update_index = index - 1
|
130
|
+
batch_size = ops.shape(prompt)[0]
|
131
|
+
prompt = ops.slice(prompt, [0, cache_update_index], [batch_size, 1])
|
132
|
+
logits, hidden_states, cache = self.call_with_cache(
|
133
|
+
prompt,
|
134
|
+
cache,
|
135
|
+
cache_update_index,
|
136
|
+
)
|
137
|
+
return (
|
138
|
+
ops.squeeze(logits, axis=1),
|
139
|
+
ops.squeeze(hidden_states, axis=1),
|
140
|
+
cache,
|
141
|
+
)
|
142
|
+
|
143
|
+
token_ids = self.sampler(
|
144
|
+
next=next,
|
145
|
+
prompt=token_ids,
|
146
|
+
cache=cache,
|
147
|
+
index=index,
|
148
|
+
mask=padding_mask,
|
149
|
+
stop_token_ids=stop_token_ids,
|
150
|
+
hidden_states=hidden_states,
|
151
|
+
model=self,
|
152
|
+
)
|
153
|
+
|
154
|
+
# Compute an output padding mask with the token ids we updated.
|
155
|
+
if stop_token_ids is not None:
|
156
|
+
# Build a mask of stop token locations not in the original
|
157
|
+
# prompt (not in locations where `padding_mask` is True).
|
158
|
+
end_locations = any_equal(
|
159
|
+
token_ids, stop_token_ids, ops.logical_not(padding_mask)
|
160
|
+
)
|
161
|
+
end_locations = ops.cast(end_locations, "int32")
|
162
|
+
# Use cumsum to get ones in all locations after end_locations.
|
163
|
+
cumsum = ops.cast(ops.cumsum(end_locations, axis=-1), "int32")
|
164
|
+
overflow = cumsum - end_locations
|
165
|
+
# Our padding mask is the inverse of these overflow locations.
|
166
|
+
padding_mask = ops.logical_not(ops.cast(overflow, "bool"))
|
167
|
+
else:
|
168
|
+
# Without early stopping, all locations will have been updated.
|
169
|
+
padding_mask = ops.ones_like(token_ids, dtype="bool")
|
170
|
+
return {
|
171
|
+
"token_ids": token_ids,
|
172
|
+
"padding_mask": padding_mask,
|
173
|
+
}
|
174
|
+
|
175
|
+
def score(
|
176
|
+
self,
|
177
|
+
token_ids,
|
178
|
+
padding_mask=None,
|
179
|
+
scoring_mode="logits",
|
180
|
+
layer_intercept_fn=None,
|
181
|
+
target_ids=None,
|
182
|
+
):
|
183
|
+
"""Score a generation represented by the provided token ids.
|
184
|
+
|
185
|
+
Args:
|
186
|
+
token_ids: A <int>[batch_size, num_tokens] tensor containing tokens
|
187
|
+
to score. Typically, this tensor captures the output from a call
|
188
|
+
to `QwenCausalLM.generate()`, i.e., tokens for both the input
|
189
|
+
text and the model-generated text.
|
190
|
+
padding_mask: A <bool>[batch_size, num_tokens] tensor indicating the
|
191
|
+
tokens that should be preserved during generation. This is an
|
192
|
+
artifact required by the `QwenBackbone` and isn't influential
|
193
|
+
on the computation of this function. If omitted, this function
|
194
|
+
uses `keras.ops.ones()` to create a tensor of the appropriate
|
195
|
+
shape.
|
196
|
+
scoring_mode: The type of scores to return, either "logits" or
|
197
|
+
"loss", both will be per input token.
|
198
|
+
layer_intercept_fn: An optional function for augmenting activations
|
199
|
+
with additional computation, for example, as part of
|
200
|
+
interpretability research. This function will be passed the
|
201
|
+
activations as its first parameter and a numeric index
|
202
|
+
associated with that backbone layer. _This index _is not_ an
|
203
|
+
index into `self.backbone.layers`_. The index -1 accompanies the
|
204
|
+
embeddings returned by calling `self.backbone.token_embedding()`
|
205
|
+
on `token_ids` in the forward direction. All subsequent indexes
|
206
|
+
will be 0-based indices for the activations returned by each of
|
207
|
+
the Transformers layers in the backbone. This function must
|
208
|
+
return a <float>[batch_size, num_tokens, hidden_dims] tensor
|
209
|
+
that can be passed as an input to the next layer in the model.
|
210
|
+
target_ids: An <bool>[batch_size, num_tokens] tensor containing the
|
211
|
+
predicted tokens against which the loss should be computed. If a
|
212
|
+
span of tokens is provided (sequential truthy values along
|
213
|
+
axis=1 in the tensor), the loss will be computed as the
|
214
|
+
aggregate across those tokens.
|
215
|
+
|
216
|
+
Raises:
|
217
|
+
ValueError: If an unsupported scoring_mode is provided, or if the
|
218
|
+
target_ids are not provided when using ScoringMode.LOSS.
|
219
|
+
|
220
|
+
Returns:
|
221
|
+
The per-token scores as a tensor of size
|
222
|
+
<float>[batch_size, num_tokens, vocab_size] in "logits" mode, or
|
223
|
+
<float>[batch_size, num_tokens] in "loss" mode.
|
224
|
+
|
225
|
+
Example:
|
226
|
+
|
227
|
+
Compute gradients between embeddings and loss scores with TensorFlow:
|
228
|
+
```python
|
229
|
+
qwen_lm = keras_hub.models.QwenCausalLM.from_preset("qwen2.5_0.5b_en")
|
230
|
+
generations = qwen_lm.generate(
|
231
|
+
["This is a", "Where are you"],
|
232
|
+
max_length=30
|
233
|
+
)
|
234
|
+
preprocessed = qwen_lm.preprocessor.generate_preprocess(generations)
|
235
|
+
generation_ids = preprocessed["token_ids"]
|
236
|
+
padding_mask = preprocessed["padding_mask"]
|
237
|
+
target_ids = keras.ops.roll(generation_ids, shift=-1, axis=1)
|
238
|
+
|
239
|
+
embeddings = None
|
240
|
+
with tf.GradientTape(watch_accessed_variables=True) as tape:
|
241
|
+
def layer_intercept_fn(x, i):
|
242
|
+
if i == -1:
|
243
|
+
nonlocal embeddings, tape
|
244
|
+
embeddings = x
|
245
|
+
tape.watch(embeddings)
|
246
|
+
return x
|
247
|
+
|
248
|
+
losses = qwen_lm.score(
|
249
|
+
token_ids=generation_ids,
|
250
|
+
padding_mask=padding_mask,
|
251
|
+
scoring_mode="loss",
|
252
|
+
layer_intercept_fn=layer_intercept_fn,
|
253
|
+
target_ids=target_ids,
|
254
|
+
)
|
255
|
+
|
256
|
+
grads = tape.gradient(losses, embeddings)
|
257
|
+
```
|
258
|
+
"""
|
259
|
+
if scoring_mode not in ("logits", "loss"):
|
260
|
+
raise ValueError(
|
261
|
+
"Unsupported scoring_mode. Must be one of 'logits' or 'loss'."
|
262
|
+
)
|
263
|
+
|
264
|
+
if scoring_mode == "loss" and target_ids is None:
|
265
|
+
raise ValueError(
|
266
|
+
"Cannot compute loss without targets. Please provide target "
|
267
|
+
"token ids via the target_ids parameter."
|
268
|
+
)
|
269
|
+
|
270
|
+
batch_shape = ops.shape(token_ids)[:2]
|
271
|
+
assert len(batch_shape) == 2
|
272
|
+
|
273
|
+
if padding_mask is None:
|
274
|
+
padding_mask = ops.ones(shape=batch_shape)
|
275
|
+
|
276
|
+
if layer_intercept_fn is None:
|
277
|
+
|
278
|
+
def default_layer_intercept_fn(x, unused_i):
|
279
|
+
return x
|
280
|
+
|
281
|
+
layer_intercept_fn = default_layer_intercept_fn
|
282
|
+
|
283
|
+
token_embeddings = self.backbone.token_embedding(token_ids)
|
284
|
+
x = layer_intercept_fn(token_embeddings, -1)
|
285
|
+
|
286
|
+
for i, transformer_layer in enumerate(self.backbone.transformer_layers):
|
287
|
+
x = transformer_layer(x, decoder_padding_mask=padding_mask)
|
288
|
+
x = layer_intercept_fn(x, i)
|
289
|
+
|
290
|
+
x = self.backbone.layer_norm(x)
|
291
|
+
logits = self.backbone.token_embedding(x, reverse=True)
|
292
|
+
|
293
|
+
if scoring_mode == "logits":
|
294
|
+
return logits
|
295
|
+
|
296
|
+
per_token_loss_fn = keras.losses.SparseCategoricalCrossentropy(
|
297
|
+
from_logits=True, reduction="none"
|
298
|
+
)
|
299
|
+
per_token_loss = per_token_loss_fn(target_ids, logits)
|
300
|
+
return per_token_loss
|
@@ -0,0 +1,18 @@
|
|
1
|
+
from keras_hub.src.api_export import keras_hub_export
|
2
|
+
from keras_hub.src.models.causal_lm_preprocessor import CausalLMPreprocessor
|
3
|
+
from keras_hub.src.models.qwen.qwen_backbone import QwenBackbone
|
4
|
+
from keras_hub.src.models.qwen.qwen_tokenizer import QwenTokenizer
|
5
|
+
|
6
|
+
|
7
|
+
@keras_hub_export(
|
8
|
+
[
|
9
|
+
"keras_hub.models.QwenCausalLMPreprocessor",
|
10
|
+
"keras_hub.models.Qwen2CausalLMPreprocessor",
|
11
|
+
]
|
12
|
+
)
|
13
|
+
class QwenCausalLMPreprocessor(CausalLMPreprocessor):
|
14
|
+
backbone_cls = QwenBackbone
|
15
|
+
tokenizer_cls = QwenTokenizer
|
16
|
+
|
17
|
+
def __init__(self, *args, **kwargs):
|
18
|
+
super().__init__(*args, **kwargs)
|