keras-hub-nightly 0.20.0.dev202503310403__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.
- keras_hub/api/models/__init__.py +21 -0
- keras_hub/api/tokenizers/__init__.py +3 -0
- keras_hub/src/models/gemma/gemma_attention.py +9 -7
- keras_hub/src/models/roformer_v2/__init__.py +0 -0
- keras_hub/src/models/roformer_v2/roformer_v2_attention.py +212 -0
- keras_hub/src/models/roformer_v2/roformer_v2_backbone.py +198 -0
- keras_hub/src/models/roformer_v2/roformer_v2_encoder.py +128 -0
- keras_hub/src/models/roformer_v2/roformer_v2_masked_lm.py +173 -0
- keras_hub/src/models/roformer_v2/roformer_v2_masked_lm_preprocessor.py +125 -0
- keras_hub/src/models/roformer_v2/roformer_v2_presets.py +0 -0
- keras_hub/src/models/roformer_v2/roformer_v2_text_classifier.py +121 -0
- keras_hub/src/models/roformer_v2/roformer_v2_text_classifier_preprocessor.py +128 -0
- keras_hub/src/models/roformer_v2/roformer_v2_tokenizer.py +62 -0
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_text_to_image_preprocessor.py +4 -2
- keras_hub/src/models/text_to_image_preprocessor.py +35 -0
- keras_hub/src/utils/preset_utils.py +2 -1
- keras_hub/src/version_utils.py +1 -1
- {keras_hub_nightly-0.20.0.dev202503310403.dist-info → keras_hub_nightly-0.20.0.dev202504020401.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.20.0.dev202503310403.dist-info → keras_hub_nightly-0.20.0.dev202504020401.dist-info}/RECORD +21 -10
- {keras_hub_nightly-0.20.0.dev202503310403.dist-info → keras_hub_nightly-0.20.0.dev202504020401.dist-info}/WHEEL +0 -0
- {keras_hub_nightly-0.20.0.dev202503310403.dist-info → keras_hub_nightly-0.20.0.dev202504020401.dist-info}/top_level.txt +0 -0
@@ -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)
|
File without changes
|
@@ -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
|
@@ -2,14 +2,16 @@ import keras
|
|
2
2
|
from keras import layers
|
3
3
|
|
4
4
|
from keras_hub.src.api_export import keras_hub_export
|
5
|
-
from keras_hub.src.models.preprocessor import Preprocessor
|
6
5
|
from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_backbone import ( # noqa: E501
|
7
6
|
StableDiffusion3Backbone,
|
8
7
|
)
|
8
|
+
from keras_hub.src.models.text_to_image_preprocessor import (
|
9
|
+
TextToImagePreprocessor,
|
10
|
+
)
|
9
11
|
|
10
12
|
|
11
13
|
@keras_hub_export("keras_hub.models.StableDiffusion3TextToImagePreprocessor")
|
12
|
-
class StableDiffusion3TextToImagePreprocessor(
|
14
|
+
class StableDiffusion3TextToImagePreprocessor(TextToImagePreprocessor):
|
13
15
|
"""Stable Diffusion 3 text-to-image model preprocessor.
|
14
16
|
|
15
17
|
This preprocessing layer is meant for use with
|
@@ -0,0 +1,35 @@
|
|
1
|
+
from keras_hub.src.api_export import keras_hub_export
|
2
|
+
from keras_hub.src.models.preprocessor import Preprocessor
|
3
|
+
|
4
|
+
|
5
|
+
@keras_hub_export("keras_hub.models.TextToImagePreprocessor")
|
6
|
+
class TextToImagePreprocessor(Preprocessor):
|
7
|
+
"""Base class for text to image preprocessing layers.
|
8
|
+
|
9
|
+
`TextToImagePreprocessor` tasks wrap a `keras_hub.tokenizer.Tokenizer` to
|
10
|
+
create a preprocessing layer for text to image tasks. It is intended to be
|
11
|
+
paired with a `keras_hub.models.TextToImage` task.
|
12
|
+
|
13
|
+
The exact specifics of this layer will vary depending on the subclass
|
14
|
+
implementation per model architecture. Generally, it will take text input,
|
15
|
+
and tokenize, then pad/truncate so it is ready to be fed to a image
|
16
|
+
generation model (e.g. a diffusion model).
|
17
|
+
|
18
|
+
Examples.
|
19
|
+
```python
|
20
|
+
preprocessor = keras_hub.models.TextToImagePreprocessor.from_preset(
|
21
|
+
"stable_diffusion_3_medium",
|
22
|
+
sequence_length=256, # Optional.
|
23
|
+
)
|
24
|
+
|
25
|
+
# Tokenize and pad/truncate a single sentence.
|
26
|
+
x = "The quick brown fox jumped."
|
27
|
+
x = preprocessor(x)
|
28
|
+
|
29
|
+
# Tokenize and pad/truncate a batch of sentences.
|
30
|
+
x = ["The quick brown fox jumped."]
|
31
|
+
x = preprocessor(x)
|
32
|
+
```
|
33
|
+
"""
|
34
|
+
|
35
|
+
pass
|
@@ -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
|
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}'"
|
keras_hub/src/version_utils.py
CHANGED