keras-hub-nightly 0.24.0.dev202511220420__py3-none-any.whl → 0.26.0.dev202601010440__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.

Potentially problematic release.


This version of keras-hub-nightly might be problematic. Click here for more details.

Files changed (66) hide show
  1. keras_hub/models/__init__.py +12 -0
  2. keras_hub/src/layers/modeling/reversible_embedding.py +2 -275
  3. keras_hub/src/layers/modeling/rotary_embedding.py +188 -14
  4. keras_hub/src/layers/modeling/token_and_position_embedding.py +1 -3
  5. keras_hub/src/models/albert/albert_backbone.py +1 -3
  6. keras_hub/src/models/bart/bart_backbone.py +1 -3
  7. keras_hub/src/models/bert/bert_backbone.py +1 -3
  8. keras_hub/src/models/bloom/bloom_backbone.py +1 -3
  9. keras_hub/src/models/causal_lm.py +23 -1
  10. keras_hub/src/models/deberta_v3/deberta_v3_backbone.py +1 -3
  11. keras_hub/src/models/dinov3/dinov3_presets.py +90 -1
  12. keras_hub/src/models/electra/electra_backbone.py +1 -3
  13. keras_hub/src/models/esm/esm_attention.py +11 -4
  14. keras_hub/src/models/f_net/f_net_backbone.py +1 -3
  15. keras_hub/src/models/falcon/falcon_backbone.py +1 -3
  16. keras_hub/src/models/gemma/gemma_backbone.py +1 -3
  17. keras_hub/src/models/gemma/gemma_causal_lm.py +16 -0
  18. keras_hub/src/models/gemma3/gemma3_backbone.py +1 -3
  19. keras_hub/src/models/gemma3/gemma3_causal_lm_preprocessor.py +8 -3
  20. keras_hub/src/models/gemma3/gemma3_presets.py +12 -0
  21. keras_hub/src/models/gemma3/gemma3_tokenizer.py +20 -8
  22. keras_hub/src/models/gpt2/gpt2_backbone.py +1 -3
  23. keras_hub/src/models/gpt2/gpt2_causal_lm.py +17 -0
  24. keras_hub/src/models/gpt_neo_x/gpt_neo_x_backbone.py +1 -3
  25. keras_hub/src/models/gpt_oss/__init__.py +5 -0
  26. keras_hub/src/models/gpt_oss/gpt_oss_attention.py +330 -0
  27. keras_hub/src/models/gpt_oss/gpt_oss_backbone.py +219 -0
  28. keras_hub/src/models/gpt_oss/gpt_oss_causal_lm.py +284 -0
  29. keras_hub/src/models/gpt_oss/gpt_oss_causal_lm_preprocessor.py +79 -0
  30. keras_hub/src/models/gpt_oss/gpt_oss_decoder.py +444 -0
  31. keras_hub/src/models/gpt_oss/gpt_oss_layer_norm.py +34 -0
  32. keras_hub/src/models/gpt_oss/gpt_oss_presets.py +51 -0
  33. keras_hub/src/models/gpt_oss/gpt_oss_tokenizer.py +39 -0
  34. keras_hub/src/models/llama/llama_backbone.py +1 -3
  35. keras_hub/src/models/llama3/llama3_presets.py +1 -1
  36. keras_hub/src/models/masked_lm.py +22 -0
  37. keras_hub/src/models/mistral/mistral_backbone.py +1 -3
  38. keras_hub/src/models/mixtral/mixtral_backbone.py +1 -3
  39. keras_hub/src/models/moonshine/moonshine_backbone.py +1 -3
  40. keras_hub/src/models/pali_gemma/pali_gemma_backbone.py +1 -3
  41. keras_hub/src/models/parseq/parseq_decoder.py +21 -9
  42. keras_hub/src/models/phi3/phi3_backbone.py +1 -3
  43. keras_hub/src/models/qwen/qwen_backbone.py +1 -3
  44. keras_hub/src/models/qwen3/qwen3_backbone.py +1 -3
  45. keras_hub/src/models/qwen3/qwen3_presets.py +36 -0
  46. keras_hub/src/models/qwen3_moe/qwen3_moe_backbone.py +1 -3
  47. keras_hub/src/models/qwen_moe/qwen_moe_backbone.py +1 -3
  48. keras_hub/src/models/roformer_v2/roformer_v2_backbone.py +1 -3
  49. keras_hub/src/models/siglip/siglip_layers.py +1 -3
  50. keras_hub/src/models/smollm3/__init__.py +5 -0
  51. keras_hub/src/models/smollm3/smollm3_backbone.py +1 -3
  52. keras_hub/src/models/smollm3/smollm3_presets.py +16 -0
  53. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_presets.py +1 -1
  54. keras_hub/src/models/stable_diffusion_3/t5_encoder.py +1 -3
  55. keras_hub/src/models/t5/t5_backbone.py +1 -3
  56. keras_hub/src/models/t5gemma/t5gemma_backbone.py +1 -3
  57. keras_hub/src/tests/test_case.py +1 -3
  58. keras_hub/src/utils/transformers/convert_gemma3.py +353 -0
  59. keras_hub/src/utils/transformers/convert_gpt_oss.py +302 -0
  60. keras_hub/src/utils/transformers/preset_loader.py +12 -0
  61. keras_hub/src/version.py +1 -1
  62. keras_hub/tokenizers/__init__.py +3 -0
  63. {keras_hub_nightly-0.24.0.dev202511220420.dist-info → keras_hub_nightly-0.26.0.dev202601010440.dist-info}/METADATA +4 -5
  64. {keras_hub_nightly-0.24.0.dev202511220420.dist-info → keras_hub_nightly-0.26.0.dev202601010440.dist-info}/RECORD +66 -53
  65. {keras_hub_nightly-0.24.0.dev202511220420.dist-info → keras_hub_nightly-0.26.0.dev202601010440.dist-info}/WHEEL +0 -0
  66. {keras_hub_nightly-0.24.0.dev202511220420.dist-info → keras_hub_nightly-0.26.0.dev202601010440.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,219 @@
1
+ import keras
2
+ from keras.layers import ReversibleEmbedding
3
+
4
+ from keras_hub.src.api_export import keras_hub_export
5
+ from keras_hub.src.models.backbone import Backbone
6
+ from keras_hub.src.models.gpt_oss.gpt_oss_decoder import (
7
+ GptOssTransformerDecoder,
8
+ )
9
+ from keras_hub.src.models.gpt_oss.gpt_oss_layer_norm import (
10
+ GptOssLayerNormalization,
11
+ )
12
+
13
+
14
+ def _gpt_oss_kernel_initializer(stddev=0.02):
15
+ return keras.initializers.RandomNormal(stddev=stddev)
16
+
17
+
18
+ @keras_hub_export("keras_hub.models.GptOssBackbone")
19
+ class GptOssBackbone(Backbone):
20
+ """A GPT-style Transformer with a Mixture of Experts.
21
+
22
+ This network implements a GPT-style decoder network with Mixture of Expert
23
+ (MoE) layers, similar to the architecture described in
24
+ ["Mixtral of Experts"](https://arxiv.org/pdf/2401.04088) but with
25
+ customizations found in some open-source GPT models. It includes the
26
+ embedding lookups and transformer layers.
27
+
28
+ The default constructor gives a fully customizable, randomly initialized
29
+ GptOss model with any number of layers, heads, and embedding
30
+ dimensions. To load preset architectures and weights, use the `from_preset`
31
+ constructor.
32
+
33
+ Args:
34
+ vocabulary_size: int. The size of the token vocabulary.
35
+ num_layers: int. The number of transformer layers.
36
+ num_query_heads: int. The number of query attention heads for
37
+ each transformer.
38
+ hidden_dim: int. The size of the transformer encoding and pooling
39
+ layers.
40
+ intermediate_dim: int. The output dimension of the first Dense layer
41
+ in a three-layer feedforward network for each transformer.
42
+ num_key_value_heads: int. The number of key and value attention heads
43
+ for each transformer.
44
+ num_experts: int. The number of experts for the MoE layers.
45
+ top_k: int. The number of experts to use for each token.
46
+ Defaults to `2`.
47
+ rope_max_wavelength: int. The maximum angular wavelength of
48
+ the sine/cosine curves, for rotary embeddings. Defaults to `10000`.
49
+ rope_scaling_factor: float. The scaling factor for
50
+ calculation of roatary embedding. Defaults to `1.0`.
51
+ layer_norm_epsilon: float. Epsilon for the layer
52
+ normalization layers in the transformer decoder. Defaults to `1e-6`.
53
+ sliding_window: int. The sliding window for the attention
54
+ layers. This controls the maximum cache size for the attention
55
+ layers in each transformer decoder. Only `sliding_window` number
56
+ of tokens are saved in the cache and used to generate the next
57
+ token. Defaults to `4096`.
58
+ head_dim: int. Head dimension for attention layers. This
59
+ parameter is accepted for HuggingFace compatibility but ignored.
60
+ The head dimension is calculated dynamically as hidden_dim //
61
+ num_query_heads. Defaults to `None`.
62
+ dropout: float. Attention dropout probability.
63
+ dtype: string or `keras.mixed_precision.DTypePolicy`. The dtype to use
64
+ for model computations and weights. Note that some computations,
65
+ such as softmax and layer normalization, will always be done at
66
+ `float32` precision regardless of dtype.
67
+
68
+ Examples:
69
+
70
+ ```python
71
+ import numpy as np
72
+ import keras_hub
73
+
74
+ # Load a pretrained GptOss backbone from a preset.
75
+ model = keras_hub.models.GptOssBackbone.from_preset("gpt_oss_20b_en")
76
+
77
+ input_data = {
78
+ "token_ids": np.ones(shape=(1, 12), dtype="int32"),
79
+ "padding_mask": np.array(
80
+ [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype="int32"
81
+ ),
82
+ }
83
+
84
+ model(input_data)
85
+
86
+ # Randomly initialized GptOss decoder with custom config.
87
+ model = keras_hub.models.GptOssBackbone(
88
+ vocabulary_size=10,
89
+ hidden_dim=512,
90
+ num_layers=2,
91
+ num_query_heads=32,
92
+ num_key_value_heads=8,
93
+ intermediate_dim=1024,
94
+ num_experts=4,
95
+ top_k=2,
96
+ sliding_window=256,
97
+ layer_norm_epsilon=1e-6,
98
+ dtype="float32"
99
+ )
100
+ model(input_data)
101
+ ```
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ vocabulary_size,
107
+ num_layers,
108
+ num_query_heads,
109
+ hidden_dim,
110
+ intermediate_dim,
111
+ num_key_value_heads,
112
+ num_experts,
113
+ top_k=2,
114
+ rope_max_wavelength=10000,
115
+ rope_scaling_factor=1.0,
116
+ layer_norm_epsilon=1e-6,
117
+ sliding_window=4096,
118
+ head_dim=None,
119
+ dropout=0,
120
+ output_router_logits=False,
121
+ dtype=None,
122
+ **kwargs,
123
+ ):
124
+ # === Layers ===
125
+ self.token_embedding = ReversibleEmbedding(
126
+ input_dim=vocabulary_size,
127
+ output_dim=hidden_dim,
128
+ tie_weights=False,
129
+ embeddings_initializer=_gpt_oss_kernel_initializer(stddev=0.01),
130
+ dtype=dtype,
131
+ name="token_embedding",
132
+ )
133
+ self.transformer_layers = []
134
+ for i in range(num_layers):
135
+ layer = GptOssTransformerDecoder(
136
+ intermediate_dim=intermediate_dim,
137
+ num_query_heads=num_query_heads,
138
+ num_key_value_heads=num_key_value_heads,
139
+ num_experts=num_experts,
140
+ top_k=top_k,
141
+ output_router_logits=output_router_logits,
142
+ rope_max_wavelength=rope_max_wavelength,
143
+ rope_scaling_factor=rope_scaling_factor,
144
+ layer_norm_epsilon=layer_norm_epsilon,
145
+ kernel_initializer=_gpt_oss_kernel_initializer(stddev=0.02),
146
+ # GPT-OSS uses SW attention in every other layer
147
+ sliding_window=sliding_window if i % 2 == 1 else None,
148
+ dropout=dropout,
149
+ head_dim=head_dim,
150
+ dtype=dtype,
151
+ name=f"transformer_layer_{i}",
152
+ )
153
+ self.transformer_layers.append(layer)
154
+ self.layer_norm = GptOssLayerNormalization(
155
+ epsilon=layer_norm_epsilon,
156
+ dtype=dtype,
157
+ name="sequence_output_layernorm",
158
+ )
159
+
160
+ # === Functional Model ===
161
+ token_id_input = keras.Input(
162
+ shape=(None,), dtype="int32", name="token_ids"
163
+ )
164
+ padding_mask_input = keras.Input(
165
+ shape=(None,), dtype="int32", name="padding_mask"
166
+ )
167
+ x = self.token_embedding(token_id_input)
168
+ for transformer_layer in self.transformer_layers:
169
+ x = transformer_layer(x, decoder_padding_mask=padding_mask_input)
170
+ sequence_output = self.layer_norm(x)
171
+ super().__init__(
172
+ inputs={
173
+ "token_ids": token_id_input,
174
+ "padding_mask": padding_mask_input,
175
+ },
176
+ outputs=sequence_output,
177
+ dtype=dtype,
178
+ **kwargs,
179
+ )
180
+
181
+ # === Config ===
182
+ self.vocabulary_size = vocabulary_size
183
+ self.num_layers = num_layers
184
+ self.num_query_heads = num_query_heads
185
+ self.hidden_dim = hidden_dim
186
+ self.intermediate_dim = intermediate_dim
187
+ self.num_key_value_heads = num_key_value_heads
188
+ self.num_experts = num_experts
189
+ self.top_k = top_k
190
+ self.rope_max_wavelength = rope_max_wavelength
191
+ self.rope_scaling_factor = rope_scaling_factor
192
+ self.sliding_window = sliding_window
193
+ self.layer_norm_epsilon = layer_norm_epsilon
194
+ self.dropout = dropout
195
+ self.output_router_logits = output_router_logits
196
+ self.head_dim = head_dim
197
+
198
+ def get_config(self):
199
+ config = super().get_config()
200
+ config.update(
201
+ {
202
+ "vocabulary_size": self.vocabulary_size,
203
+ "num_layers": self.num_layers,
204
+ "num_query_heads": self.num_query_heads,
205
+ "hidden_dim": self.hidden_dim,
206
+ "intermediate_dim": self.intermediate_dim,
207
+ "num_experts": self.num_experts,
208
+ "top_k": self.top_k,
209
+ "rope_max_wavelength": self.rope_max_wavelength,
210
+ "rope_scaling_factor": self.rope_scaling_factor,
211
+ "num_key_value_heads": self.num_key_value_heads,
212
+ "sliding_window": self.sliding_window,
213
+ "layer_norm_epsilon": self.layer_norm_epsilon,
214
+ "dropout": self.dropout,
215
+ "output_router_logits": self.output_router_logits,
216
+ "head_dim": self.head_dim,
217
+ }
218
+ )
219
+ return config
@@ -0,0 +1,284 @@
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.gpt_oss.gpt_oss_backbone import GptOssBackbone
7
+ from keras_hub.src.models.gpt_oss.gpt_oss_causal_lm_preprocessor import (
8
+ GptOssCausalLMPreprocessor,
9
+ )
10
+ from keras_hub.src.utils.tensor_utils import any_equal
11
+
12
+
13
+ @keras_hub_export("keras_hub.models.GptOssCausalLM")
14
+ class GptOssCausalLM(CausalLM):
15
+ """An end-to-end GptOss 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 GptOss 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.GptOssBackbone` instance.
31
+ preprocessor: A `keras_hub.models.GptOssCausalLMPreprocessor` 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 = GptOssBackbone
37
+ preprocessor_cls = GptOssCausalLMPreprocessor
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 `GptOssCausalLM` 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.head_dim or (
104
+ self.backbone.hidden_dim // self.backbone.num_query_heads
105
+ )
106
+ shape = [
107
+ batch_size,
108
+ num_layers,
109
+ 2,
110
+ max_length,
111
+ num_key_value_heads,
112
+ head_dim,
113
+ ]
114
+ cache = ops.zeros(shape, dtype=self.compute_dtype)
115
+ # Seed the cache.
116
+ _, hidden_states, cache = self.call_with_cache(token_ids, cache, 0)
117
+ return hidden_states, cache
118
+
119
+ def generate_step(
120
+ self,
121
+ inputs,
122
+ stop_token_ids=None,
123
+ ):
124
+ """A compilable generation function for a single batch of inputs.
125
+
126
+ This function represents the inner, XLA-compilable, generation function
127
+ for a single batch of inputs. Inputs should have the same structure as
128
+ model inputs, a dictionary with keys `"token_ids"` and `"padding_mask"`.
129
+
130
+ Args:
131
+ inputs: A dictionary with two keys `"token_ids"` and
132
+ `"padding_mask"` and batched tensor values.
133
+ stop_token_ids: List of id's of end token's to stop on. If all
134
+ sequences have produced a new stop token, generation
135
+ will stop.
136
+ """
137
+ token_ids, padding_mask = inputs["token_ids"], inputs["padding_mask"]
138
+ # Create and seed cache with a single forward pass.
139
+ hidden_states, cache = self._build_cache(token_ids)
140
+ # Compute the lengths of all user inputted tokens ids.
141
+ row_lengths = ops.sum(ops.cast(padding_mask, "int32"), axis=-1)
142
+ # Start at the first index that has no user inputted id.
143
+ index = ops.min(row_lengths)
144
+
145
+ def next(prompt, cache, index):
146
+ # The cache index is the index of our previous token.
147
+ cache_update_index = index - 1
148
+ batch_size = ops.shape(prompt)[0]
149
+ prompt = ops.slice(prompt, [0, cache_update_index], [batch_size, 1])
150
+ logits, hidden_states, cache = self.call_with_cache(
151
+ prompt,
152
+ cache,
153
+ cache_update_index,
154
+ )
155
+ return (
156
+ ops.squeeze(logits, axis=1),
157
+ ops.squeeze(hidden_states, axis=1),
158
+ cache,
159
+ )
160
+
161
+ token_ids = self.sampler(
162
+ next=next,
163
+ prompt=token_ids,
164
+ cache=cache,
165
+ index=index,
166
+ mask=padding_mask,
167
+ stop_token_ids=stop_token_ids,
168
+ hidden_states=hidden_states,
169
+ model=self,
170
+ )
171
+
172
+ # Compute an output padding mask with the token ids we updated.
173
+ if stop_token_ids is not None:
174
+ # Build a mask of stop_tokens locations not in the original
175
+ # prompt (not in locations where `padding_mask` is True).
176
+ end_locations = any_equal(
177
+ token_ids, stop_token_ids, ops.logical_not(padding_mask)
178
+ )
179
+
180
+ end_locations = ops.cast(end_locations, "int32")
181
+ # Use cumsum to get ones in all locations after end_locations.
182
+ cumsum = ops.cast(ops.cumsum(end_locations, axis=-1), "int32")
183
+ overflow = cumsum - end_locations
184
+ # Our padding mask is the inverse of these overflow locations.
185
+ padding_mask = ops.logical_not(ops.cast(overflow, "bool"))
186
+ else:
187
+ # Without early stopping, all locations will have been updated.
188
+ padding_mask = ops.ones_like(token_ids, dtype="bool")
189
+ return {
190
+ "token_ids": token_ids,
191
+ "padding_mask": padding_mask,
192
+ }
193
+
194
+ def score(
195
+ self,
196
+ token_ids,
197
+ padding_mask=None,
198
+ scoring_mode="logits",
199
+ layer_intercept_fn=None,
200
+ target_ids=None,
201
+ ):
202
+ """Score a generation represented by the provided token ids.
203
+
204
+ Args:
205
+ token_ids: A `<int>[batch_size, num_tokens]` tensor containing
206
+ tokens to score. Typically, this tensor captures the output
207
+ from a call to `GptOssCausalLM.generate()`, i.e., tokens for
208
+ both the input text and the model-generated text.
209
+ padding_mask: A `<bool>[batch_size, num_tokens]` tensor indicating
210
+ the tokens that should be preserved during generation. This is
211
+ an artifact required by the GptOssBackbone and isn't
212
+ influential on the computation of this function. If omitted,
213
+ this function uses `keras.ops.ones()` to create a tensor of
214
+ the appropriate shape.
215
+ scoring_mode: The type of scores to return, either "logits" or
216
+ "loss", both will be per input token.
217
+ layer_intercept_fn: An optional function for augmenting
218
+ activations with additional computation, for example, as part
219
+ of interpretability research. This function will be passed the
220
+ activations as its first parameter and a numeric index
221
+ associated with that backbone layer. _This index _is not_ an
222
+ index into `self.backbone.layers`. The index -1 accompanies
223
+ the embeddings returned by calling
224
+ `self.backbone.token_embedding()` on `token_ids` in the
225
+ forward direction. All subsequent indexes will be 0-based
226
+ indices for the activations returned by each of the
227
+ Transformers layers in the backbone. This function must
228
+ return a `<float>[batch_size, num_tokens, hidden_dims]`
229
+ tensor that can be passed as an input to the next layer in
230
+ the model.
231
+ target_ids: An `<bool>[batch_size, num_tokens]` tensor containing
232
+ the predicted tokens against which the loss should be
233
+ computed. If a span of tokens is provided (sequential truthy
234
+ values along axis=1 in the tensor), the loss will be computed
235
+ as the aggregate across those tokens.
236
+
237
+ Raises:
238
+ ValueError: If an unsupported scoring_mode is provided, or if the
239
+ target_ids are not provided when using ScoringMode.LOSS.
240
+
241
+ Returns:
242
+ The per-token scores as a tensor of size
243
+ `<float>[batch_size, num_tokens, vocab_size]` in "logits" mode, or
244
+ `<float>[batch_size, num_tokens]` in "loss" mode.
245
+ """
246
+ if scoring_mode not in ("logits", "loss"):
247
+ raise ValueError(
248
+ "Unsupported scoring_mode. Must be one of 'logits' or 'loss'."
249
+ )
250
+
251
+ if scoring_mode == "loss" and target_ids is None:
252
+ raise ValueError(
253
+ "Cannot compute loss without targets. Please provide target "
254
+ "token ids via the target_ids parameter."
255
+ )
256
+
257
+ batch_shape = ops.shape(token_ids)[:2]
258
+ assert len(batch_shape) == 2
259
+
260
+ if layer_intercept_fn is None:
261
+
262
+ def default_layer_intercept_fn(x, unused_i):
263
+ return x
264
+
265
+ layer_intercept_fn = default_layer_intercept_fn
266
+
267
+ token_embeddings = self.backbone.token_embedding(token_ids)
268
+ x = layer_intercept_fn(token_embeddings, -1)
269
+
270
+ for i, transformer_layer in enumerate(self.backbone.transformer_layers):
271
+ x = transformer_layer(x, decoder_padding_mask=padding_mask)
272
+ x = layer_intercept_fn(x, i)
273
+
274
+ x = self.backbone.layer_norm(x)
275
+ logits = self.backbone.token_embedding(x, reverse=True)
276
+
277
+ if scoring_mode == "logits":
278
+ return logits
279
+
280
+ per_token_loss_fn = keras.losses.SparseCategoricalCrossentropy(
281
+ from_logits=True, reduction="none"
282
+ )
283
+ per_token_loss = per_token_loss_fn(target_ids, logits)
284
+ return per_token_loss
@@ -0,0 +1,79 @@
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.gpt_oss.gpt_oss_backbone import GptOssBackbone
4
+ from keras_hub.src.models.gpt_oss.gpt_oss_tokenizer import GptOssTokenizer
5
+
6
+
7
+ @keras_hub_export("keras_hub.models.GptOssCausalLMPreprocessor")
8
+ class GptOssCausalLMPreprocessor(CausalLMPreprocessor):
9
+ """GptOss Causal LM preprocessor.
10
+
11
+ This preprocessing layer is meant for use with
12
+ `keras_hub.models.GptOssCausalLM`. 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.GptOssCausalLM` 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.GptOssTokenizer` 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
+ import tensorflow as tf
42
+ import keras_hub
43
+
44
+ # Load the preprocessor from a preset.
45
+ preprocessor = keras_hub.models.GptOssCausalLMPreprocessor.from_preset(
46
+ "gpt_oss_base_en"
47
+ )
48
+
49
+ # Tokenize and pack a single sentence.
50
+ sentence = tf.constant("League of legends")
51
+ preprocessor(sentence)
52
+ # Same output.
53
+ preprocessor("League of legends")
54
+
55
+ # Tokenize a batch of sentences.
56
+ sentences = tf.constant(["Taco tuesday", "Fish taco please!"])
57
+ preprocessor(sentences)
58
+ # Same output.
59
+ preprocessor(["Taco tuesday", "Fish taco please!"])
60
+
61
+ # Map a dataset to preprocess a single sentence.
62
+ features = tf.constant(
63
+ [
64
+ "Avatar 2 is amazing!",
65
+ "Well, I am not sure.",
66
+ ]
67
+ )
68
+ labels = tf.constant([1, 0])
69
+ ds = tf.data.Dataset.from_tensor_slices((features, labels))
70
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
71
+
72
+ # Map a dataset to preprocess unlabled sentences.
73
+ ds = tf.data.Dataset.from_tensor_slices(features)
74
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
75
+ ```
76
+ """
77
+
78
+ backbone_cls = GptOssBackbone
79
+ tokenizer_cls = GptOssTokenizer