keras-hub-nightly 0.23.0.dev202510170417__py3-none-any.whl → 0.23.0.dev202510180414__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.

@@ -649,6 +649,30 @@ from keras_hub.src.models.siglip.siglip_tokenizer import (
649
649
  from keras_hub.src.models.siglip.siglip_vision_encoder import (
650
650
  SigLIPVisionEncoder as SigLIPVisionEncoder,
651
651
  )
652
+ from keras_hub.src.models.smollm3.smollm3_backbone import (
653
+ SmolLM3Backbone as SmolLM3Backbone,
654
+ )
655
+ from keras_hub.src.models.smollm3.smollm3_backbone import (
656
+ SmolLM3Backbone as SmolLMBackbone,
657
+ )
658
+ from keras_hub.src.models.smollm3.smollm3_causal_lm import (
659
+ SmolLM3CausalLM as SmolLM3CausalLM,
660
+ )
661
+ from keras_hub.src.models.smollm3.smollm3_causal_lm import (
662
+ SmolLM3CausalLM as SmolLMCausalLM,
663
+ )
664
+ from keras_hub.src.models.smollm3.smollm3_causal_lm_preprocessor import (
665
+ SmolLM3CausalLMPreprocessor as SmolLM3CausalLMPreprocessor,
666
+ )
667
+ from keras_hub.src.models.smollm3.smollm3_causal_lm_preprocessor import (
668
+ SmolLM3CausalLMPreprocessor as SmolLMCausalLMPreprocessor,
669
+ )
670
+ from keras_hub.src.models.smollm3.smollm3_tokenizer import (
671
+ SmolLM3Tokenizer as SmolLM3Tokenizer,
672
+ )
673
+ from keras_hub.src.models.smollm3.smollm3_tokenizer import (
674
+ SmolLM3Tokenizer as SmolLMTokenizer,
675
+ )
652
676
  from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_backbone import (
653
677
  StableDiffusion3Backbone as StableDiffusion3Backbone,
654
678
  )
@@ -206,4 +206,26 @@ backbone_presets = {
206
206
  },
207
207
  "kaggle_handle": "kaggle://keras/vaultgemma/keras/vault_gemma_1b_en/2",
208
208
  },
209
+ "c2s_scale_gemma_2_2b_en": {
210
+ "metadata": {
211
+ "description": (
212
+ "A 2 billion parameter, single-cell biology-aware model "
213
+ "built on the Gemma-2 architecture."
214
+ ),
215
+ "params": 2614341888,
216
+ "path": "gemma",
217
+ },
218
+ "kaggle_handle": "kaggle://keras/cell2sentence/keras/c2s_scale_gemma_2_2b_en/1",
219
+ },
220
+ "c2s_scale_gemma_2_27b_en": {
221
+ "metadata": {
222
+ "description": (
223
+ "A 27 billion parameter, single-cell biology-aware model "
224
+ "built on the Gemma-2 architecture."
225
+ ),
226
+ "params": 27227128320,
227
+ "path": "gemma",
228
+ },
229
+ "kaggle_handle": "kaggle://keras/cell2sentence/keras/c2s_scale_gemma_2_27b_en/1",
230
+ },
209
231
  }
@@ -0,0 +1,211 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.layers.modeling.reversible_embedding import (
5
+ ReversibleEmbedding,
6
+ )
7
+ from keras_hub.src.models.backbone import Backbone
8
+ from keras_hub.src.models.smollm3.smollm3_layers import SmolLM3DecoderLayer
9
+
10
+
11
+ @keras_hub_export(
12
+ [
13
+ "keras_hub.models.SmolLM3Backbone",
14
+ "keras_hub.models.SmolLMBackbone",
15
+ ]
16
+ )
17
+ class SmolLM3Backbone(Backbone):
18
+ """SmolLM3 core network with hyperparameters.
19
+
20
+ This network implements a Transformer-based decoder network,
21
+ SmolLM3, as described in the SmolLM3 model architecture.
22
+ It includes the embedding lookups and transformer layers.
23
+
24
+ The default constructor gives a fully customizable, randomly initialized
25
+ SmolLM3 model with any number of layers, heads, and embedding
26
+ dimensions. To load preset architectures and weights, use the `from_preset`
27
+ constructor.
28
+
29
+ Args:
30
+ vocabulary_size: int. The size of the token vocabulary.
31
+ hidden_dim: int. The size of the transformer hidden state at the end
32
+ of each transformer layer.
33
+ intermediate_dim: int. The output dimension of the first Dense layer in
34
+ the MLP network of each transformer layer.
35
+ num_layers: int. The number of transformer layers.
36
+ num_attention_heads: int. The number of attention heads for each
37
+ transformer layer.
38
+ num_key_value_heads: int. The number of key-value heads for grouped
39
+ query attention in each transformer layer.
40
+ attention_bias: bool. Whether to use bias in the query, key, value, and
41
+ output projection layers in the attention blocks.
42
+ attention_dropout: float. Dropout probability for the attention layers.
43
+ rope_layer_enabled_list: list of bool. List indicating whether RoPE
44
+ (Rotary Position Embedding) is enabled for each layer. Typically,
45
+ some layers may disable RoPE for architectural variations.
46
+ layer_types: list of str. List of layer types for each transformer
47
+ layer (e.g., "attention" or other custom types).
48
+ mlp_bias: bool. Whether to use bias in the MLP (feedforward) layers.
49
+ layer_norm_epsilon: float. Epsilon value for layer normalization layers
50
+ to prevent division by zero.
51
+ max_position_embeddings: int. The maximum sequence length that this
52
+ model might ever be used with.
53
+ rope_theta: float. The base period of the RoPE embeddings.
54
+ partial_rotary_factor: float. The percentage of hidden dimensions to
55
+ rotate in RoPE. A value of 1.0 rotates all dimensions, while values
56
+ less than 1.0 only rotate a subset.
57
+
58
+ Examples:
59
+
60
+ ```python
61
+ input_data = {
62
+ "token_ids": np.ones(shape=(1, 12), dtype="int32"),
63
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]),
64
+ }
65
+
66
+ # Pretrained SmolLM3 decoder.
67
+ model = keras_hub.models.SmolLM3Backbone.from_preset(
68
+ "hf://HuggingFaceTB/SmolLM3-3B"
69
+ )
70
+ model(input_data)
71
+
72
+ # Randomly initialized SmolLM3 decoder with custom config.
73
+ model = keras_hub.models.SmolLM3Backbone(
74
+ vocabulary_size=49152,
75
+ hidden_dim=576,
76
+ intermediate_dim=1536,
77
+ num_layers=30,
78
+ num_attention_heads=9,
79
+ num_key_value_heads=3,
80
+ attention_bias=False,
81
+ attention_dropout=0.0,
82
+ rope_layer_enabled_list=[True] * 30,
83
+ layer_types=["attention"] * 30,
84
+ mlp_bias=False,
85
+ layer_norm_epsilon=1e-5,
86
+ max_position_embeddings=2048,
87
+ rope_theta=10000.0,
88
+ partial_rotary_factor=1.0,
89
+ )
90
+ model(input_data)
91
+ ```
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ vocabulary_size,
97
+ hidden_dim,
98
+ intermediate_dim,
99
+ num_layers,
100
+ num_attention_heads,
101
+ num_key_value_heads,
102
+ attention_bias,
103
+ attention_dropout,
104
+ rope_layer_enabled_list,
105
+ layer_types,
106
+ mlp_bias,
107
+ layer_norm_epsilon,
108
+ max_position_embeddings,
109
+ rope_theta,
110
+ partial_rotary_factor,
111
+ **kwargs,
112
+ ):
113
+ # === Layers ===
114
+ self.token_embedding = ReversibleEmbedding(
115
+ input_dim=vocabulary_size,
116
+ output_dim=hidden_dim,
117
+ name="token_embedding",
118
+ )
119
+ self.transformer_layers = []
120
+ for i in range(num_layers):
121
+ layer = SmolLM3DecoderLayer(
122
+ hidden_size=hidden_dim,
123
+ num_attention_heads=num_attention_heads,
124
+ num_key_value_heads=num_key_value_heads,
125
+ attention_bias=attention_bias,
126
+ attention_dropout=attention_dropout,
127
+ rope_layer_enabled_list=rope_layer_enabled_list,
128
+ layer_types=layer_types,
129
+ layer_idx=i,
130
+ intermediate_size=intermediate_dim,
131
+ mlp_bias=mlp_bias,
132
+ layer_norm_epsilon=layer_norm_epsilon,
133
+ max_position_embeddings=max_position_embeddings,
134
+ rope_theta=rope_theta,
135
+ partial_rotary_factor=partial_rotary_factor,
136
+ name=f"transformer_layer_{i}",
137
+ )
138
+ self.transformer_layers.append(layer)
139
+
140
+ self.norm = keras.layers.RMSNormalization(
141
+ epsilon=layer_norm_epsilon,
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
+
150
+ padding_mask_input = keras.Input(
151
+ shape=(None,), dtype="int32", name="padding_mask"
152
+ )
153
+
154
+ x = self.token_embedding(token_id_input)
155
+
156
+ for decoder_layer in self.transformer_layers:
157
+ x = decoder_layer(
158
+ x,
159
+ decoder_padding_mask=padding_mask_input,
160
+ **kwargs,
161
+ )
162
+
163
+ sequence_output = self.norm(x)
164
+ super().__init__(
165
+ inputs={
166
+ "token_ids": token_id_input,
167
+ "padding_mask": padding_mask_input,
168
+ },
169
+ outputs=sequence_output,
170
+ **kwargs,
171
+ )
172
+
173
+ # === Config ===
174
+ self.vocabulary_size = vocabulary_size
175
+ self.hidden_dim = hidden_dim
176
+ self.intermediate_dim = intermediate_dim
177
+ self.num_layers = num_layers
178
+ self.num_attention_heads = num_attention_heads
179
+ self.num_key_value_heads = num_key_value_heads
180
+ self.attention_bias = attention_bias
181
+ self.attention_dropout = attention_dropout
182
+ self.rope_layer_enabled_list = rope_layer_enabled_list
183
+ self.layer_types = layer_types
184
+ self.mlp_bias = mlp_bias
185
+ self.layer_norm_epsilon = layer_norm_epsilon
186
+ self.max_position_embeddings = max_position_embeddings
187
+ self.rope_theta = rope_theta
188
+ self.partial_rotary_factor = partial_rotary_factor
189
+
190
+ def get_config(self):
191
+ config = super().get_config()
192
+ config.update(
193
+ {
194
+ "vocabulary_size": self.vocabulary_size,
195
+ "hidden_dim": self.hidden_dim,
196
+ "intermediate_dim": self.intermediate_dim,
197
+ "num_layers": self.num_layers,
198
+ "num_attention_heads": self.num_attention_heads,
199
+ "num_key_value_heads": self.num_key_value_heads,
200
+ "attention_bias": self.attention_bias,
201
+ "attention_dropout": self.attention_dropout,
202
+ "rope_layer_enabled_list": self.rope_layer_enabled_list,
203
+ "layer_types": self.layer_types,
204
+ "mlp_bias": self.mlp_bias,
205
+ "layer_norm_epsilon": self.layer_norm_epsilon,
206
+ "max_position_embeddings": self.max_position_embeddings,
207
+ "rope_theta": self.rope_theta,
208
+ "partial_rotary_factor": self.partial_rotary_factor,
209
+ }
210
+ )
211
+ return config
@@ -0,0 +1,310 @@
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.smollm3.smollm3_backbone import SmolLM3Backbone
7
+ from keras_hub.src.models.smollm3.smollm3_causal_lm_preprocessor import (
8
+ SmolLM3CausalLMPreprocessor,
9
+ )
10
+ from keras_hub.src.utils.tensor_utils import any_equal
11
+
12
+
13
+ @keras_hub_export(
14
+ [
15
+ "keras_hub.models.SmolLM3CausalLM",
16
+ "keras_hub.models.SmolLMCausalLM",
17
+ ]
18
+ )
19
+ class SmolLM3CausalLM(CausalLM):
20
+ backbone_cls = SmolLM3Backbone
21
+ preprocessor_cls = SmolLM3CausalLMPreprocessor
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 `SmolLM3CausalLM` 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, seq_len)`.
55
+ For prefill, `seq_len` is the prompt length. For generation,
56
+ `seq_len` is typically 1.
57
+ cache: a dense float Tensor, the cache of key and value.
58
+ Shape: (batch_size, num_layers, 2, max_seq_len,
59
+ num_key_value_heads, head_dim)
60
+ cache_update_index: int, or int Tensor. The index of current
61
+ inputs in the whole sequence.
62
+ training: Boolean, whether the call is during training or inference.
63
+ attention_mask: Optional attention mask.
64
+
65
+ Returns:
66
+ A (logits, hidden_states, cache) tuple. Where `logits` is the
67
+ language model logits for the input token_ids, `hidden_states` is
68
+ the final hidden representation of the input tokens, and `cache` is
69
+ the decoding cache.
70
+ """
71
+ x = self.backbone.token_embedding(token_ids)
72
+
73
+ # Each decoder layer has a cache; we update them separately.
74
+ updated_cache = []
75
+
76
+ for i in range(self.backbone.num_layers):
77
+ current_cache = cache[:, i, ...]
78
+ x, next_cache = self.backbone.transformer_layers[i](
79
+ x,
80
+ self_attention_cache=current_cache,
81
+ self_attention_cache_update_index=cache_update_index,
82
+ )
83
+ updated_cache.append(next_cache)
84
+ cache = ops.stack(updated_cache, axis=1)
85
+ hidden_states = x = self.backbone.norm(x)
86
+ logits = self.backbone.token_embedding(x, reverse=True)
87
+ return logits, hidden_states, cache
88
+
89
+ def _build_cache(self, token_ids):
90
+ """Build an empty cache for use with `call_with_cache()`."""
91
+ batch_size = ops.shape(token_ids)[0]
92
+ max_length = ops.shape(token_ids)[1]
93
+ num_layers = self.backbone.num_layers
94
+ num_key_value_heads = self.backbone.num_key_value_heads
95
+ head_dim = self.backbone.hidden_dim // self.backbone.num_attention_heads
96
+ shape = [
97
+ batch_size,
98
+ num_layers,
99
+ 2,
100
+ max_length,
101
+ num_key_value_heads,
102
+ head_dim,
103
+ ]
104
+ cache = ops.zeros(shape, dtype=self.compute_dtype)
105
+ index = ops.convert_to_tensor(0, dtype="int32")
106
+ # Seed the cache.
107
+ _, hidden_states, cache = self.call_with_cache(token_ids, cache, index)
108
+ return hidden_states, cache
109
+
110
+ def generate_step(
111
+ self,
112
+ inputs,
113
+ stop_token_ids=None,
114
+ ):
115
+ """A compilable generation function for a single batch of inputs.
116
+
117
+ This function represents the inner, XLA-compilable, generation function
118
+ for a single batch of inputs. Inputs should have the same structure as
119
+ model inputs, a dictionary with keys `"token_ids"` and `"padding_mask"`.
120
+
121
+ Args:
122
+ inputs: A dictionary with two keys `"token_ids"` and
123
+ `"padding_mask"` and batched tensor values.
124
+ stop_token_ids: Tuple of id's of the end token to stop on. If all
125
+ sequences have produced a new stop token, generation
126
+ will stop.
127
+ """
128
+ token_ids, padding_mask = inputs["token_ids"], inputs["padding_mask"]
129
+
130
+ hidden_states, cache = self._build_cache(token_ids)
131
+ # Compute the lengths of all user inputted tokens ids.
132
+ row_lengths = ops.sum(ops.cast(padding_mask, "int32"), axis=-1)
133
+ # Start at the first index that has no user inputted id.
134
+ index = ops.min(row_lengths)
135
+
136
+ def next(prompt, cache, index):
137
+ # The cache index is the index of our previous token.
138
+ cache_update_index = index - 1
139
+ batch_size = ops.shape(prompt)[0]
140
+ prompt = ops.slice(prompt, [0, cache_update_index], [batch_size, 1])
141
+
142
+ logits, hidden_states, cache = self.call_with_cache(
143
+ prompt,
144
+ cache,
145
+ cache_update_index,
146
+ )
147
+ return (
148
+ ops.squeeze(logits, axis=1),
149
+ ops.squeeze(hidden_states, axis=1),
150
+ cache,
151
+ )
152
+
153
+ token_ids = self.sampler(
154
+ next=next,
155
+ prompt=token_ids,
156
+ cache=cache,
157
+ index=index,
158
+ mask=padding_mask,
159
+ stop_token_ids=stop_token_ids,
160
+ hidden_states=hidden_states,
161
+ model=self,
162
+ )
163
+
164
+ # Compute an output padding mask with the token ids we updated.
165
+ if stop_token_ids is not None:
166
+ # Build a mask of stop token locations not in the original
167
+ # prompt (not in locations where `padding_mask` is True).
168
+ end_locations = any_equal(
169
+ token_ids, stop_token_ids, ops.logical_not(padding_mask)
170
+ )
171
+ end_locations = ops.cast(end_locations, "int32")
172
+ # Use cumsum to get ones in all locations after end_locations.
173
+ cumsum = ops.cast(ops.cumsum(end_locations, axis=-1), "int32")
174
+ overflow = cumsum - end_locations
175
+ # Our padding mask is the inverse of these overflow locations.
176
+ padding_mask = ops.logical_not(ops.cast(overflow, "bool"))
177
+ else:
178
+ # Without early stopping, all locations will have been updated.
179
+ padding_mask = ops.ones_like(token_ids, dtype="bool")
180
+ return {
181
+ "token_ids": token_ids,
182
+ "padding_mask": padding_mask,
183
+ }
184
+
185
+ def score(
186
+ self,
187
+ token_ids,
188
+ padding_mask=None,
189
+ scoring_mode="logits",
190
+ layer_intercept_fn=None,
191
+ target_ids=None,
192
+ ):
193
+ """Score a generation represented by the provided token ids.
194
+
195
+ Args:
196
+ token_ids: A <int>[batch_size, num_tokens] tensor containing tokens
197
+ to score. Typically, this tensor captures the output from a call
198
+ to `SmolLM3CausalLM.generate()`, i.e., tokens for both the input
199
+ text and the model-generated text.
200
+ padding_mask: A <bool>[batch_size, num_tokens] tensor indicating the
201
+ tokens that should be preserved during generation. This is an
202
+ artifact required by the `SmolLM3Backbone` and isn't influential
203
+ on the computation of this function. If omitted, this function
204
+ uses `keras.ops.ones()` to create a tensor of the appropriate
205
+ shape.
206
+ scoring_mode: The type of scores to return, either "logits" or
207
+ "loss", both will be per input token.
208
+ layer_intercept_fn: An optional function for augmenting activations
209
+ with additional computation, for example, as part of
210
+ interpretability research. This function will be passed the
211
+ activations as its first parameter and a numeric index
212
+ associated with that backbone layer. _This index _is not_ an
213
+ index into `self.backbone.layers`_. The index -1 accompanies the
214
+ embeddings returned by calling `self.backbone.token_embedding()`
215
+ on `token_ids` in the forward direction. All subsequent indexes
216
+ will be 0-based indices for the activations returned by each of
217
+ the Transformers layers in the backbone. This function must
218
+ return a <float>[batch_size, num_tokens, hidden_dims] tensor
219
+ that can be passed as an input to the next layer in the model.
220
+ target_ids: An <bool>[batch_size, num_tokens] tensor containing the
221
+ predicted tokens against which the loss should be computed. If a
222
+ span of tokens is provided (sequential truthy values along
223
+ axis=1 in the tensor), the loss will be computed as the
224
+ aggregate across those tokens.
225
+
226
+ Raises:
227
+ ValueError: If an unsupported scoring_mode is provided, or if the
228
+ target_ids are not provided when using ScoringMode.LOSS.
229
+
230
+ Returns:
231
+ The per-token scores as a tensor of size
232
+ <float>[batch_size, num_tokens, vocab_size] in "logits" mode, or
233
+ <float>[batch_size, num_tokens] in "loss" mode.
234
+
235
+ Example:
236
+
237
+ Compute gradients between embeddings and loss scores with TensorFlow:
238
+ ```python
239
+ smol_lm = keras_hub.models.SmolLM3CausalLM.from_preset("...")
240
+ generations = smol_lm.generate(
241
+ ["This is a", "Where are you"],
242
+ max_length=30
243
+ )
244
+ preprocessed = smol_lm.preprocessor.generate_preprocess(generations)
245
+ generation_ids = preprocessed["token_ids"]
246
+ padding_mask = preprocessed["padding_mask"]
247
+ target_ids = keras.ops.roll(generation_ids, shift=-1, axis=1)
248
+
249
+ embeddings = None
250
+ with tf.GradientTape(watch_accessed_variables=True) as tape:
251
+ def layer_intercept_fn(x, i):
252
+ if i == -1:
253
+ nonlocal embeddings, tape
254
+ embeddings = x
255
+ tape.watch(embeddings)
256
+ return x
257
+
258
+ losses = smol_lm.score(
259
+ token_ids=generation_ids,
260
+ padding_mask=padding_mask,
261
+ scoring_mode="loss",
262
+ layer_intercept_fn=layer_intercept_fn,
263
+ target_ids=target_ids,
264
+ )
265
+
266
+ grads = tape.gradient(losses, embeddings)
267
+ ```
268
+ """
269
+ if scoring_mode not in ("logits", "loss"):
270
+ raise ValueError(
271
+ "Unsupported scoring_mode. Must be one of 'logits' or 'loss'."
272
+ )
273
+
274
+ if scoring_mode == "loss" and target_ids is None:
275
+ raise ValueError(
276
+ "Cannot compute loss without targets. Please provide target "
277
+ "token ids via the target_ids parameter."
278
+ )
279
+
280
+ batch_shape = ops.shape(token_ids)[:2]
281
+ assert len(batch_shape) == 2
282
+
283
+ if padding_mask is None:
284
+ padding_mask = ops.ones(shape=batch_shape)
285
+
286
+ if layer_intercept_fn is None:
287
+
288
+ def default_layer_intercept_fn(x, unused_i):
289
+ return x
290
+
291
+ layer_intercept_fn = default_layer_intercept_fn
292
+
293
+ token_embeddings = self.backbone.token_embedding(token_ids)
294
+ x = layer_intercept_fn(token_embeddings, -1)
295
+
296
+ for i, transformer_layer in enumerate(self.backbone.transformer_layers):
297
+ x = transformer_layer(x, decoder_padding_mask=padding_mask)
298
+ x = layer_intercept_fn(x, i)
299
+
300
+ x = self.backbone.norm(x)
301
+ logits = self.backbone.token_embedding(x, reverse=True)
302
+
303
+ if scoring_mode == "logits":
304
+ return logits
305
+
306
+ per_token_loss_fn = keras.losses.SparseCategoricalCrossentropy(
307
+ from_logits=True, reduction="none"
308
+ )
309
+ per_token_loss = per_token_loss_fn(target_ids, logits)
310
+ return per_token_loss
@@ -0,0 +1,84 @@
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.smollm3.smollm3_backbone import SmolLM3Backbone
4
+ from keras_hub.src.models.smollm3.smollm3_tokenizer import SmolLM3Tokenizer
5
+
6
+
7
+ @keras_hub_export(
8
+ [
9
+ "keras_hub.models.SmolLMCausalLMPreprocessor",
10
+ "keras_hub.models.SmolLM3CausalLMPreprocessor",
11
+ ]
12
+ )
13
+ class SmolLM3CausalLMPreprocessor(CausalLMPreprocessor):
14
+ """SmolLM3 Causal LM preprocessor.
15
+
16
+ This preprocessing layer is meant for use with
17
+ `keras_hub.models.SmolLM3CausalLM`. By default, it will take in batches of
18
+ strings, and return outputs in a `(x, y, sample_weight)` format, where the
19
+ `y` label is the next token id in the `x` sequence.
20
+
21
+ For use with generation, the layer also exposes two methods
22
+ `generate_preprocess()` and `generate_postprocess()`. When this preprocessor
23
+ is attached to a `keras_hub.models.SmolLM3CausalLM` instance, these methods
24
+ will be called implicitly in `generate()`. They can also be called
25
+ standalone (e.g. to precompute preprocessing inputs for generation in a
26
+ separate process).
27
+
28
+ Args:
29
+ tokenizer: A `keras_hub.models.SmolLM3Tokenizer` instance.
30
+ sequence_length: The length of the packed inputs.
31
+ add_start_token: If `True`, the preprocessor will prepend the tokenizer
32
+ start token to each input sequence. Default is `True`.
33
+ add_end_token: If `True`, the preprocessor will append the tokenizer
34
+ end token to each input sequence. Default is `False`.
35
+
36
+ Call arguments:
37
+ x: A string, `tf.Tensor` or list of python strings.
38
+ y: Label data. Should always be `None` as the layer generates labels.
39
+ sample_weight: Label weights. Should always be `None` as the layer
40
+ generates label weights.
41
+ sequence_length: Pass to override the configured `sequence_length` of
42
+ the layer.
43
+
44
+ Examples:
45
+ ```python
46
+ # Load the preprocessor from a preset.
47
+ preprocessor = keras_hub.models.SmolLM3CausalLMPreprocessor.from_preset(
48
+ "..."
49
+ )
50
+
51
+ # Tokenize and pack a single sentence.
52
+ sentence = tf.constant("...")
53
+ preprocessor(sentence)
54
+ # Same output.
55
+ preprocessor("...")
56
+
57
+ # Tokenize a batch of sentences.
58
+ sentences = tf.constant(["...", "..."])
59
+ preprocessor(sentences)
60
+ # Same output.
61
+ preprocessor(["...", "..."])
62
+
63
+ # Map a dataset to preprocess a single sentence.
64
+ features = tf.constant(
65
+ [
66
+ "...",
67
+ "...",
68
+ ]
69
+ )
70
+ labels = tf.constant([1, 0])
71
+ ds = tf.data.Dataset.from_tensor_slices((features, labels))
72
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
73
+
74
+ # Map a dataset to preprocess unlabled sentences.
75
+ ds = tf.data.Dataset.from_tensor_slices(features)
76
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
77
+ ```
78
+ """
79
+
80
+ backbone_cls = SmolLM3Backbone
81
+ tokenizer_cls = SmolLM3Tokenizer
82
+
83
+ def __init__(self, *args, **kwargs):
84
+ super().__init__(*args, **kwargs)