keras-hub-nightly 0.20.0.dev202504010407__py3-none-any.whl → 0.20.0.dev202504020401__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.
@@ -323,6 +323,24 @@ from keras_hub.src.models.roberta.roberta_text_classifier_preprocessor import (
323
323
  RobertaTextClassifierPreprocessor as RobertaPreprocessor,
324
324
  )
325
325
  from keras_hub.src.models.roberta.roberta_tokenizer import RobertaTokenizer
326
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
327
+ RoformerV2Backbone as RorformerV2Backbone,
328
+ )
329
+ from keras_hub.src.models.roformer_v2.roformer_v2_masked_lm import (
330
+ RoformerV2MaskedLM,
331
+ )
332
+ from keras_hub.src.models.roformer_v2.roformer_v2_masked_lm_preprocessor import (
333
+ RoformerV2MaskedLMPreprocessor,
334
+ )
335
+ from keras_hub.src.models.roformer_v2.roformer_v2_text_classifier import (
336
+ RorformerV2TextClassifier,
337
+ )
338
+ from keras_hub.src.models.roformer_v2.roformer_v2_text_classifier_preprocessor import (
339
+ RoformerV2TextClassifierPreprocessor,
340
+ )
341
+ from keras_hub.src.models.roformer_v2.roformer_v2_tokenizer import (
342
+ RoformerV2Tokenizer,
343
+ )
326
344
  from keras_hub.src.models.sam.sam_backbone import SAMBackbone
327
345
  from keras_hub.src.models.sam.sam_image_segmenter import SAMImageSegmenter
328
346
  from keras_hub.src.models.sam.sam_image_segmenter_preprocessor import (
@@ -35,6 +35,9 @@ from keras_hub.src.models.qwen.qwen_tokenizer import (
35
35
  QwenTokenizer as Qwen2Tokenizer,
36
36
  )
37
37
  from keras_hub.src.models.roberta.roberta_tokenizer import RobertaTokenizer
38
+ from keras_hub.src.models.roformer_v2.roformer_v2_tokenizer import (
39
+ RoformerV2Tokenizer,
40
+ )
38
41
  from keras_hub.src.models.siglip.siglip_tokenizer import SigLIPTokenizer
39
42
  from keras_hub.src.models.t5.t5_tokenizer import T5Tokenizer
40
43
  from keras_hub.src.models.whisper.whisper_tokenizer import WhisperTokenizer
@@ -133,6 +133,13 @@ class CachedGemmaAttention(keras.layers.Layer):
133
133
  query_normalization = 1 / np.sqrt(
134
134
  self.hidden_dim // self.num_query_heads
135
135
  )
136
+
137
+ if self.use_sliding_window_attention and attention_mask is not None:
138
+ attention_mask = self._mask_sliding_window(
139
+ attention_mask,
140
+ cache_update_index=cache_update_index,
141
+ )
142
+
136
143
  if self._can_use_flash_attention():
137
144
  if attention_mask is not None:
138
145
  attention_mask = ops.expand_dims(attention_mask, axis=1)
@@ -172,13 +179,8 @@ class CachedGemmaAttention(keras.layers.Layer):
172
179
  ops.tanh(attention_logits), self.logit_soft_cap
173
180
  )
174
181
 
175
- if self.use_sliding_window_attention:
176
- attention_mask = self._mask_sliding_window(
177
- attention_mask,
178
- cache_update_index=cache_update_index,
179
- )
180
-
181
- attention_mask = attention_mask[:, None, None, :, :]
182
+ if attention_mask is not None:
183
+ attention_mask = attention_mask[:, None, None, :, :]
182
184
  orig_dtype = attention_logits.dtype
183
185
  attention_softmax = self.softmax(attention_logits, mask=attention_mask)
184
186
  attention_softmax = ops.cast(attention_softmax, orig_dtype)
File without changes
@@ -0,0 +1,212 @@
1
+ import keras
2
+ from keras import initializers
3
+ from keras import ops
4
+
5
+
6
+ class RoformerNorm(keras.layers.Layer):
7
+ """A normalization layer for Roformer that implements RMS normalization."""
8
+
9
+ def __init__(self, epsilon=1e-6, **kwargs):
10
+ super().__init__(**kwargs)
11
+ self.epsilon = epsilon
12
+
13
+ def build(self, input_shape):
14
+ dim = input_shape[-1]
15
+ self.scale = self.add_weight(
16
+ name="scale",
17
+ trainable=True,
18
+ shape=(dim,),
19
+ initializer="ones",
20
+ dtype=self.variable_dtype,
21
+ )
22
+ self.built = True
23
+
24
+ def call(self, x):
25
+ x = ops.cast(x, "float32")
26
+ var = ops.mean(ops.power(x, 2), axis=-1, keepdims=True)
27
+ x = x * ops.rsqrt(var + self.epsilon)
28
+ return ops.cast(x * self.scale, self.compute_dtype)
29
+
30
+ def get_config(self):
31
+ config = super().get_config()
32
+ config.update({"epsilon": self.epsilon})
33
+ return config
34
+
35
+
36
+ class RoformrPositionalEmbedding(keras.layers.Layer):
37
+ """Native rotary implement by jianlin su
38
+ from native implement
39
+ https://github.com/bojone/bert4keras
40
+
41
+ """
42
+
43
+ def __init__(self, output_dim, max_wavelength=10000, **kwargs):
44
+ super().__init__(**kwargs)
45
+ self.max_wavelength = max_wavelength
46
+ self.output_dim = output_dim
47
+
48
+ def call(self, tensors):
49
+ input_shape = ops.shape(tensors[0])
50
+ seq_len = input_shape[1]
51
+ position_ids = ops.arange(0, seq_len, dtype=tensors[0].dtype)[None]
52
+ embeddings = self.sinusoidal_embeddings(
53
+ position_ids, self.output_dim, self.max_wavelength
54
+ )
55
+ embeddings = ops.cast(embeddings, self.compute_dtype)
56
+
57
+ ndim = ops.ndim(tensors[0])
58
+ sinusoidal = self.align(embeddings, [0, 1, -1], ndim)
59
+ cos_pos = ops.repeat(sinusoidal[..., 1::2], 2, -1)
60
+ sin_pos = ops.repeat(sinusoidal[..., ::2], 2, -1)
61
+ outputs = []
62
+ for tensor in tensors:
63
+ tensor2 = ops.stack([-tensor[..., 1::2], tensor[..., ::2]], ndim)
64
+ tensor2 = ops.reshape(tensor2, ops.shape(tensor))
65
+ outputs.append(tensor * cos_pos + tensor2 * sin_pos)
66
+ return outputs[0] if len(outputs) == 1 else outputs
67
+
68
+ def align(self, tensor, axes, ndim=None):
69
+ ndim = ndim or max(axes) + 1
70
+ indices = [None] * ndim
71
+ for i in axes:
72
+ indices[i] = slice(None)
73
+ if keras.config.backend() == "jax":
74
+ return tensor[tuple(indices)]
75
+ return tensor[indices]
76
+
77
+ def sinusoidal_embeddings(self, pos, dim, base=10000):
78
+ if dim % 2 != 0:
79
+ raise ("Dimension must be even")
80
+
81
+ indices = ops.arange(0, dim // 2, dtype="float32")
82
+ indices = ops.power(ops.cast(base, dtype="float32"), -2 * indices / dim)
83
+ embeddings = ops.einsum("...,d->...d", pos, indices)
84
+ embeddings = ops.stack(
85
+ [ops.sin(embeddings), ops.cos(embeddings)], axis=-1
86
+ )
87
+ shape = list(ops.shape(embeddings))
88
+ embeddings = ops.reshape(embeddings, shape[:-2] + [-1])
89
+ return embeddings
90
+
91
+ def get_config(self):
92
+ config = super().get_config()
93
+ config.update(
94
+ {
95
+ "out_dim": self.out_dim,
96
+ "max_wavelength": self.max_wavelength,
97
+ }
98
+ )
99
+ return config
100
+
101
+
102
+ @keras.saving.register_keras_serializable(package="keras_hub")
103
+ class RoformerAttention(keras.layers.Layer):
104
+ """MultiHeadAttention by roformerV2
105
+
106
+ modifity from native implement
107
+ https://github.com/bojone/bert4keras
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ heads,
113
+ head_size,
114
+ out_dim=None,
115
+ use_bias=False,
116
+ max_wavelength=10000,
117
+ kernel_initializer="glorot_uniform",
118
+ **kwargs,
119
+ ):
120
+ super().__init__(**kwargs)
121
+ self.heads = heads
122
+ self.head_size = head_size
123
+ self.out_dim = out_dim or heads * head_size
124
+ self.use_bias = use_bias
125
+ self.kernel_initializer = initializers.get(kernel_initializer)
126
+ self.max_wavelength = max_wavelength
127
+
128
+ def build(self, input_shape):
129
+ super().build(input_shape)
130
+ self.q_dense = keras.layers.Dense(
131
+ units=self.head_size * self.heads,
132
+ use_bias=self.use_bias,
133
+ kernel_initializer=self.kernel_initializer,
134
+ name="q_dense_layer",
135
+ dtype=self.dtype_policy,
136
+ )
137
+ self.q_dense.build(input_shape)
138
+
139
+ self.k_dense = keras.layers.Dense(
140
+ units=self.head_size * self.heads,
141
+ use_bias=self.use_bias,
142
+ kernel_initializer=self.kernel_initializer,
143
+ name="k_dense_layer",
144
+ dtype=self.dtype_policy,
145
+ )
146
+ self.k_dense.build(input_shape)
147
+
148
+ self.v_dense = keras.layers.Dense(
149
+ units=self.head_size * self.heads,
150
+ use_bias=self.use_bias,
151
+ kernel_initializer=self.kernel_initializer,
152
+ name="v_dense_layer",
153
+ dtype=self.dtype_policy,
154
+ )
155
+ self.v_dense.build(input_shape)
156
+
157
+ self.o_dense = keras.layers.Dense(
158
+ units=self.out_dim,
159
+ use_bias=self.use_bias,
160
+ kernel_initializer=self.kernel_initializer,
161
+ name="o_dense_layer",
162
+ dtype=self.dtype_policy,
163
+ )
164
+ self.o_dense.build([None, None, self.head_size * self.heads])
165
+
166
+ self.rotary_embedding_layer = RoformrPositionalEmbedding(
167
+ self.head_size, self.max_wavelength, dtype=self.dtype_policy
168
+ )
169
+ self.rotary_embedding_layer.build([])
170
+
171
+ def call(self, x, attention_mask=None):
172
+ qw = self.q_dense(x)
173
+ kw = self.k_dense(x)
174
+ vw = self.v_dense(x)
175
+
176
+ b, s = ops.shape(qw)[:2]
177
+ qw = ops.reshape(qw, (b, s, self.heads, self.head_size))
178
+ kw = ops.reshape(kw, (b, s, self.heads, self.head_size))
179
+ vw = ops.reshape(vw, (b, s, self.heads, self.head_size))
180
+
181
+ qw, kw = self.rotary_embedding_layer([qw, kw])
182
+ if keras.__version__ < "3.6":
183
+ raise ("Please make sure your Keras version is >=3.6.")
184
+ flash_attention = keras.config.is_flash_attention_enabled()
185
+ attention_mask = ops.reshape(attention_mask, [b, 1, s, 1])
186
+ if keras.config.backend() == "torch":
187
+ attention_mask = ops.repeat(attention_mask, s, -1)
188
+ attention_mask = ops.transpose(attention_mask, [0, 1, 3, 2])
189
+ o = ops.dot_product_attention(
190
+ qw, kw, vw, mask=attention_mask, flash_attention=flash_attention
191
+ )
192
+
193
+ return self.o_dense(ops.reshape(o, [b, s, -1]))
194
+
195
+ def compute_output_shape(self, input_shape):
196
+ return input_shape
197
+
198
+ def get_config(self):
199
+ config = super().get_config()
200
+ config.update(
201
+ {
202
+ "heads": self.heads,
203
+ "head_size": self.head_size,
204
+ "out_dim": self.out_dim,
205
+ "use_bias": self.use_bias,
206
+ "max_wavelength": self.max_wavelength,
207
+ "kernel_initializer": initializers.serialize(
208
+ self.kernel_initializer
209
+ ),
210
+ }
211
+ )
212
+ return config
@@ -0,0 +1,198 @@
1
+ import keras
2
+ from keras import activations
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.roformer_v2.roformer_v2_attention import RoformerNorm
10
+ from keras_hub.src.models.roformer_v2.roformer_v2_encoder import (
11
+ RoformerV2Encoder,
12
+ )
13
+
14
+
15
+ def roformer_kernel_initializer(stddev=0.02):
16
+ return keras.initializers.TruncatedNormal(stddev=stddev)
17
+
18
+
19
+ @keras_hub_export("keras_hub.models.RorformerV2Backbone")
20
+ class RoformerV2Backbone(Backbone):
21
+ """A RoformerV2 encoder network.
22
+
23
+ This class implements a bi-directional Transformer-based encoder as
24
+ described in ["Roformer"](https://github.com/ZhuiyiTechnology/roformer).
25
+ It includes the
26
+ embedding lookups and transformer layers, but not the masked language model
27
+ or next sentence prediction heads.
28
+
29
+ The default constructor gives a fully customizable, randomly initialized
30
+ RoformerV2 encoder with any number of layers, heads, and embed dim.To
31
+ load preset architectures and weights, use the `from_preset()` constructor.
32
+
33
+ Disclaimer: Pre-trained models are provided on an "as is" basis, without
34
+ warranties or conditions of any kind.
35
+
36
+ Args:
37
+ vocabulary_size: int. The size of the token vocabulary.
38
+ num_layers: int. The number of transformer layers.
39
+ num_heads: int. The number of attention heads for each transformer.
40
+ The hidden size must be divisible by the number of attention heads.
41
+ hidden_dim: int. The size of the transformer encoding and pooler layers.
42
+ intermediate_dim: int. The output dimension of the first Dense layer in
43
+ a two-layer feedforward network for each transformer.
44
+ dropout: float. Dropout probability for the Transformer encoder.
45
+ num_segments: int. The number of types that the 'segment_ids' input can
46
+ take.
47
+ dtype: string or `keras.mixed_precision.DTypePolicy`. The dtype to use
48
+ for model computations and weights. Note that some computations,
49
+ such as softmax and layer normalization, will always be done at
50
+ float32 precision regardless of dtype.
51
+
52
+ Examples:
53
+ ```python
54
+ input_data = {
55
+ "token_ids": np.ones(shape=(1, 12), dtype="int32"),
56
+ "segment_ids": np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0]]),
57
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]),
58
+ }
59
+
60
+ # Pretrained RoformerV2 encoder.
61
+ model = keras_hub.models.RoformerV2Backbone.from_preset("roformer_v2_base")
62
+ model(input_data)
63
+
64
+ # Randomly initialized RoformerV2 encoder with a custom config.
65
+ model = keras_hub.models.RoformerV2Backbone(
66
+ vocabulary_size=30552,
67
+ num_layers=4,
68
+ num_heads=4,
69
+ hidden_dim=256,
70
+ intermediate_dim=512,
71
+ head_size = 64,
72
+ )
73
+ model(input_data)
74
+ ```
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ vocabulary_size,
80
+ num_layers,
81
+ num_heads,
82
+ hidden_dim,
83
+ intermediate_dim,
84
+ head_size,
85
+ use_bias=False,
86
+ activation="relu",
87
+ dropout=0.1,
88
+ num_segments=2,
89
+ dtype=None,
90
+ max_wavelength=10000,
91
+ **kwargs,
92
+ ):
93
+ # === Layers ===
94
+ self.token_embedding = ReversibleEmbedding(
95
+ input_dim=vocabulary_size,
96
+ output_dim=hidden_dim,
97
+ embeddings_initializer=roformer_kernel_initializer(),
98
+ dtype=dtype,
99
+ name="token_embedding",
100
+ )
101
+ self.segment_embedding = keras.layers.Embedding(
102
+ input_dim=num_segments,
103
+ output_dim=hidden_dim,
104
+ embeddings_initializer=roformer_kernel_initializer(),
105
+ dtype=dtype,
106
+ name="segment_embedding",
107
+ )
108
+ self.embeddings_add = keras.layers.Add(
109
+ dtype=dtype,
110
+ name="embeddings_add",
111
+ )
112
+ self.embeddings_layer_norm = RoformerNorm(
113
+ epsilon=keras.backend.epsilon(),
114
+ dtype=dtype,
115
+ name="embeddings_layer_norm",
116
+ )
117
+ self.embeddings_dropout = keras.layers.Dropout(
118
+ dropout,
119
+ dtype=dtype,
120
+ name="embeddings_dropout",
121
+ )
122
+ self.transformer_layers = []
123
+ for i in range(num_layers):
124
+ layer = RoformerV2Encoder(
125
+ heads=num_heads,
126
+ head_size=head_size,
127
+ intermediate_size=intermediate_dim,
128
+ use_bias=use_bias,
129
+ max_wavelength=max_wavelength,
130
+ dropout=dropout,
131
+ activation=activation,
132
+ kernel_initializer=roformer_kernel_initializer(),
133
+ dtype=dtype,
134
+ name=f"transformer_layer_{i}",
135
+ )
136
+ self.transformer_layers.append(layer)
137
+
138
+ # === Functional Model ===
139
+ token_id_input = keras.Input(
140
+ shape=(None,), dtype="int32", name="token_ids"
141
+ )
142
+ segment_id_input = keras.Input(
143
+ shape=(None,), dtype="int32", name="segment_ids"
144
+ )
145
+ attention_mask = keras.ops.not_equal(token_id_input, 0)
146
+ # Embed tokens, positions, and segment ids.
147
+ tokens = self.token_embedding(token_id_input)
148
+ segments = self.segment_embedding(segment_id_input)
149
+ # Sum, normalize and apply dropout to embeddings.
150
+ x = self.embeddings_add((tokens, segments))
151
+ x = self.embeddings_layer_norm(x)
152
+ x = self.embeddings_dropout(x)
153
+ for transformer_layer in self.transformer_layers:
154
+ x = transformer_layer(x, attention_mask=attention_mask)
155
+
156
+ super().__init__(
157
+ inputs={
158
+ "token_ids": token_id_input,
159
+ "segment_ids": segment_id_input,
160
+ },
161
+ outputs=x,
162
+ dtype=dtype,
163
+ **kwargs,
164
+ )
165
+
166
+ # === Config ===
167
+ self.vocabulary_size = vocabulary_size
168
+ self.num_layers = num_layers
169
+ self.num_heads = num_heads
170
+ self.hidden_dim = hidden_dim
171
+ self.intermediate_dim = intermediate_dim
172
+ self.dropout = dropout
173
+ self.num_segments = num_segments
174
+ self.max_wavelength = max_wavelength
175
+ self.head_size = head_size
176
+ self.dropout = dropout
177
+ self.activation = activations.get(activation)
178
+ self.use_bias = use_bias
179
+ self.start_token_index = 0
180
+
181
+ def get_config(self):
182
+ config = super().get_config()
183
+ config.update(
184
+ {
185
+ "vocabulary_size": self.vocabulary_size,
186
+ "num_layers": self.num_layers,
187
+ "num_heads": self.num_heads,
188
+ "hidden_dim": self.hidden_dim,
189
+ "intermediate_dim": self.intermediate_dim,
190
+ "dropout": self.dropout,
191
+ "num_segments": self.num_segments,
192
+ "max_wavelength": self.max_wavelength,
193
+ "head_size": self.head_size,
194
+ "use_bias": self.use_bias,
195
+ "activation": activations.serialize(self.activation),
196
+ }
197
+ )
198
+ return config
@@ -0,0 +1,128 @@
1
+ import keras
2
+ from keras import activations
3
+ from keras import initializers
4
+
5
+ from keras_hub.src.models.roformer_v2.roformer_v2_attention import (
6
+ RoformerAttention,
7
+ )
8
+ from keras_hub.src.models.roformer_v2.roformer_v2_attention import RoformerNorm
9
+
10
+
11
+ @keras.saving.register_keras_serializable(package="keras_hub")
12
+ class RoformerV2Encoder(keras.layers.Layer):
13
+ """A Transformer Encoder layer for the Roformer backbone."""
14
+
15
+ def __init__(
16
+ self,
17
+ heads,
18
+ head_size,
19
+ intermediate_size=None,
20
+ max_wavelength=10000,
21
+ dropout=0,
22
+ activation="relu",
23
+ use_bias=False,
24
+ kernel_initializer="glorot_uniform",
25
+ **kwargs,
26
+ ):
27
+ super().__init__(**kwargs)
28
+ self.heads = heads
29
+ self.head_size = head_size
30
+ self.intermediate_size = intermediate_size
31
+ self.use_bias = use_bias
32
+ self.kernel_initializer = initializers.get(kernel_initializer)
33
+ self.max_wavelength = max_wavelength
34
+ self.dropout = dropout
35
+ self.activation = activations.get(activation)
36
+
37
+ def build(self, input_shape):
38
+ super().build(input_shape)
39
+ self.attention_layer = RoformerAttention(
40
+ heads=self.heads,
41
+ head_size=self.head_size,
42
+ use_bias=self.use_bias,
43
+ max_wavelength=self.max_wavelength,
44
+ kernel_initializer=self.kernel_initializer,
45
+ dtype=self.dtype_policy,
46
+ name="attention_layer",
47
+ )
48
+ self.attention_layer.build(input_shape)
49
+
50
+ self.dropout_layer = keras.layers.Dropout(
51
+ rate=self.dropout,
52
+ dtype=self.dtype_policy,
53
+ name="self_attention_dropout",
54
+ )
55
+ self.dropout_layer.build([])
56
+
57
+ # Feedforward layers.
58
+ self.feedforward_intermediate_dense = keras.layers.Dense(
59
+ self.intermediate_size,
60
+ kernel_initializer=self.kernel_initializer,
61
+ use_bias=self.use_bias,
62
+ dtype=self.dtype_policy,
63
+ activation=self.activation,
64
+ name="feedforward_intermediate_dense",
65
+ )
66
+ self.feedforward_intermediate_dense.build(input_shape)
67
+
68
+ self.feedforward_output_dense = keras.layers.Dense(
69
+ input_shape[-1],
70
+ kernel_initializer=self.kernel_initializer,
71
+ use_bias=self.use_bias,
72
+ dtype=self.dtype_policy,
73
+ name="feedforward_output_dense",
74
+ )
75
+
76
+ self.feedforward_output_dense.build(
77
+ [None, None, self.intermediate_size]
78
+ )
79
+
80
+ self.attention_norm = RoformerNorm(
81
+ epsilon=keras.backend.epsilon(),
82
+ name="attention_norm",
83
+ dtype=self.dtype_policy,
84
+ )
85
+ self.attention_norm.build(input_shape)
86
+
87
+ self.feedforward_norm = RoformerNorm(
88
+ epsilon=keras.backend.epsilon(),
89
+ name="feedforward_norm",
90
+ dtype=self.dtype_policy,
91
+ )
92
+ self.feedforward_norm.build(input_shape)
93
+
94
+ def call(self, x, attention_mask=None):
95
+ attention_output = self.attention_layer(
96
+ x,
97
+ attention_mask=attention_mask,
98
+ )
99
+
100
+ residual = x + self.dropout_layer(attention_output)
101
+ x = self.attention_norm(residual)
102
+
103
+ intermediate_output = self.feedforward_intermediate_dense(x)
104
+ feedroward_output = self.feedforward_output_dense(intermediate_output)
105
+
106
+ residual = x + self.dropout_layer(feedroward_output)
107
+ return self.feedforward_norm(residual)
108
+
109
+ def compute_output_shape(self, input_shape):
110
+ return input_shape
111
+
112
+ def get_config(self):
113
+ config = super().get_config()
114
+ config.update(
115
+ {
116
+ "heads": self.heads,
117
+ "head_size": self.head_size,
118
+ "intermediate_size": self.intermediate_size,
119
+ "max_wavelength": self.max_wavelength,
120
+ "use_bias": self.use_bias,
121
+ "activation": activations.serialize(self.activation),
122
+ "dropout": self.dropout,
123
+ "kernel_initializer": initializers.serialize(
124
+ self.kernel_initializer
125
+ ),
126
+ }
127
+ )
128
+ return config
@@ -0,0 +1,173 @@
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.masked_lm import MaskedLM
6
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
7
+ RoformerV2Backbone,
8
+ )
9
+ from keras_hub.src.models.roformer_v2.roformer_v2_masked_lm_preprocessor import ( # noqa: E501
10
+ RoformerV2MaskedLMPreprocessor,
11
+ )
12
+
13
+
14
+ class RoformerV2MaskedLMHead(keras.layers.Layer):
15
+ def __init__(
16
+ self,
17
+ vocabulary_size=None,
18
+ token_embedding=None,
19
+ activation=None,
20
+ **kwargs,
21
+ ):
22
+ super().__init__(**kwargs, autocast=False)
23
+
24
+ self.token_embedding = token_embedding
25
+ self.activation = keras.activations.get(activation)
26
+
27
+ if vocabulary_size and vocabulary_size != token_embedding.input_dim:
28
+ raise ValueError(
29
+ "`vocabulary_size` should match the input dimension of the "
30
+ "of `token_embedding`. Received: "
31
+ f"`vocabulary_size={vocabulary_size}`, "
32
+ f"`token_embedding.input_dim={token_embedding.input_dim}`"
33
+ )
34
+ self.vocabulary_size = token_embedding.input_dim
35
+
36
+ def call(self, inputs, mask_positions):
37
+ if keras.config.backend() == "tensorflow":
38
+ import tensorflow as tf
39
+
40
+ # On the tf backend, we need to work around an issue with dynamic
41
+ # shape broadcasting in take_along_axis.
42
+ x = tf.gather(inputs, mask_positions, batch_dims=1)
43
+ else:
44
+ # Gather the encoded tokens at the masked indices.
45
+ mask_positions = ops.expand_dims(mask_positions, axis=-1)
46
+ x = ops.take_along_axis(inputs, mask_positions, axis=1)
47
+
48
+ outputs = self.token_embedding(x, reverse=True)
49
+
50
+ # Apply a final activation.
51
+ if self.activation is not None:
52
+ outputs = self.activation(outputs)
53
+
54
+ outputs = ops.cast(outputs, "float32")
55
+ return outputs
56
+
57
+ def get_config(self):
58
+ config = super().get_config()
59
+ embedding_config = None
60
+ if self.token_embedding:
61
+ embedding_config = keras.layers.serialize(self.token_embedding)
62
+ config.update(
63
+ {
64
+ "token_embedding": embedding_config,
65
+ "vocabulary_size": self.vocabulary_size,
66
+ "activation": keras.activations.serialize(self.activation),
67
+ }
68
+ )
69
+ return config
70
+
71
+
72
+ @keras_hub_export("keras_hub.models.RoformerV2MaskedLM")
73
+ class RoformerV2MaskedLM(MaskedLM):
74
+ """An end-to-end Roformer model for the masked language modeling task.
75
+
76
+ This model will train RoformerV2 on a masked language modeling task.
77
+ The model will predict labels for a number of masked tokens in the
78
+ input data. For usage of this model with pre-trained weights, see the
79
+ `from_preset()` constructor.
80
+
81
+ This model can optionally be configured with a `preprocessor` layer, in
82
+ which case inputs can be raw string features during `fit()`, `predict()`,
83
+ and `evaluate()`. Inputs will be tokenized and dynamically masked during
84
+ training and evaluation. This is done by default when creating the model
85
+ with `from_preset()`.
86
+
87
+ Disclaimer: Pre-trained models are provided on an "as is" basis, without
88
+ warranties or conditions of any kind.
89
+
90
+ Args:
91
+ backbone: A `keras_hub.models.RoformerV2Backbone` instance.
92
+ preprocessor: A `keras_hub.models.RoformerV2MaskedLMPreprocessor` or
93
+ `None`. If `None`, this model will not apply preprocessing, and
94
+ inputs should be preprocessed before calling the model.
95
+
96
+ Examples:
97
+
98
+ Raw string data.
99
+ ```python
100
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
101
+
102
+ # Pretrained language model.
103
+ masked_lm = keras_hub.models.RoformerV2MaskedLM.from_preset(
104
+ "roformer_v2_base_zh",
105
+ )
106
+ masked_lm.fit(x=features, batch_size=2)
107
+
108
+ # Re-compile (e.g., with a new learning rate).
109
+ masked_lm.compile(
110
+ loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
111
+ optimizer=keras.optimizers.Adam(5e-5),
112
+ jit_compile=True,
113
+ )
114
+ # Access backbone programmatically (e.g., to change `trainable`).
115
+ masked_lm.backbone.trainable = False
116
+ # Fit again.
117
+ masked_lm.fit(x=features, batch_size=2)
118
+ ```
119
+
120
+ Preprocessed integer data.
121
+ ```python
122
+ # Create preprocessed batch where 0 is the mask token.
123
+ features = {
124
+ "token_ids": np.array([[1, 2, 0, 4, 0, 6, 7, 8]] * 2),
125
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1]] * 2),
126
+ "mask_positions": np.array([[2, 4]] * 2),
127
+ "segment_ids": np.array([[0, 0, 0, 0, 0, 0, 0, 0]] * 2)
128
+ }
129
+ # Labels are the original masked values.
130
+ labels = [[3, 5]] * 2
131
+
132
+ masked_lm = keras_hub.models.RoformerV2MaskedLM.from_preset(
133
+ "roformer_v2_base_zh",
134
+ preprocessor=None,
135
+ )
136
+ masked_lm.fit(x=features, y=labels, batch_size=2)
137
+ ```
138
+ """
139
+
140
+ backbone_cls = RoformerV2Backbone
141
+ preprocessor_cls = RoformerV2MaskedLMPreprocessor
142
+
143
+ def __init__(
144
+ self,
145
+ backbone,
146
+ preprocessor=None,
147
+ **kwargs,
148
+ ):
149
+ # === Layers ===
150
+ self.backbone = backbone
151
+ self.preprocessor = preprocessor
152
+ self.masked_lm_head = RoformerV2MaskedLMHead(
153
+ vocabulary_size=backbone.vocabulary_size,
154
+ token_embedding=backbone.token_embedding,
155
+ name="mlm_head",
156
+ )
157
+
158
+ # === Functional Model ===
159
+ inputs = {
160
+ **backbone.input,
161
+ "mask_positions": keras.Input(
162
+ shape=(None,), dtype="int32", name="mask_positions"
163
+ ),
164
+ }
165
+ backbone_outputs = backbone(backbone.input)
166
+ outputs = self.masked_lm_head(
167
+ backbone_outputs, inputs["mask_positions"]
168
+ )
169
+ super().__init__(
170
+ inputs=inputs,
171
+ outputs=outputs,
172
+ **kwargs,
173
+ )
@@ -0,0 +1,125 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.models.masked_lm_preprocessor import MaskedLMPreprocessor
5
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
6
+ RoformerV2Backbone,
7
+ )
8
+ from keras_hub.src.models.roformer_v2.roformer_v2_tokenizer import (
9
+ RoformerV2Tokenizer,
10
+ )
11
+ from keras_hub.src.utils.tensor_utils import preprocessing_function
12
+
13
+
14
+ @keras_hub_export("keras_hub.models.RoformerV2MaskedLMPreprocessor")
15
+ class RoformerV2MaskedLMPreprocessor(MaskedLMPreprocessor):
16
+ """RoformerV2 preprocessing for the masked language modeling task.
17
+
18
+ This preprocessing layer will prepare inputs for a masked language modeling
19
+ task. It is primarily intended for use with the
20
+ `keras_hub.models.RoformerV2MaskedLM` task model.
21
+ Preprocessing will occur in multiple steps.
22
+
23
+ 1. Tokenize any number of input segments using the `tokenizer`.
24
+ 2. Pack the inputs together with the appropriate `"[CLS]"`, `"[SEP]"` and
25
+ `"[PAD]"` tokens.
26
+ 3. Randomly select non-special tokens to mask, controlled by
27
+ `mask_selection_rate`.
28
+ 4. Construct a `(x, y, sample_weight)` tuple suitable for training with a
29
+ `keras_hub.models.RoformerV2MaskedLM` task model.
30
+
31
+ Args:
32
+ tokenizer: A `keras_hub.models.RoformerV2Tokenizer` instance.
33
+ sequence_length: int. The length of the packed inputs.
34
+ truncate: string. The algorithm to truncate a list of batched segments
35
+ to fit within `sequence_length`. The value can be either
36
+ `round_robin` or `waterfall`:
37
+ - `"round_robin"`: Available space is assigned one token at a
38
+ time in a round-robin fashion to the inputs that still need
39
+ some, until the limit is reached.
40
+ - `"waterfall"`: The allocation of the budget is done using a
41
+ "waterfall" algorithm that allocates quota in a
42
+ left-to-right manner and fills up the buckets until we run
43
+ out of budget. It supports an arbitrary number of segments.
44
+ mask_selection_rate: float. The probability an input token will be
45
+ dynamically masked.
46
+ mask_selection_length: int. The maximum number of masked tokens
47
+ in a given sample.
48
+ mask_token_rate: float. The probability the a selected token will be
49
+ replaced with the mask token.
50
+ random_token_rate: float. The probability the a selected token will be
51
+ replaced with a random token from the vocabulary. A selected token
52
+ will be left as is with probability
53
+ `1 - mask_token_rate - random_token_rate`.
54
+
55
+ Call arguments:
56
+ x: A tensor of single string sequences, or a tuple of multiple
57
+ tensor sequences to be packed together. Inputs may be batched or
58
+ unbatched. For single sequences, raw python inputs will be converted
59
+ to tensors. For multiple sequences, pass tensors directly.
60
+ y: Label data. Should always be `None` as the layer generates labels.
61
+ sample_weight: Label weights. Should always be `None` as the layer
62
+ generates label weights.
63
+
64
+ Examples:
65
+
66
+ Directly calling the layer on data.
67
+ ```python
68
+ preprocessor = keras_hub.models.RoformerV2MaskedLMPreprocessor.from_preset(
69
+ "roformer_v2_base_zh"
70
+ )
71
+
72
+ # Tokenize and mask a single sentence.
73
+ preprocessor("The quick brown fox jumped.")
74
+
75
+ # Tokenize and mask a batch of single sentences.
76
+ preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
77
+
78
+ # Tokenize and mask sentence pairs.
79
+ # In this case, always convert input to tensors before calling the layer.
80
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
81
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
82
+ preprocessor((first, second))
83
+ ```
84
+
85
+ Mapping with `tf.data.Dataset`.
86
+ ```python
87
+ preprocessor = keras_hub.models.RoformerV2MaskedLMPreprocessor.from_preset(
88
+ "roformer_v2_base_zh"
89
+ )
90
+
91
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
92
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
93
+
94
+ # Map single sentences.
95
+ ds = tf.data.Dataset.from_tensor_slices(first)
96
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
97
+
98
+ # Map sentence pairs.
99
+ ds = tf.data.Dataset.from_tensor_slices((first, second))
100
+ # Watch out for tf.data's default unpacking of tuples here!
101
+ # Best to invoke the `preprocessor` directly in this case.
102
+ ds = ds.map(
103
+ lambda first, second: preprocessor(x=(first, second)),
104
+ num_parallel_calls=tf.data.AUTOTUNE,
105
+ )
106
+ ```
107
+ """
108
+
109
+ backbone_cls = RoformerV2Backbone
110
+ tokenizer_cls = RoformerV2Tokenizer
111
+
112
+ @preprocessing_function
113
+ def call(self, x, y=None, sample_weight=None):
114
+ x = x if isinstance(x, tuple) else (x,)
115
+ x = tuple(self.tokenizer(segment) for segment in x)
116
+ token_ids, segment_ids = self.packer(x)
117
+ masker_outputs = self.masker(token_ids)
118
+ x = {
119
+ "token_ids": masker_outputs["token_ids"],
120
+ "segment_ids": segment_ids,
121
+ "mask_positions": masker_outputs["mask_positions"],
122
+ }
123
+ y = masker_outputs["mask_ids"]
124
+ sample_weight = masker_outputs["mask_weights"]
125
+ return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
@@ -0,0 +1,121 @@
1
+ from keras_hub.src.api_export import keras_hub_export
2
+ from keras_hub.src.models.roberta.roberta_text_classifier import (
3
+ RobertaTextClassifier, # noqa: E501
4
+ )
5
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
6
+ RoformerV2Backbone,
7
+ )
8
+ from keras_hub.src.models.roformer_v2.roformer_v2_text_classifier_preprocessor import ( # noqa: E501
9
+ RoformerV2TextClassifierPreprocessor,
10
+ )
11
+
12
+
13
+ @keras_hub_export("keras_hub.models.RorformerV2TextClassifier")
14
+ class RorformerV2TextClassifier(RobertaTextClassifier):
15
+ """An end-to-end RoformerV2 model for classification tasks.
16
+
17
+ This model attaches a classification head to
18
+ `keras_hub.model.RoformerV2Backbone`, mapping from the backbone outputs
19
+ to logits suitable for a classification task. For usage of this model with
20
+ pre-trained weights, use the `from_preset()` constructor.
21
+
22
+ This model can optionally be configured with a `preprocessor` layer, in
23
+ which case it will automatically apply preprocessing to raw inputs during
24
+ `fit()`, `predict()`, and `evaluate()`. This is done by default when
25
+ creating the model with `from_preset()`.
26
+
27
+ Disclaimer: Pre-trained models are provided on an "as is" basis, without
28
+ warranties or conditions of any kind.
29
+
30
+ Args:
31
+ backbone: A `keras_hub.models.RoformerV2Backbone` instance.
32
+ num_classes: int. Number of classes to predict.
33
+ preprocessor: A `keras_hub.models.RoformerV2TextClassifierPreprocessor`
34
+ or `None`. If `None`, this model will not apply preprocessing, and
35
+ inputs should be preprocessed before calling the model.
36
+ activation: Optional `str` or callable. The
37
+ activation function to use on the model outputs. Set
38
+ `activation="softmax"` to return output probabilities.
39
+ Defaults to `None`.
40
+ dropout: float. The dropout probability value, applied after the dense
41
+ layer.
42
+
43
+ Examples:
44
+
45
+ Raw string data.
46
+ ```python
47
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
48
+ labels = [0, 3]
49
+
50
+ # Pretrained classifier.
51
+ classifier = keras_hub.models.RoformerV2TextClassifier.from_preset(
52
+ "roformer_v2_base_zh",
53
+ num_classes=4,
54
+ )
55
+ classifier.fit(x=features, y=labels, batch_size=2)
56
+ classifier.predict(x=features, batch_size=2)
57
+
58
+ # Re-compile (e.g., with a new learning rate).
59
+ classifier.compile(
60
+ loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
61
+ optimizer=keras.optimizers.Adam(5e-5),
62
+ jit_compile=True,
63
+ )
64
+ # Access backbone programmatically (e.g., to change `trainable`).
65
+ classifier.backbone.trainable = False
66
+ # Fit again.
67
+ classifier.fit(x=features, y=labels, batch_size=2)
68
+ ```
69
+
70
+ Preprocessed integer data.
71
+ ```python
72
+ features = {
73
+ "token_ids": np.ones(shape=(2, 12), dtype="int32"),
74
+ "segment_ids": np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0]] * 2),
75
+ "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]] * 2),
76
+ }
77
+ labels = [0, 3]
78
+
79
+ # Pretrained classifier without preprocessing.
80
+ classifier = keras_hub.models.RoformerV2TextClassifier.from_preset(
81
+ "roformer_v2_base_zh",
82
+ num_classes=4,
83
+ preprocessor=None,
84
+ )
85
+ classifier.fit(x=features, y=labels, batch_size=2)
86
+ ```
87
+
88
+ Custom backbone and vocabulary.
89
+ ```python
90
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
91
+ labels = [0, 3]
92
+
93
+ vocab = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
94
+ vocab += ["The", "quick", "brown", "fox", "jumped", "."]
95
+ tokenizer = keras_hub.models.RoformerV2Tokenizer(
96
+ vocabulary=vocab,
97
+ )
98
+ preprocessor = keras_hub.models.RoformerV2TextClassifierPreprocessor(
99
+ tokenizer=tokenizer,
100
+ sequence_length=128,
101
+ )
102
+ backbone = keras_hub.models.RoformerV2Backbone(
103
+ vocabulary_size=30552,
104
+ num_layers=4,
105
+ num_heads=4,
106
+ hidden_dim=256,
107
+ intermediate_dim=512,
108
+ max_wavelength=128,
109
+ head_size=64,
110
+ )
111
+ classifier = keras_hub.models.RoformerV2TextClassifier(
112
+ backbone=backbone,
113
+ preprocessor=preprocessor,
114
+ num_classes=4,
115
+ )
116
+ classifier.fit(x=features, y=labels, batch_size=2)
117
+ ```
118
+ """
119
+
120
+ backbone_cls = RoformerV2Backbone
121
+ preprocessor_cls = RoformerV2TextClassifierPreprocessor
@@ -0,0 +1,128 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.models.bert.bert_text_classifier_preprocessor import (
5
+ BertTextClassifierPreprocessor,
6
+ )
7
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
8
+ RoformerV2Backbone,
9
+ )
10
+ from keras_hub.src.models.roformer_v2.roformer_v2_tokenizer import (
11
+ RoformerV2Tokenizer,
12
+ )
13
+ from keras_hub.src.utils.tensor_utils import preprocessing_function
14
+
15
+
16
+ @keras_hub_export("keras_hub.models.RoformerV2TextClassifierPreprocessor")
17
+ class RoformerV2TextClassifierPreprocessor(BertTextClassifierPreprocessor):
18
+ """A RoformerV2 preprocessing layer which tokenizes and packs inputs.
19
+
20
+ This preprocessing layer will do three things:
21
+
22
+ 1. Tokenize any number of input segments using the `tokenizer`.
23
+ 2. Pack the inputs together using a `keras_hub.layers.MultiSegmentPacker`.
24
+ with the appropriate `"[CLS]"`, `"[SEP]"` and `"[PAD]"` tokens.
25
+ 3. Construct a dictionary with keys `"token_ids"`, `"segment_ids"`,
26
+ `"padding_mask"`, that can be passed directly to a RoformerV2 model.
27
+
28
+ This layer can be used directly with `tf.data.Dataset.map` to preprocess
29
+ string data in the `(x, y, sample_weight)` format used by
30
+ `keras.Model.fit`.
31
+
32
+ Args:
33
+ tokenizer: A `keras_hub.models.RoformerV2Tokenizer` instance.
34
+ sequence_length: The length of the packed inputs.
35
+ truncate: string. The algorithm to truncate a list of batched segments
36
+ to fit within `sequence_length`. The value can be either
37
+ `round_robin` or `waterfall`:
38
+ - `"round_robin"`: Available space is assigned one token at a
39
+ time in a round-robin fashion to the inputs that still need
40
+ some, until the limit is reached.
41
+ - `"waterfall"`: The allocation of the budget is done using a
42
+ "waterfall" algorithm that allocates quota in a
43
+ left-to-right manner and fills up the buckets until we run
44
+ out of budget. It supports an arbitrary number of segments.
45
+
46
+ Call arguments:
47
+ x: A tensor of single string sequences, or a tuple of multiple
48
+ tensor sequences to be packed together. Inputs may be batched or
49
+ unbatched. For single sequences, raw python inputs will be converted
50
+ to tensors. For multiple sequences, pass tensors directly.
51
+ y: Any label data. Will be passed through unaltered.
52
+ sample_weight: Any label weight data. Will be passed through unaltered.
53
+
54
+ Examples:
55
+
56
+ Directly calling the layer on data.
57
+ ```python
58
+ preprocessor = keras_hub.models.TextClassifierPreprocessor.from_preset(
59
+ "roformer_v2_base_zh"
60
+ )
61
+
62
+ # Tokenize and pack a single sentence.
63
+ preprocessor("The quick brown fox jumped.")
64
+
65
+ # Tokenize a batch of single sentences.
66
+ preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
67
+
68
+ # Preprocess a batch of sentence pairs.
69
+ # When handling multiple sequences, always convert to tensors first!
70
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
71
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
72
+ preprocessor((first, second))
73
+
74
+ # Custom vocabulary.
75
+ vocab = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
76
+ vocab += ["The", "quick", "brown", "fox", "jumped", "."]
77
+ tokenizer = keras_hub.models.RoformerV2Tokenizer(vocabulary=vocab)
78
+ preprocessor =
79
+ keras_hub.models.RoformerV2TextClassifierPreprocessor(tokenizer)
80
+ preprocessor("The quick brown fox jumped.")
81
+ ```
82
+
83
+ Mapping with `tf.data.Dataset`.
84
+ ```python
85
+ preprocessor = keras_hub.models.TextClassifierPreprocessor.from_preset(
86
+ "roformer_v2_base_zh"
87
+ )
88
+
89
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
90
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
91
+ label = tf.constant([1, 1])
92
+
93
+ # Map labeled single sentences.
94
+ ds = tf.data.Dataset.from_tensor_slices((first, label))
95
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
96
+
97
+ # Map unlabeled single sentences.
98
+ ds = tf.data.Dataset.from_tensor_slices(first)
99
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
100
+
101
+ # Map labeled sentence pairs.
102
+ ds = tf.data.Dataset.from_tensor_slices(((first, second), label))
103
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
104
+
105
+ # Map unlabeled sentence pairs.
106
+ ds = tf.data.Dataset.from_tensor_slices((first, second))
107
+ # Watch out for tf.data's default unpacking of tuples here!
108
+ # Best to invoke the `preprocessor` directly in this case.
109
+ ds = ds.map(
110
+ lambda first, second: preprocessor(x=(first, second)),
111
+ num_parallel_calls=tf.data.AUTOTUNE,
112
+ )
113
+ ```
114
+ """
115
+
116
+ backbone_cls = RoformerV2Backbone
117
+ tokenizer_cls = RoformerV2Tokenizer
118
+
119
+ @preprocessing_function
120
+ def call(self, x, y=None, sample_weight=None):
121
+ x = x if isinstance(x, tuple) else (x,)
122
+ x = tuple(self.tokenizer(segment) for segment in x)
123
+ token_ids, segment_ids = self.packer(x)
124
+ x = {
125
+ "token_ids": token_ids,
126
+ "segment_ids": segment_ids,
127
+ }
128
+ return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
@@ -0,0 +1,62 @@
1
+ from keras_hub.src.api_export import keras_hub_export
2
+ from keras_hub.src.models.bert.bert_tokenizer import BertTokenizer
3
+ from keras_hub.src.models.roformer_v2.roformer_v2_backbone import (
4
+ RoformerV2Backbone,
5
+ )
6
+
7
+
8
+ @keras_hub_export(
9
+ [
10
+ "keras_hub.tokenizers.RoformerV2Tokenizer",
11
+ "keras_hub.models.RoformerV2Tokenizer",
12
+ ]
13
+ )
14
+ class RoformerV2Tokenizer(BertTokenizer):
15
+ """A RoformerV2 tokenizer using WordPiece subword segmentation.
16
+
17
+ This tokenizer class will tokenize raw strings into integer sequences and
18
+ is based on `keras_hub.tokenizers.WordPieceTokenizer`. Unlike the
19
+ underlying tokenizer, it will check for special tokens needed by RoformerV2
20
+ models and provides a `from_preset()` method to automatically download
21
+ a matching vocabulary for a RoformerV2 preset.
22
+
23
+ If input is a batch of strings (rank > 0), the layer will output a
24
+ `tf.RaggedTensor` where the last dimension of the output is ragged.
25
+
26
+ If input is a scalar string (rank == 0), the layer will output a dense
27
+ `tf.Tensor` with static shape `[None]`.
28
+
29
+ Args:
30
+ vocabulary: A list of strings or a string filename path. If
31
+ passing a list, each element of the list should be a single word
32
+ piece token string. If passing a filename, the file should be a
33
+ plain text file containing a single word piece token per line.
34
+ lowercase: If `True`, the input text will be first lowered before
35
+ tokenization.
36
+ special_tokens_in_strings: bool. A bool to indicate if the tokenizer
37
+ should expect special tokens in input strings that should be
38
+ tokenized and mapped correctly to their ids. Defaults to False.
39
+
40
+ Examples:
41
+ ```python
42
+ # Unbatched input.
43
+ tokenizer = keras_hub.models.RoformerV2Tokenizer.from_preset(
44
+ "roformer_v2_base_zh",
45
+ )
46
+ tokenizer("The quick brown fox jumped.")
47
+
48
+ # Batched input.
49
+ tokenizer(["The quick brown fox jumped.", "The fox slept."])
50
+
51
+ # Detokenization.
52
+ tokenizer.detokenize(tokenizer("The quick brown fox jumped."))
53
+
54
+ # Custom vocabulary.
55
+ vocab = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
56
+ vocab += ["The", "quick", "brown", "fox", "jumped", "."]
57
+ tokenizer = keras_hub.models.RoformerV2Tokenizer(vocabulary=vocab)
58
+ tokenizer("The quick brown fox jumped.")
59
+ ```
60
+ """
61
+
62
+ backbone_cls = RoformerV2Backbone
@@ -238,7 +238,8 @@ def get_file(preset, path):
238
238
  "2) a Kaggle Models handle like "
239
239
  "`'kaggle://keras/bert/keras/bert_base_en'`\n"
240
240
  "3) a Hugging Face handle like `'hf://username/bert_base_en'`\n"
241
- "4) a path to a local preset directory like `'./bert_base_en`\n"
241
+ "4) a Modelscope handle like `'modelscope://username/bert_base_en'`\n"
242
+ "5) a path to a local preset directory like `'./bert_base_en'`\n"
242
243
  "Use `print(cls.presets.keys())` to view all built-in presets for "
243
244
  "API symbol `cls`.\n"
244
245
  f"Received: preset='{preset}'"
@@ -1,7 +1,7 @@
1
1
  from keras_hub.src.api_export import keras_hub_export
2
2
 
3
3
  # Unique source of truth for the version number.
4
- __version__ = "0.20.0.dev202504010407"
4
+ __version__ = "0.20.0.dev202504020401"
5
5
 
6
6
 
7
7
  @keras_hub_export("keras_hub.version")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: keras-hub-nightly
3
- Version: 0.20.0.dev202504010407
3
+ Version: 0.20.0.dev202504020401
4
4
  Summary: Industry-strength Natural Language Processing extensions for Keras.
5
5
  Home-page: https://github.com/keras-team/keras-hub
6
6
  Author: Keras team
@@ -2,13 +2,13 @@ keras_hub/__init__.py,sha256=QGdXyHgYt6cMUAP1ebxwc6oR86dE0dkMxNy2eOCQtFo,855
2
2
  keras_hub/api/__init__.py,sha256=EzR6D-XWsm_gDrX5LDwKEmrah_gu3ffpj8GKBudE0yI,485
3
3
  keras_hub/api/layers/__init__.py,sha256=cALDY20DHCVjJDKCD84zHvTZtAgz0xEvozk7a3Cl1Uk,3719
4
4
  keras_hub/api/metrics/__init__.py,sha256=So8Ec-lOcTzn_UUMmAdzDm8RKkPu2dbRUm2px8gpUEI,381
5
- keras_hub/api/models/__init__.py,sha256=Ml8AQyMz9VKuLGEjKKQzlIDNScIaoCYmlgH-Zfk4Jxo,18725
5
+ keras_hub/api/models/__init__.py,sha256=cN3c2t8tldP79aVk4Z2CnMNLqwu0uOym7yuZ_niKZzE,19393
6
6
  keras_hub/api/samplers/__init__.py,sha256=n-_SEXxr2LNUzK2FqVFN7alsrkx1P_HOVTeLZKeGCdE,730
7
- keras_hub/api/tokenizers/__init__.py,sha256=TOTM3he5JWPME_4e29_S1nrWibTHomcuuKQ4KarqUNo,2831
7
+ keras_hub/api/tokenizers/__init__.py,sha256=NCQSOg3vf3KlM2YBsxApcJUVu9MH2jV0NQrM3f4EhJ4,2927
8
8
  keras_hub/api/utils/__init__.py,sha256=Gp1E6gG-RtKQS3PBEQEOz9PQvXkXaJ0ySGMqZ7myN7A,215
9
9
  keras_hub/src/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  keras_hub/src/api_export.py,sha256=9pQZK27JObxWZ96QPLBp1OBsjWigh1iuV6RglPGMRk0,1499
11
- keras_hub/src/version_utils.py,sha256=OsUwPWPZpPCMjDiiDuMytzPQ_fmJixCqlxXypU5TQGg,222
11
+ keras_hub/src/version_utils.py,sha256=Cu7L8D-l2tjToEgezwk_RlRVOFOvu5Fs_mSsbhAGc_4,222
12
12
  keras_hub/src/layers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  keras_hub/src/layers/modeling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
14
  keras_hub/src/layers/modeling/alibi_bias.py,sha256=1XBTHI52L_iJDhN_w5ydu_iMhCuTgQAxEPwcLA6BPuk,4411
@@ -187,7 +187,7 @@ keras_hub/src/models/flux/flux_presets.py,sha256=z7C_FbI1_F5YETXuWpc7Yh_0w-5N0eB
187
187
  keras_hub/src/models/flux/flux_text_to_image.py,sha256=Rf5dD2EhG0bE8Gyg9sqaA8YEexS1kdraofIkxiZDjvc,4166
188
188
  keras_hub/src/models/flux/flux_text_to_image_preprocessor.py,sha256=Fs9jr97QtmRUbRRz1kITpkuhDM2GoV3n0XSFC-qQA14,2252
189
189
  keras_hub/src/models/gemma/__init__.py,sha256=rVzOJMJ39bgVlT8UdC0t8PlN2c237GKTBmfHIsbPuOQ,251
190
- keras_hub/src/models/gemma/gemma_attention.py,sha256=XShBTunOWQOOE4Aapy3HdV9uIWuMcdNdYS1k1P3ia60,9708
190
+ keras_hub/src/models/gemma/gemma_attention.py,sha256=j-YjkcUIv2ZqQCrJ2GW1nMgpO2ZQsxNedSvxAyKaHNA,9783
191
191
  keras_hub/src/models/gemma/gemma_backbone.py,sha256=GzAUSArw_pN9dtWQzTVhWDbW-XyWt4GyMcFLn9hwmh0,13391
192
192
  keras_hub/src/models/gemma/gemma_causal_lm.py,sha256=3OXaIXlrKqMIuUnBk-bUz-0SYFL-XkkQTWm8qRY2YII,16770
193
193
  keras_hub/src/models/gemma/gemma_causal_lm_preprocessor.py,sha256=bpKkEurWIfa6Kp9s4pz84-sBDSA6ZFNHP8nXG1fFQrg,2912
@@ -315,6 +315,16 @@ keras_hub/src/models/roberta/roberta_presets.py,sha256=lu8_E888-YGlhMo1kE4LnsR0R
315
315
  keras_hub/src/models/roberta/roberta_text_classifier.py,sha256=x36hU84P-ROReZniUA8sMODzj2olrHvG0F5RTiz6Two,6681
316
316
  keras_hub/src/models/roberta/roberta_text_classifier_preprocessor.py,sha256=gAJa8JdPUmT1N7nxBqtaIbnfXV-xlNjTtkEevQhfjNU,5993
317
317
  keras_hub/src/models/roberta/roberta_tokenizer.py,sha256=VKPrgXVT9aMKP7et2DIWKlTN8g4tIzjya0MHqNz9BwQ,2712
318
+ keras_hub/src/models/roformer_v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
319
+ keras_hub/src/models/roformer_v2/roformer_v2_attention.py,sha256=RvDxuh0eZ6QEhyU_SzVcCbadSFWtNtsbHfYfWtBU7r0,7166
320
+ keras_hub/src/models/roformer_v2/roformer_v2_backbone.py,sha256=g1xCi9Zet0dHkiOtpjwsO1odc__HzLDn9cTHNykpYEE,7188
321
+ keras_hub/src/models/roformer_v2/roformer_v2_encoder.py,sha256=o_M3dDtebBtXRAxwhiRmdWA59tu1_MNKLINf4GQYfeA,4218
322
+ keras_hub/src/models/roformer_v2/roformer_v2_masked_lm.py,sha256=4uQ6DKFDdBOu0bHaL45bqtpL-CMZw59inXirD9zWFlI,5950
323
+ keras_hub/src/models/roformer_v2/roformer_v2_masked_lm_preprocessor.py,sha256=1APlYMi_Be_aaEk4Ij6c16JH5OpDrGnvwtv8LY3fjrw,5403
324
+ keras_hub/src/models/roformer_v2/roformer_v2_presets.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
325
+ keras_hub/src/models/roformer_v2/roformer_v2_text_classifier.py,sha256=QSRSSWt1T16BFlSynyJduUTd86AEV4NvqdJgIiw1wys,4380
326
+ keras_hub/src/models/roformer_v2/roformer_v2_text_classifier_preprocessor.py,sha256=Md0ioE6OlEyhn6QDTrLVik8EVtiF2YvR5Bu5vAyGEHg,5270
327
+ keras_hub/src/models/roformer_v2/roformer_v2_tokenizer.py,sha256=Pc4z7e5rSZH6qh_suORb-O89ZaFcCjde_4gs-odYook,2406
318
328
  keras_hub/src/models/sam/__init__.py,sha256=fp71Q288xeE81tIOZkkudec4Acs8v4aO5WdyzCD9x-c,239
319
329
  keras_hub/src/models/sam/sam_backbone.py,sha256=VtT-tjTaVW6v2u_JLe3vyKUoHASPDs5aetc3s0MDo6U,4302
320
330
  keras_hub/src/models/sam/sam_image_converter.py,sha256=5POp3aYFu6CK3R0NNfeUBbjhguBkincSMNvlcIJXarE,324
@@ -422,7 +432,7 @@ keras_hub/src/tokenizers/word_piece_tokenizer_trainer.py,sha256=cylrs02ZrYQ1TuZr
422
432
  keras_hub/src/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
423
433
  keras_hub/src/utils/keras_utils.py,sha256=IB_eIrln3N5sVyCapwv1jzLEmuBv8vBRwSVd3toSgyI,3097
424
434
  keras_hub/src/utils/pipeline_model.py,sha256=jgzB6NQPSl0KOu08N-TazfOnXnUJbZjH2EXXhx25Ftg,9084
425
- keras_hub/src/utils/preset_utils.py,sha256=5xEm6Uz1vfQkBqyENt97qaxWoq-P7mlPC0LIpXqDM70,31928
435
+ keras_hub/src/utils/preset_utils.py,sha256=BqTqtLouPQrTKelup2og_yziRBcu9dXFbbAST0I-XlE,32012
426
436
  keras_hub/src/utils/python_utils.py,sha256=N8nWeO3san4YnGkffRXG3Ix7VEIMTKSN21FX5TuL7G8,202
427
437
  keras_hub/src/utils/tensor_utils.py,sha256=lczQWgPVJU09cLtNbo8MErVFNV9ne4gNlrzbNVQazg4,15042
428
438
  keras_hub/src/utils/imagenet/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -449,7 +459,7 @@ keras_hub/src/utils/transformers/convert_qwen.py,sha256=I2bfwo8AQd_JfwFpiAuCQ3k_
449
459
  keras_hub/src/utils/transformers/convert_vit.py,sha256=9SUZ9utNJhW_5cj3acMn9cRy47u2eIcDsrhmzj77o9k,5187
450
460
  keras_hub/src/utils/transformers/preset_loader.py,sha256=0Hi7R8HnATcwFVLsJwMMIMWTCXHNfep4IPiRpQXqM-w,3933
451
461
  keras_hub/src/utils/transformers/safetensor_utils.py,sha256=CYUHyA4y-B61r7NDnCsFb4t_UmSwZ1k9L-8gzEd6KRg,3339
452
- keras_hub_nightly-0.20.0.dev202504010407.dist-info/METADATA,sha256=77ncA8nPcUGWqFtGIA4EPqrK6BdhNskTR3vDrTVWaLU,7715
453
- keras_hub_nightly-0.20.0.dev202504010407.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
454
- keras_hub_nightly-0.20.0.dev202504010407.dist-info/top_level.txt,sha256=N4J6piIWBKa38A4uV-CnIopnOEf8mHAbkNXafXm_CuA,10
455
- keras_hub_nightly-0.20.0.dev202504010407.dist-info/RECORD,,
462
+ keras_hub_nightly-0.20.0.dev202504020401.dist-info/METADATA,sha256=UdVE9mpAcH4RH9b_-tSwYDep5ldoTNBEeDdj3uk1XnU,7715
463
+ keras_hub_nightly-0.20.0.dev202504020401.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
464
+ keras_hub_nightly-0.20.0.dev202504020401.dist-info/top_level.txt,sha256=N4J6piIWBKa38A4uV-CnIopnOEf8mHAbkNXafXm_CuA,10
465
+ keras_hub_nightly-0.20.0.dev202504020401.dist-info/RECORD,,