keras-hub-nightly 0.21.0.dev202505050407__py3-none-any.whl → 0.21.0.dev202505070407__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 (40) hide show
  1. keras_hub/models/__init__.py +21 -0
  2. keras_hub/src/models/backbone.py +5 -2
  3. keras_hub/src/models/cspnet/cspnet_backbone.py +51 -26
  4. keras_hub/src/models/cspnet/cspnet_presets.py +38 -3
  5. keras_hub/src/models/mixtral/mixtral_attention.py +263 -0
  6. keras_hub/src/models/mixtral/mixtral_backbone.py +207 -0
  7. keras_hub/src/models/mixtral/mixtral_causal_lm.py +281 -0
  8. keras_hub/src/models/mixtral/mixtral_causal_lm_preprocessor.py +76 -0
  9. keras_hub/src/models/mixtral/mixtral_decoder.py +494 -0
  10. keras_hub/src/models/mixtral/mixtral_layer_norm.py +34 -0
  11. keras_hub/src/models/mixtral/mixtral_tokenizer.py +21 -0
  12. keras_hub/src/models/qwen/qwen_attention.py +3 -1
  13. keras_hub/src/models/qwen/qwen_presets.py +61 -0
  14. keras_hub/src/models/qwen_moe/__init__.py +0 -0
  15. keras_hub/src/models/qwen_moe/qwen_moe_attention.py +377 -0
  16. keras_hub/src/models/qwen_moe/qwen_moe_backbone.py +373 -0
  17. keras_hub/src/models/qwen_moe/qwen_moe_causal_lm.py +350 -0
  18. keras_hub/src/models/qwen_moe/qwen_moe_causal_lm_preprocessor.py +17 -0
  19. keras_hub/src/models/qwen_moe/qwen_moe_decoder.py +625 -0
  20. keras_hub/src/models/qwen_moe/qwen_moe_layernorm.py +32 -0
  21. keras_hub/src/models/qwen_moe/qwen_moe_tokenizer.py +46 -0
  22. keras_hub/src/models/retinanet/retinanet_image_converter.py +0 -13
  23. keras_hub/src/models/retinanet/retinanet_presets.py +2 -2
  24. keras_hub/src/models/segformer/segformer_image_segmenter_preprocessor.py +0 -18
  25. keras_hub/src/models/segformer/segformer_presets.py +12 -12
  26. keras_hub/src/models/task.py +5 -2
  27. keras_hub/src/utils/keras_utils.py +11 -0
  28. keras_hub/src/utils/preset_utils.py +69 -9
  29. keras_hub/src/utils/tensor_utils.py +27 -1
  30. keras_hub/src/utils/timm/convert_cspnet.py +94 -23
  31. keras_hub/src/utils/timm/preset_loader.py +6 -6
  32. keras_hub/src/utils/transformers/convert_mixtral.py +139 -0
  33. keras_hub/src/utils/transformers/convert_qwen_moe.py +253 -0
  34. keras_hub/src/utils/transformers/preset_loader.py +6 -0
  35. keras_hub/src/version.py +1 -1
  36. keras_hub/tokenizers/__init__.py +6 -0
  37. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/METADATA +1 -1
  38. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/RECORD +40 -22
  39. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/WHEEL +0 -0
  40. {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,207 @@
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.mixtral.mixtral_decoder import (
10
+ MixtralTransformerDecoder,
11
+ )
12
+ from keras_hub.src.models.mixtral.mixtral_layer_norm import (
13
+ MixtralLayerNormalization,
14
+ )
15
+
16
+
17
+ def _mixtral_kernel_initializer(stddev=0.02):
18
+ return keras.initializers.RandomNormal(stddev=stddev)
19
+
20
+
21
+ @keras_hub_export("keras_hub.models.MixtralBackbone")
22
+ class MixtralBackbone(Backbone):
23
+ """The Mixtral Transformer core architecture with hyperparameters.
24
+
25
+ This network implements a mixture of Experts based decoder network,
26
+ Mixtral, as described in
27
+ ["Mixtral of Experts"](https://arxiv.org/pdf/2401.04088).
28
+ It includes the embedding lookups and transformer layers.
29
+
30
+ The default constructor gives a fully customizable, randomly initialized
31
+ Mixtral model with any number of layers, heads, and embedding
32
+ dimensions. To load preset architectures and weights, use the `from_preset`
33
+ constructor.
34
+
35
+ Args:
36
+ vocabulary_size (int): The size of the token vocabulary.
37
+ num_layers (int): The number of transformer layers.
38
+ num_query_heads (int): The number of query attention heads for
39
+ each transformer.
40
+ hidden_dim (int): The size of the transformer encoding and pooling
41
+ layers.
42
+ intermediate_dim (int): The output dimension of the first Dense layer
43
+ in a three-layer feedforward network for each transformer.
44
+ num_key_value_heads (int): The number of key and value attention heads
45
+ for each transformer.
46
+ rope_max_wavelength (int, optional): The maximum angular wavelength of
47
+ the sine/cosine curves, for rotary embeddings. Defaults to `10000`.
48
+ rope_scaling_factor (float, optional): The scaling factor for
49
+ calculation of roatary embedding. Defaults to `1.0`.
50
+ layer_norm_epsilon (float, optional): Epsilon for the layer
51
+ normalization layers in the transformer decoder. Defaults to `1e-6`.
52
+ sliding_window (int, optional): The sliding window for the mixtral
53
+ attention layers. This controls the maximum cache size for the
54
+ attention layers in each transformer decoder. Only `sliding_window`
55
+ number of tokens are saved in the cache and used to generate the
56
+ next token. Defaults to `512`.
57
+ dtype: string or `keras.mixed_precision.DTypePolicy`. The dtype to use
58
+ for model computations and weights. Note that some computations,
59
+ such as softmax and layer normalization, will always be done at
60
+ float32 precision regardless of dtype.
61
+
62
+ Examples:
63
+
64
+ ```python
65
+ input_data = {
66
+ "token_ids": np.ones(shape=(1, 12), dtype="int32"),
67
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]),
68
+ }
69
+
70
+ # Pretrained Mixtral decoder.
71
+ model = keras_hub.models.MixtralBackbone.from_preset("mixtral7b_base_en")
72
+ model(input_data)
73
+
74
+ # Randomly initialized Mixtral decoder with custom config.
75
+ model = keras_hub.models.MixtralBackbone(
76
+ vocabulary_size=10,
77
+ hidden_dim=512,
78
+ num_layers=2,
79
+ num_query_heads=32,
80
+ num_key_value_heads=8,
81
+ intermediate_dim=1024,
82
+ sliding_window=512,
83
+ layer_norm_epsilon=1e-6,
84
+ dtype="float32"
85
+ )
86
+ model(input_data)
87
+ ```
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ vocabulary_size,
93
+ num_layers,
94
+ num_query_heads,
95
+ hidden_dim,
96
+ intermediate_dim,
97
+ num_key_value_heads,
98
+ num_experts,
99
+ top_k=2,
100
+ router_jitter_noise=0.0,
101
+ rope_max_wavelength=10000,
102
+ rope_scaling_factor=1.0,
103
+ layer_norm_epsilon=1e-6,
104
+ router_aux_loss_coef=0.02,
105
+ sliding_window=512,
106
+ dropout=0,
107
+ dtype=None,
108
+ output_router_logits=False,
109
+ **kwargs,
110
+ ):
111
+ # === Layers ===
112
+ self.token_embedding = ReversibleEmbedding(
113
+ input_dim=vocabulary_size,
114
+ output_dim=hidden_dim,
115
+ tie_weights=False,
116
+ embeddings_initializer=_mixtral_kernel_initializer(stddev=0.01),
117
+ dtype=dtype,
118
+ name="token_embedding",
119
+ )
120
+ self.transformer_layers = []
121
+ for i in range(num_layers):
122
+ layer = MixtralTransformerDecoder(
123
+ intermediate_dim=intermediate_dim,
124
+ num_query_heads=num_query_heads,
125
+ num_key_value_heads=num_key_value_heads,
126
+ num_experts=num_experts,
127
+ top_k=top_k,
128
+ router_jitter_noise=router_jitter_noise,
129
+ output_router_logits=output_router_logits,
130
+ rope_max_wavelength=rope_max_wavelength,
131
+ rope_scaling_factor=rope_scaling_factor,
132
+ layer_norm_epsilon=layer_norm_epsilon,
133
+ activation=ops.silu,
134
+ router_aux_loss_coef=router_aux_loss_coef,
135
+ kernel_initializer=_mixtral_kernel_initializer(stddev=0.02),
136
+ sliding_window=sliding_window,
137
+ dropout=dropout,
138
+ dtype=dtype,
139
+ name=f"transformer_layer_{i}",
140
+ )
141
+ self.transformer_layers.append(layer)
142
+ self.layer_norm = MixtralLayerNormalization(
143
+ epsilon=layer_norm_epsilon,
144
+ dtype=dtype,
145
+ name="sequence_output_layernorm",
146
+ )
147
+
148
+ # === Functional Model ===
149
+ token_id_input = keras.Input(
150
+ shape=(None,), dtype="int32", name="token_ids"
151
+ )
152
+ padding_mask_input = keras.Input(
153
+ shape=(None,), dtype="int32", name="padding_mask"
154
+ )
155
+ x = self.token_embedding(token_id_input)
156
+ for transformer_layer in self.transformer_layers:
157
+ x = transformer_layer(x, decoder_padding_mask=padding_mask_input)
158
+ sequence_output = self.layer_norm(x)
159
+ super().__init__(
160
+ inputs={
161
+ "token_ids": token_id_input,
162
+ "padding_mask": padding_mask_input,
163
+ },
164
+ outputs=sequence_output,
165
+ dtype=dtype,
166
+ **kwargs,
167
+ )
168
+
169
+ # === Config ===
170
+ self.vocabulary_size = vocabulary_size
171
+ self.num_layers = num_layers
172
+ self.num_query_heads = num_query_heads
173
+ self.hidden_dim = hidden_dim
174
+ self.intermediate_dim = intermediate_dim
175
+ self.num_key_value_heads = num_key_value_heads
176
+ self.num_experts = num_experts
177
+ self.top_k = top_k
178
+ self.router_jitter_noise = router_jitter_noise
179
+ self.rope_max_wavelength = rope_max_wavelength
180
+ self.router_aux_loss_coef = router_aux_loss_coef
181
+ self.rope_scaling_factor = rope_scaling_factor
182
+ self.sliding_window = sliding_window
183
+ self.layer_norm_epsilon = layer_norm_epsilon
184
+ self.dropout = dropout
185
+
186
+ def get_config(self):
187
+ config = super().get_config()
188
+ config.update(
189
+ {
190
+ "vocabulary_size": self.vocabulary_size,
191
+ "num_layers": self.num_layers,
192
+ "num_query_heads": self.num_query_heads,
193
+ "hidden_dim": self.hidden_dim,
194
+ "intermediate_dim": self.intermediate_dim,
195
+ "num_experts": self.num_experts,
196
+ "top_k": self.top_k,
197
+ "router_jitter_noise": self.router_jitter_noise,
198
+ "rope_max_wavelength": self.rope_max_wavelength,
199
+ "rope_scaling_factor": self.rope_scaling_factor,
200
+ "num_key_value_heads": self.num_key_value_heads,
201
+ "router_aux_loss_coef": self.router_aux_loss_coef,
202
+ "sliding_window": self.sliding_window,
203
+ "layer_norm_epsilon": self.layer_norm_epsilon,
204
+ "dropout": self.dropout,
205
+ }
206
+ )
207
+ return config
@@ -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