keras-hub-nightly 0.23.0.dev202509180413__py3-none-any.whl → 0.23.0.dev202509280419__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 (32) hide show
  1. keras_hub/layers/__init__.py +3 -0
  2. keras_hub/models/__init__.py +24 -0
  3. keras_hub/src/models/depth_anything/__init__.py +9 -0
  4. keras_hub/src/models/depth_anything/depth_anything_backbone.py +232 -0
  5. keras_hub/src/models/depth_anything/depth_anything_depth_estimator.py +70 -0
  6. keras_hub/src/models/depth_anything/depth_anything_depth_estimator_preprocessor.py +16 -0
  7. keras_hub/src/models/depth_anything/depth_anything_image_converter.py +10 -0
  8. keras_hub/src/models/depth_anything/depth_anything_layers.py +725 -0
  9. keras_hub/src/models/depth_anything/depth_anything_loss.py +89 -0
  10. keras_hub/src/models/depth_anything/depth_anything_presets.py +4 -0
  11. keras_hub/src/models/depth_anything/interpolate.py +62 -0
  12. keras_hub/src/models/depth_estimator.py +239 -0
  13. keras_hub/src/models/depth_estimator_preprocessor.py +78 -0
  14. keras_hub/src/models/dinov2/dinov2_backbone.py +29 -3
  15. keras_hub/src/models/dinov2/dinov2_layers.py +13 -3
  16. keras_hub/src/models/qwen3_moe/qwen3_moe_attention.py +371 -0
  17. keras_hub/src/models/qwen3_moe/qwen3_moe_backbone.py +365 -0
  18. keras_hub/src/models/qwen3_moe/qwen3_moe_causal_lm.py +357 -0
  19. keras_hub/src/models/qwen3_moe/qwen3_moe_causal_lm_preprocessor.py +12 -0
  20. keras_hub/src/models/qwen3_moe/qwen3_moe_decoder.py +672 -0
  21. keras_hub/src/models/qwen3_moe/qwen3_moe_layernorm.py +45 -0
  22. keras_hub/src/models/qwen3_moe/qwen3_moe_tokenizer.py +48 -0
  23. keras_hub/src/tests/test_case.py +3 -2
  24. keras_hub/src/utils/transformers/convert_dinov2.py +1 -0
  25. keras_hub/src/utils/transformers/convert_qwen3_moe.py +216 -0
  26. keras_hub/src/utils/transformers/preset_loader.py +3 -0
  27. keras_hub/src/version.py +1 -1
  28. keras_hub/tokenizers/__init__.py +3 -0
  29. {keras_hub_nightly-0.23.0.dev202509180413.dist-info → keras_hub_nightly-0.23.0.dev202509280419.dist-info}/METADATA +1 -1
  30. {keras_hub_nightly-0.23.0.dev202509180413.dist-info → keras_hub_nightly-0.23.0.dev202509280419.dist-info}/RECORD +32 -13
  31. {keras_hub_nightly-0.23.0.dev202509180413.dist-info → keras_hub_nightly-0.23.0.dev202509280419.dist-info}/WHEEL +0 -0
  32. {keras_hub_nightly-0.23.0.dev202509180413.dist-info → keras_hub_nightly-0.23.0.dev202509280419.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,357 @@
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.qwen3_moe.qwen3_moe_backbone import Qwen3MoeBackbone
7
+ from keras_hub.src.models.qwen3_moe.qwen3_moe_causal_lm_preprocessor import (
8
+ Qwen3MoeCausalLMPreprocessor,
9
+ )
10
+ from keras_hub.src.utils.tensor_utils import any_equal
11
+
12
+
13
+ @keras_hub_export(
14
+ "keras_hub.models.Qwen3MoeCausalLM",
15
+ )
16
+ class Qwen3MoeCausalLM(CausalLM):
17
+ """An end-to-end Qwen3 MoE model for causal language modeling.
18
+
19
+ A causal language model (LM) predicts the next token based on previous
20
+ tokens. This task setup can be used to train the model unsupervised on plain
21
+ text input, or to autoregressively generate plain text similar to the data
22
+ used for training. This task can be used for pre-training or fine-tuning a
23
+ Qwen3 MoE model, simply by calling `fit()`.
24
+
25
+ This model has a `generate()` method, which generates text based on a
26
+ prompt. The generation strategy used is controlled by an additional
27
+ `sampler` argument on `compile()`. You can recompile the model with
28
+ different `keras_hub.samplers` objects to control the generation.
29
+ By default, `"greedy"` sampling will be used.
30
+
31
+ This model can optionally be configured with a `preprocessor` layer, in
32
+ which case it will automatically apply preprocessing to string inputs during
33
+ `fit()`, `predict()`, `evaluate()`, and `generate()`. This is done by
34
+ default when creating the model with `from_preset()`.
35
+
36
+ The Qwen3 MoE architecture leverages a Mixture of Experts (MoE) design,
37
+ where each transformer layer uses a sparse set of experts to process tokens
38
+ efficiently, making it suitable for large-scale language tasks with
39
+ optimized computational resources.
40
+
41
+ Args:
42
+ backbone: A `keras_hub.models.Qwen3MoeBackbone` instance.
43
+ preprocessor: A `keras_hub.models.Qwen3MoeCausalLMPreprocessor` or
44
+ `None`. If `None`, this model will not apply preprocessing, and
45
+ inputs should be preprocessed before calling the model.
46
+
47
+ Examples:
48
+
49
+ Use `generate()` to do text generation.
50
+ ```python
51
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
52
+ "qwen3_moe_3b_en"
53
+ )
54
+ qwen3_moe_lm.generate("I want to say", max_length=30)
55
+
56
+ # Generate with batched prompts.
57
+ qwen3_moe_lm.generate(["This is a", "Where are you"], max_length=30)
58
+ ```
59
+
60
+ Compile the `generate()` function with a custom sampler.
61
+ ```python
62
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
63
+ "qwen3_moe_3b_en"
64
+ )
65
+ qwen3_moe_lm.compile(sampler="top_k")
66
+ qwen3_moe_lm.generate("I want to say", max_length=30)
67
+
68
+ qwen3_moe_lm.compile(sampler=keras_hub.samplers.BeamSampler(num_beams=2))
69
+ qwen3_moe_lm.generate("I want to say", max_length=30)
70
+ ```
71
+
72
+ Use `generate()` without preprocessing.
73
+ ```python
74
+ prompt = {
75
+ # Token ids for "<bos> Qwen3 is".
76
+ "token_ids": np.array([[2, 12345, 678, 0, 0, 0, 0]] * 2),
77
+ # Use `"padding_mask"` to indicate values that should not be overridden.
78
+ "padding_mask": np.array([[1, 1, 1, 0, 0, 0, 0]] * 2),
79
+ }
80
+
81
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
82
+ "qwen3_moe_a2_7b",
83
+ preprocessor=None,
84
+ )
85
+ qwen3_moe_lm.generate(prompt)
86
+ ```
87
+
88
+ Call `fit()` on a single batch.
89
+ ```python
90
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
91
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
92
+ "qwen3_moe_3b_en"
93
+ )
94
+ qwen3_moe_lm.fit(x=features, batch_size=2)
95
+ ```
96
+
97
+ Call `fit()` with LoRA fine-tuning enabled.
98
+ ```python
99
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
100
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
101
+ "qwen3_moe_3b_en"
102
+ )
103
+ qwen3_moe_lm.backbone.enable_lora(rank=4)
104
+ qwen3_moe_lm.fit(x=features, batch_size=2)
105
+ ```
106
+
107
+ Call `fit()` without preprocessing.
108
+ ```python
109
+ x = {
110
+ # Token ids for "<bos> Qwen3 is a language model<eos>"
111
+ "token_ids": np.array([[2, 12345, 678, 543, 9876, 1, 0, 0]] * 2),
112
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 0, 0]] * 2),
113
+ }
114
+ y = np.array([[12345, 678, 543, 9876, 1, 0, 0, 0]] * 2)
115
+ sw = np.array([[1, 1, 1, 1, 1, 0, 0, 0]] * 2)
116
+
117
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset(
118
+ "qwen3_moe_a2_7b",
119
+ preprocessor=None,
120
+ )
121
+ qwen3_moe_lm.fit(x=x, y=y, sample_weight=sw, batch_size=2)
122
+ ```
123
+
124
+ Custom backbone and vocabulary.
125
+ ```python
126
+ tokenizer = keras_hub.models.Qwen3MoeTokenizer(
127
+ proto="qwen3_moe_vocab.spm",
128
+ )
129
+ preprocessor = keras_hub.models.Qwen3MoeCausalLMPreprocessor(
130
+ tokenizer=tokenizer,
131
+ sequence_length=128,
132
+ )
133
+ backbone = keras_hub.models.Qwen3MoeBackbone(
134
+ vocabulary_size=151936,
135
+ num_layers=28,
136
+ num_query_heads=16,
137
+ num_key_value_heads=8,
138
+ hidden_dim=2048,
139
+ intermediate_dim=4096,
140
+ moe_intermediate_dim=128,
141
+ num_experts=60,
142
+ top_k=4,
143
+ max_sequence_length=4096,
144
+ )
145
+ qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM(
146
+ backbone=backbone,
147
+ preprocessor=preprocessor,
148
+ )
149
+ qwen3_moe_lm.fit(x=features, batch_size=2)
150
+ ```
151
+ """
152
+
153
+ backbone_cls = Qwen3MoeBackbone
154
+ preprocessor_cls = Qwen3MoeCausalLMPreprocessor
155
+
156
+ def __init__(self, backbone, preprocessor=None, **kwargs):
157
+ # === Layers ===
158
+ self.backbone = backbone
159
+ self.preprocessor = preprocessor
160
+
161
+ # === Functional Model ===
162
+ # This must be "backbone.input" i.e. the full input structure,
163
+ # rather than "backbone.inputs" which is the flattened list of inputs.
164
+ inputs = backbone.input
165
+ hidden_states = backbone(inputs)
166
+ outputs = backbone.token_embedding(hidden_states, reverse=True)
167
+ super().__init__(
168
+ inputs=inputs,
169
+ outputs=outputs,
170
+ **kwargs,
171
+ )
172
+
173
+ def call_with_cache(
174
+ self,
175
+ token_ids,
176
+ cache,
177
+ cache_update_index,
178
+ ):
179
+ """Forward pass of `Qwen3MoeCausalLM` with cache.
180
+
181
+ `call_with_cache` adds an additional forward pass for the model for
182
+ autoregressive inference. Unlike calling the model directly, this method
183
+ allows caching previous key/value Tensors in multi-head attention layer,
184
+ and avoids recomputing the outputs of seen tokens.
185
+
186
+ Args:
187
+ token_ids: a dense int Tensor with shape `(batch_size, max_length)`.
188
+ cache: a dense float Tensor, the cache of key and value.
189
+ cache_update_index: int, or int Tensor. The index of current inputs
190
+ in the whole sequence.
191
+
192
+ Returns:
193
+ A (logits, hidden_states, cache) tuple. Where `logits` is the
194
+ language model logits for the input token_ids, `hidden_states` is
195
+ the final hidden representation of the input tokens, and `cache` is
196
+ the decoding cache.
197
+ """
198
+ x = self.backbone.token_embedding(token_ids)
199
+ # Each decoder layer has a cache; we update them separately.
200
+ updated_cache = []
201
+ for i in range(self.backbone.num_layers):
202
+ current_cache = cache[:, i, ...]
203
+ x, next_cache = self.backbone.transformer_layers[i](
204
+ x,
205
+ self_attention_cache=current_cache,
206
+ self_attention_cache_update_index=cache_update_index,
207
+ )
208
+ updated_cache.append(next_cache)
209
+ cache = ops.stack(updated_cache, axis=1)
210
+ hidden_states = x = self.backbone.layer_norm(x)
211
+ logits = self.backbone.token_embedding(x, reverse=True)
212
+ return logits, hidden_states, cache
213
+
214
+ def _build_cache(self, token_ids):
215
+ """Build an empty cache for use with `call_with_cache()`."""
216
+ batch_size = ops.shape(token_ids)[0]
217
+ max_length = ops.shape(token_ids)[1]
218
+ num_layers = self.backbone.num_layers
219
+ num_key_value_heads = self.backbone.num_key_value_heads
220
+ head_dim = self.backbone.head_dim
221
+ shape = [
222
+ batch_size,
223
+ num_layers,
224
+ 2,
225
+ max_length,
226
+ num_key_value_heads,
227
+ head_dim,
228
+ ]
229
+ cache = ops.zeros(shape, dtype=self.compute_dtype)
230
+ # Seed the cache.
231
+ _, hidden_states, cache = self.call_with_cache(token_ids, cache, 0)
232
+ return hidden_states, cache
233
+
234
+ def generate_step(
235
+ self,
236
+ inputs,
237
+ stop_token_ids=None,
238
+ ):
239
+ """A compilable generation function for a single batch of inputs.
240
+
241
+ This function represents the inner, XLA-compilable, generation function
242
+ for a single batch of inputs. Inputs should have the same structure as
243
+ model inputs, a dictionary with keys `"token_ids"` and `"padding_mask"`.
244
+
245
+ Args:
246
+ inputs: A dictionary with two keys `"token_ids"` and
247
+ `"padding_mask"` and batched tensor values.
248
+ stop_token_ids: Tuple of id's of the end token to stop on. If all
249
+ sequences have produced a new stop token, generation
250
+ will stop.
251
+ """
252
+ token_ids, padding_mask = inputs["token_ids"], inputs["padding_mask"]
253
+ # Create and seed cache with a single forward pass.
254
+ hidden_states, cache = self._build_cache(token_ids)
255
+ # Compute the lengths of all user inputted tokens ids.
256
+ row_lengths = ops.sum(ops.cast(padding_mask, "int32"), axis=-1)
257
+ # Start at the first index that has no user inputted id.
258
+ index = ops.min(row_lengths)
259
+
260
+ def next(prompt, cache, index):
261
+ # The cache index is the index of our previous token.
262
+ cache_update_index = index - 1
263
+ batch_size = ops.shape(prompt)[0]
264
+ prompt = ops.slice(prompt, [0, cache_update_index], [batch_size, 1])
265
+ logits, hidden_states, cache = self.call_with_cache(
266
+ prompt,
267
+ cache,
268
+ cache_update_index,
269
+ )
270
+ return (
271
+ ops.squeeze(logits, axis=1),
272
+ ops.squeeze(hidden_states, axis=1),
273
+ cache,
274
+ )
275
+
276
+ token_ids = self.sampler(
277
+ next=next,
278
+ prompt=token_ids,
279
+ cache=cache,
280
+ index=index,
281
+ mask=padding_mask,
282
+ stop_token_ids=stop_token_ids,
283
+ hidden_states=hidden_states,
284
+ model=self,
285
+ )
286
+
287
+ # Compute an output padding mask with the token ids we updated.
288
+ if stop_token_ids is not None:
289
+ # Build a mask of stop token locations not in the original
290
+ # prompt (not in locations where `padding_mask` is True).
291
+ end_locations = any_equal(
292
+ token_ids, stop_token_ids, ops.logical_not(padding_mask)
293
+ )
294
+ end_locations = ops.cast(end_locations, "int32")
295
+ # Use cumsum to get ones in all locations after end_locations.
296
+ cumsum = ops.cast(ops.cumsum(end_locations, axis=-1), "int32")
297
+ overflow = cumsum - end_locations
298
+ # Our padding mask is the inverse of these overflow locations.
299
+ padding_mask = ops.logical_not(ops.cast(overflow, "bool"))
300
+ else:
301
+ # Without early stopping, all locations will have been updated.
302
+ padding_mask = ops.ones_like(token_ids, dtype="bool")
303
+ return {
304
+ "token_ids": token_ids,
305
+ "padding_mask": padding_mask,
306
+ }
307
+
308
+ def score(
309
+ self,
310
+ token_ids,
311
+ padding_mask=None,
312
+ scoring_mode="logits",
313
+ layer_intercept_fn=None,
314
+ target_ids=None,
315
+ ):
316
+ if scoring_mode not in ("logits", "loss"):
317
+ raise ValueError(
318
+ "Unsupported scoring_mode. Must be one of 'logits' or 'loss'."
319
+ )
320
+
321
+ if scoring_mode == "loss" and target_ids is None:
322
+ raise ValueError(
323
+ "Cannot compute loss without targets. Please provide target "
324
+ "token ids via the target_ids parameter."
325
+ )
326
+
327
+ batch_shape = ops.shape(token_ids)[:2]
328
+ assert len(batch_shape) == 2
329
+
330
+ if padding_mask is None:
331
+ padding_mask = ops.ones(shape=batch_shape)
332
+
333
+ if layer_intercept_fn is None:
334
+
335
+ def default_layer_intercept_fn(x, unused_i):
336
+ return x
337
+
338
+ layer_intercept_fn = default_layer_intercept_fn
339
+
340
+ token_embeddings = self.backbone.token_embedding(token_ids)
341
+ x = layer_intercept_fn(token_embeddings, -1)
342
+
343
+ for i, transformer_layer in enumerate(self.backbone.transformer_layers):
344
+ x = transformer_layer(x, decoder_padding_mask=padding_mask)
345
+ x = layer_intercept_fn(x, i)
346
+
347
+ x = self.backbone.layer_norm(x)
348
+ logits = self.backbone.token_embedding(x, reverse=True)
349
+
350
+ if scoring_mode == "logits":
351
+ return logits
352
+
353
+ per_token_loss_fn = keras.losses.SparseCategoricalCrossentropy(
354
+ from_logits=True, reduction="none"
355
+ )
356
+ per_token_loss = per_token_loss_fn(target_ids, logits)
357
+ return per_token_loss
@@ -0,0 +1,12 @@
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.qwen3_moe.qwen3_moe_backbone import Qwen3MoeBackbone
4
+ from keras_hub.src.models.qwen3_moe.qwen3_moe_tokenizer import Qwen3MoeTokenizer
5
+
6
+
7
+ @keras_hub_export(
8
+ "keras_hub.models.Qwen3MoeCausalLMPreprocessor",
9
+ )
10
+ class Qwen3MoeCausalLMPreprocessor(CausalLMPreprocessor):
11
+ backbone_cls = Qwen3MoeBackbone
12
+ tokenizer_cls = Qwen3MoeTokenizer