keras-hub-nightly 0.21.0.dev202505050407__py3-none-any.whl → 0.21.0.dev202505060405__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 (34) hide show
  1. keras_hub/models/__init__.py +21 -0
  2. keras_hub/src/models/backbone.py +5 -2
  3. keras_hub/src/models/mixtral/mixtral_attention.py +263 -0
  4. keras_hub/src/models/mixtral/mixtral_backbone.py +207 -0
  5. keras_hub/src/models/mixtral/mixtral_causal_lm.py +281 -0
  6. keras_hub/src/models/mixtral/mixtral_causal_lm_preprocessor.py +76 -0
  7. keras_hub/src/models/mixtral/mixtral_decoder.py +494 -0
  8. keras_hub/src/models/mixtral/mixtral_layer_norm.py +34 -0
  9. keras_hub/src/models/mixtral/mixtral_tokenizer.py +21 -0
  10. keras_hub/src/models/qwen/qwen_attention.py +3 -1
  11. keras_hub/src/models/qwen/qwen_presets.py +61 -0
  12. keras_hub/src/models/qwen_moe/__init__.py +0 -0
  13. keras_hub/src/models/qwen_moe/qwen_moe_attention.py +377 -0
  14. keras_hub/src/models/qwen_moe/qwen_moe_backbone.py +373 -0
  15. keras_hub/src/models/qwen_moe/qwen_moe_causal_lm.py +350 -0
  16. keras_hub/src/models/qwen_moe/qwen_moe_causal_lm_preprocessor.py +17 -0
  17. keras_hub/src/models/qwen_moe/qwen_moe_decoder.py +625 -0
  18. keras_hub/src/models/qwen_moe/qwen_moe_layernorm.py +32 -0
  19. keras_hub/src/models/qwen_moe/qwen_moe_tokenizer.py +46 -0
  20. keras_hub/src/models/retinanet/retinanet_image_converter.py +0 -13
  21. keras_hub/src/models/retinanet/retinanet_presets.py +2 -2
  22. keras_hub/src/models/task.py +5 -2
  23. keras_hub/src/utils/keras_utils.py +11 -0
  24. keras_hub/src/utils/preset_utils.py +69 -9
  25. keras_hub/src/utils/tensor_utils.py +27 -1
  26. keras_hub/src/utils/transformers/convert_mixtral.py +139 -0
  27. keras_hub/src/utils/transformers/convert_qwen_moe.py +253 -0
  28. keras_hub/src/utils/transformers/preset_loader.py +6 -0
  29. keras_hub/src/version.py +1 -1
  30. keras_hub/tokenizers/__init__.py +6 -0
  31. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505060405.dist-info}/METADATA +1 -1
  32. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505060405.dist-info}/RECORD +34 -16
  33. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505060405.dist-info}/WHEEL +0 -0
  34. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505060405.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,281 @@
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.mixtral.mixtral_backbone import MixtralBackbone
7
+ from keras_hub.src.models.mixtral.mixtral_causal_lm_preprocessor import (
8
+ MixtralCausalLMPreprocessor,
9
+ )
10
+ from keras_hub.src.utils.tensor_utils import any_equal
11
+
12
+
13
+ @keras_hub_export("keras_hub.models.MixtralCausalLM")
14
+ class MixtralCausalLM(CausalLM):
15
+ """An end-to-end Mixtral model for causal language modeling.
16
+
17
+ A causal language model (LM) predicts the next token based on previous
18
+ tokens. This task setup can be used to train the model unsupervised on
19
+ plain text input, or to autoregressively generate plain text similar to
20
+ the data used for training. This task can be used for pre-training or
21
+ fine-tuning a GPT-NeoX model, simply by calling `fit()`.
22
+
23
+ This model has a `generate()` method, which generates text based on a
24
+ prompt. The generation strategy used is controlled by an additional
25
+ `sampler` argument on `compile()`. You can recompile the model with
26
+ different `keras_hub.samplers` objects to control the generation. By
27
+ default, `"top_k"` sampling will be used.
28
+
29
+ Args:
30
+ backbone: A `keras_hub.models.MixtralBackbone` instance.
31
+ preprocessor: A `keras_hub.models.MixtralCausalLMPreprocessor` or
32
+ `None`. If `None`, this model will not apply preprocessing, and
33
+ inputs should be preprocessed before calling the model.
34
+ """
35
+
36
+ backbone_cls = MixtralBackbone
37
+ preprocessor_cls = MixtralCausalLMPreprocessor
38
+
39
+ def __init__(self, backbone, preprocessor=None, **kwargs):
40
+ # === Layers ===
41
+ self.backbone = backbone
42
+ self.preprocessor = preprocessor
43
+
44
+ # === Functional Model ===
45
+ # This must be "backbone.input" i.e. the full input structure,
46
+ # rather than "backbone.inputs" which is the flattened list of inputs.
47
+ inputs = backbone.input
48
+ hidden_states = backbone(inputs)
49
+ outputs = backbone.token_embedding(hidden_states, reverse=True)
50
+ super().__init__(
51
+ inputs=inputs,
52
+ outputs=outputs,
53
+ **kwargs,
54
+ )
55
+
56
+ def call_with_cache(
57
+ self,
58
+ token_ids,
59
+ cache,
60
+ cache_update_index,
61
+ ):
62
+ """Forward pass of `MixtralCausalLM` with cache.
63
+
64
+ `call_with_cache` adds an additional forward pass for the model for
65
+ autoregressive inference. Unlike calling the model directly, this method
66
+ allows caching previous key/value Tensors in multi-head attention layer,
67
+ and avoids recomputing the outputs of seen tokens.
68
+
69
+ Args:
70
+ token_ids: a dense int Tensor with shape `(batch_size, max_length)`.
71
+ cache: a dense float Tensor, the cache of key and value.
72
+ cache_update_index: int, or int Tensor. The index of current inputs
73
+ in the whole sequence.
74
+
75
+ Returns:
76
+ A (logits, hidden_states, cache) tuple. Where `logits` is the
77
+ language model logits for the input token_ids, `hidden_states` is
78
+ the final hidden representation of the input tokens, and `cache` is
79
+ the decoding cache.
80
+ """
81
+ x = self.backbone.token_embedding(token_ids)
82
+ # Each decoder layer has a cache; we update them separately.
83
+ updated_cache = []
84
+ for i in range(self.backbone.num_layers):
85
+ current_cache = cache[:, i, ...]
86
+ x, next_cache = self.backbone.transformer_layers[i](
87
+ x,
88
+ self_attention_cache=current_cache,
89
+ self_attention_cache_update_index=cache_update_index,
90
+ )
91
+ updated_cache.append(next_cache)
92
+ cache = ops.stack(updated_cache, axis=1)
93
+ hidden_states = x = self.backbone.layer_norm(x)
94
+ logits = self.backbone.token_embedding(x, reverse=True)
95
+ return logits, hidden_states, cache
96
+
97
+ def _build_cache(self, token_ids):
98
+ """Build an empty cache for use with `call_with_cache()`."""
99
+ batch_size = ops.shape(token_ids)[0]
100
+ max_length = ops.shape(token_ids)[1]
101
+ num_layers = self.backbone.num_layers
102
+ num_key_value_heads = self.backbone.num_key_value_heads
103
+ head_dim = self.backbone.hidden_dim // self.backbone.num_query_heads
104
+ shape = [
105
+ batch_size,
106
+ num_layers,
107
+ 2,
108
+ max_length,
109
+ num_key_value_heads,
110
+ head_dim,
111
+ ]
112
+ cache = ops.zeros(shape, dtype=self.compute_dtype)
113
+ # Seed the cache.
114
+ _, hidden_states, cache = self.call_with_cache(token_ids, cache, 0)
115
+ return hidden_states, cache
116
+
117
+ def generate_step(
118
+ self,
119
+ inputs,
120
+ stop_token_ids=None,
121
+ ):
122
+ """A compilable generation function for a single batch of inputs.
123
+
124
+ This function represents the inner, XLA-compilable, generation function
125
+ for a single batch of inputs. Inputs should have the same structure as
126
+ model inputs, a dictionary with keys `"token_ids"` and `"padding_mask"`.
127
+
128
+ Args:
129
+ inputs: A dictionary with two keys `"token_ids"` and
130
+ `"padding_mask"` and batched tensor values.
131
+ stop_token_ids: List of id's of end token's to stop on. If all
132
+ sequences have produced a new stop token, generation
133
+ will stop.
134
+ """
135
+ token_ids, padding_mask = inputs["token_ids"], inputs["padding_mask"]
136
+ # Create and seed cache with a single forward pass.
137
+ hidden_states, cache = self._build_cache(token_ids)
138
+ # Compute the lengths of all user inputted tokens ids.
139
+ row_lengths = ops.sum(ops.cast(padding_mask, "int32"), axis=-1)
140
+ # Start at the first index that has no user inputted id.
141
+ index = ops.min(row_lengths)
142
+
143
+ def next(prompt, cache, index):
144
+ # The cache index is the index of our previous token.
145
+ cache_update_index = index - 1
146
+ batch_size = ops.shape(prompt)[0]
147
+ prompt = ops.slice(prompt, [0, cache_update_index], [batch_size, 1])
148
+ logits, hidden_states, cache = self.call_with_cache(
149
+ prompt,
150
+ cache,
151
+ cache_update_index,
152
+ )
153
+ return (
154
+ ops.squeeze(logits, axis=1),
155
+ ops.squeeze(hidden_states, axis=1),
156
+ cache,
157
+ )
158
+
159
+ token_ids = self.sampler(
160
+ next=next,
161
+ prompt=token_ids,
162
+ cache=cache,
163
+ index=index,
164
+ mask=padding_mask,
165
+ stop_token_ids=stop_token_ids,
166
+ hidden_states=hidden_states,
167
+ model=self,
168
+ )
169
+
170
+ # Compute an output padding mask with the token ids we updated.
171
+ if stop_token_ids is not None:
172
+ # Build a mask of stop_tokens locations not in the original
173
+ # prompt (not in locations where `padding_mask` is True).
174
+ end_locations = any_equal(
175
+ token_ids, stop_token_ids, ops.logical_not(padding_mask)
176
+ )
177
+
178
+ end_locations = ops.cast(end_locations, "int32")
179
+ # Use cumsum to get ones in all locations after end_locations.
180
+ cumsum = ops.cast(ops.cumsum(end_locations, axis=-1), "int32")
181
+ overflow = cumsum - end_locations
182
+ # Our padding mask is the inverse of these overflow locations.
183
+ padding_mask = ops.logical_not(ops.cast(overflow, "bool"))
184
+ else:
185
+ # Without early stopping, all locations will have been updated.
186
+ padding_mask = ops.ones_like(token_ids, dtype="bool")
187
+ return {
188
+ "token_ids": token_ids,
189
+ "padding_mask": padding_mask,
190
+ }
191
+
192
+ def score(
193
+ self,
194
+ token_ids,
195
+ padding_mask=None,
196
+ scoring_mode="logits",
197
+ layer_intercept_fn=None,
198
+ target_ids=None,
199
+ ):
200
+ """Score a generation represented by the provided token ids.
201
+
202
+ Args:
203
+ token_ids: A <int>[batch_size, num_tokens] tensor containing tokens
204
+ to score. Typically, this tensor captures the output from a call
205
+ to `MixtralCausalLM.generate()`, i.e., tokens for both the input
206
+ text and the model-generated text.
207
+ padding_mask: A <bool>[batch_size, num_tokens] tensor indicating the
208
+ tokens that should be preserved during generation. This is an
209
+ artifact required by the MixtralBackbone and isn't influential
210
+ on the computation of this function. If omitted, this function
211
+ uses `keras.ops.ones()` to create a tensor of the appropriate
212
+ shape.
213
+ scoring_mode: The type of scores to return, either "logits" or
214
+ "loss", both will be per input token.
215
+ layer_intercept_fn: An optional function for augmenting activations
216
+ with additional computation, for example, as part of
217
+ interpretability research. This function will be passed the
218
+ activations as its first parameter and a numeric index
219
+ associated with that backbone layer. _This index _is not_ an
220
+ index into `self.backbone.layers`. The index -1 accompanies the
221
+ embeddings returned by calling `self.backbone.token_embedding()`
222
+ on `token_ids` in the forward direction. All subsequent indexes
223
+ will be 0-based indices for the activations returned by each of
224
+ the Transformers layers in the backbone. This function must
225
+ return a <float>[batch_size, num_tokens, hidden_dims] tensor
226
+ that can be passed as an input to the next layer in the model.
227
+ target_ids: An <bool>[batch_size, num_tokens] tensor containing the
228
+ predicted tokens against which the loss should be computed. If a
229
+ span of tokens is provided (sequential truthy values along
230
+ axis=1 in the tensor), the loss will be computed as the
231
+ aggregate across those tokens.
232
+
233
+ Raises:
234
+ ValueError: If an unsupported scoring_mode is provided, or if the
235
+ target_ids are not provided when using ScoringMode.LOSS.
236
+
237
+ Returns:
238
+ The per-token scores as a tensor of size
239
+ <float>[batch_size, num_tokens, vocab_size] in "logits" mode, or
240
+ <float>[batch_size, num_tokens] in "loss" mode.
241
+ ```
242
+ """
243
+ if scoring_mode not in ("logits", "loss"):
244
+ raise ValueError(
245
+ "Unsupported scoring_mode. Must be one of 'logits' or 'loss'."
246
+ )
247
+
248
+ if scoring_mode == "loss" and target_ids is None:
249
+ raise ValueError(
250
+ "Cannot compute loss without targets. Please provide target "
251
+ "token ids via the target_ids parameter."
252
+ )
253
+
254
+ batch_shape = ops.shape(token_ids)[:2]
255
+ assert len(batch_shape) == 2
256
+
257
+ if layer_intercept_fn is None:
258
+
259
+ def default_layer_intercept_fn(x, unused_i):
260
+ return x
261
+
262
+ layer_intercept_fn = default_layer_intercept_fn
263
+
264
+ token_embeddings = self.backbone.token_embedding(token_ids)
265
+ x = layer_intercept_fn(token_embeddings, -1)
266
+
267
+ for i, transformer_layer in enumerate(self.backbone.transformer_layers):
268
+ x = transformer_layer(x, decoder_padding_mask=padding_mask)
269
+ x = layer_intercept_fn(x, i)
270
+
271
+ x = self.backbone.layer_norm(x)
272
+ logits = self.backbone.token_embedding(x, reverse=True)
273
+
274
+ if scoring_mode == "logits":
275
+ return logits
276
+
277
+ per_token_loss_fn = keras.losses.SparseCategoricalCrossentropy(
278
+ from_logits=True, reduction="none"
279
+ )
280
+ per_token_loss = per_token_loss_fn(target_ids, logits)
281
+ return per_token_loss
@@ -0,0 +1,76 @@
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.mixtral.mixtral_backbone import MixtralBackbone
4
+ from keras_hub.src.models.mixtral.mixtral_tokenizer import MixtralTokenizer
5
+
6
+
7
+ @keras_hub_export("keras_hub.models.MixtralCausalLMPreprocessor")
8
+ class MixtralCausalLMPreprocessor(CausalLMPreprocessor):
9
+ """Mixtral Causal LM preprocessor.
10
+
11
+ This preprocessing layer is meant for use with
12
+ `keras_hub.models.MixtralCausalLM`. By default, it will take in batches of
13
+ strings, and return outputs in a `(x, y, sample_weight)` format, where the
14
+ `y` label is the next token id in the `x` sequence.
15
+
16
+ For use with generation, the layer also exposes two methods
17
+ `generate_preprocess()` and `generate_postprocess()`. When this preprocessor
18
+ is attached to a `keras_hub.models.MixtralCausalLM` instance, these methods
19
+ will be called implicitly in `generate()`. They can also be called
20
+ standalone (e.g. to precompute preprocessing inputs for generation in a
21
+ separate process).
22
+
23
+ Args:
24
+ tokenizer: A `keras_hub.models.MixtralTokenizer` instance.
25
+ sequence_length: The length of the packed inputs.
26
+ add_start_token: If `True`, the preprocessor will prepend the tokenizer
27
+ start token to each input sequence. Default is `True`.
28
+ add_end_token: If `True`, the preprocessor will append the tokenizer
29
+ end token to each input sequence. Default is `False`.
30
+
31
+ Call arguments:
32
+ x: A string, `tf.Tensor` or list of python strings.
33
+ y: Label data. Should always be `None` as the layer generates labels.
34
+ sample_weight: Label weights. Should always be `None` as the layer
35
+ generates label weights.
36
+ sequence_length: Pass to override the configured `sequence_length` of
37
+ the layer.
38
+
39
+ Examples:
40
+ ```python
41
+ # Load the preprocessor from a preset.
42
+ preprocessor = keras_hub.models.MixtralCausalLMPreprocessor.from_preset(
43
+ "mixtral_base_en"
44
+ )
45
+
46
+ # Tokenize and pack a single sentence.
47
+ sentence = tf.constant("League of legends")
48
+ preprocessor(sentence)
49
+ # Same output.
50
+ preprocessor("League of legends")
51
+
52
+ # Tokenize a batch of sentences.
53
+ sentences = tf.constant(["Taco tuesday", "Fish taco please!"])
54
+ preprocessor(sentences)
55
+ # Same output.
56
+ preprocessor(["Taco tuesday", "Fish taco please!"])
57
+
58
+ # Map a dataset to preprocess a single sentence.
59
+ features = tf.constant(
60
+ [
61
+ "Avatar 2 is amazing!",
62
+ "Well, I am not sure.",
63
+ ]
64
+ )
65
+ labels = tf.constant([1, 0])
66
+ ds = tf.data.Dataset.from_tensor_slices((features, labels))
67
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
68
+
69
+ # Map a dataset to preprocess unlabled sentences.
70
+ ds = tf.data.Dataset.from_tensor_slices(features)
71
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
72
+ ```
73
+ """
74
+
75
+ backbone_cls = MixtralBackbone
76
+ tokenizer_cls = MixtralTokenizer