keras-hub-nightly 0.15.0.dev20240911134614__py3-none-any.whl → 0.16.0.dev2024092017__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/__init__.py +0 -6
- keras_hub/api/__init__.py +1 -0
- keras_hub/api/models/__init__.py +22 -17
- keras_hub/{src/models/llama3/llama3_preprocessor.py → api/utils/__init__.py} +7 -8
- keras_hub/src/api_export.py +15 -9
- keras_hub/src/models/albert/albert_text_classifier.py +6 -1
- keras_hub/src/models/bert/bert_text_classifier.py +6 -1
- keras_hub/src/models/deberta_v3/deberta_v3_text_classifier.py +6 -1
- keras_hub/src/models/densenet/densenet_backbone.py +1 -1
- keras_hub/src/models/distil_bert/distil_bert_text_classifier.py +6 -1
- keras_hub/src/models/f_net/f_net_text_classifier.py +6 -1
- keras_hub/src/models/gemma/gemma_decoder_block.py +1 -1
- keras_hub/src/models/gpt2/gpt2_preprocessor.py +7 -78
- keras_hub/src/models/pali_gemma/pali_gemma_tokenizer.py +1 -1
- keras_hub/src/models/preprocessor.py +1 -5
- keras_hub/src/models/resnet/resnet_backbone.py +3 -16
- keras_hub/src/models/resnet/resnet_image_classifier.py +26 -3
- keras_hub/src/models/resnet/resnet_presets.py +12 -12
- keras_hub/src/models/retinanet/__init__.py +13 -0
- keras_hub/src/models/retinanet/anchor_generator.py +175 -0
- keras_hub/src/models/retinanet/box_matcher.py +259 -0
- keras_hub/src/models/retinanet/non_max_supression.py +578 -0
- keras_hub/src/models/roberta/roberta_text_classifier.py +6 -1
- keras_hub/src/models/task.py +6 -6
- keras_hub/src/models/text_classifier.py +12 -1
- keras_hub/src/models/xlm_roberta/xlm_roberta_text_classifier.py +6 -1
- keras_hub/src/tests/test_case.py +21 -0
- keras_hub/src/tokenizers/byte_pair_tokenizer.py +1 -0
- keras_hub/src/tokenizers/sentence_piece_tokenizer.py +1 -0
- keras_hub/src/tokenizers/word_piece_tokenizer.py +1 -0
- keras_hub/src/utils/imagenet/__init__.py +13 -0
- keras_hub/src/utils/imagenet/imagenet_utils.py +1067 -0
- keras_hub/src/utils/preset_utils.py +24 -33
- keras_hub/src/utils/tensor_utils.py +14 -14
- keras_hub/src/utils/timm/convert_resnet.py +0 -1
- keras_hub/src/utils/timm/preset_loader.py +6 -7
- keras_hub/src/version_utils.py +1 -1
- keras_hub_nightly-0.16.0.dev2024092017.dist-info/METADATA +202 -0
- {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev2024092017.dist-info}/RECORD +41 -45
- {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev2024092017.dist-info}/WHEEL +1 -1
- keras_hub/src/models/bart/bart_preprocessor.py +0 -264
- keras_hub/src/models/bloom/bloom_preprocessor.py +0 -178
- keras_hub/src/models/electra/electra_preprocessor.py +0 -155
- keras_hub/src/models/falcon/falcon_preprocessor.py +0 -180
- keras_hub/src/models/gemma/gemma_preprocessor.py +0 -184
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_preprocessor.py +0 -138
- keras_hub/src/models/llama/llama_preprocessor.py +0 -182
- keras_hub/src/models/mistral/mistral_preprocessor.py +0 -183
- keras_hub/src/models/opt/opt_preprocessor.py +0 -181
- keras_hub/src/models/phi3/phi3_preprocessor.py +0 -183
- keras_hub_nightly-0.15.0.dev20240911134614.dist-info/METADATA +0 -33
- {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev2024092017.dist-info}/top_level.txt +0 -0
@@ -1,178 +0,0 @@
|
|
1
|
-
# Copyright 2024 The KerasHub Authors
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# https://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
|
15
|
-
|
16
|
-
import keras
|
17
|
-
|
18
|
-
from keras_hub.src.api_export import keras_hub_export
|
19
|
-
from keras_hub.src.layers.preprocessing.start_end_packer import StartEndPacker
|
20
|
-
from keras_hub.src.models.bloom.bloom_backbone import BloomBackbone
|
21
|
-
from keras_hub.src.models.bloom.bloom_tokenizer import BloomTokenizer
|
22
|
-
from keras_hub.src.models.preprocessor import Preprocessor
|
23
|
-
from keras_hub.src.utils.tensor_utils import preprocessing_function
|
24
|
-
|
25
|
-
|
26
|
-
@keras_hub_export("keras_hub.models.BloomPreprocessor")
|
27
|
-
class BloomPreprocessor(Preprocessor):
|
28
|
-
"""BLOOM preprocessing layer which tokenizes and packs inputs.
|
29
|
-
|
30
|
-
This preprocessing layer will do 2 things:
|
31
|
-
|
32
|
-
- Tokenize the inputs using the `tokenizer`.
|
33
|
-
- Construct a dictionary with keys `"token_ids"`, `"padding_mask"`, that can
|
34
|
-
be passed directly to a `keras_hub.models.BloomBackbone`.
|
35
|
-
|
36
|
-
This layer can be used directly with `tf.data.Dataset.map` to preprocess
|
37
|
-
string data in the `(x, y, sample_weight)` format used by
|
38
|
-
`keras.Model.fit`.
|
39
|
-
|
40
|
-
The call method of this layer accepts three arguments, `x`, `y`, and
|
41
|
-
`sample_weight`. `x` can be a python string or tensor representing a single
|
42
|
-
segment, a list of python strings representing a batch of single segments,
|
43
|
-
or a list of tensors representing multiple segments to be packed together.
|
44
|
-
`y` and `sample_weight` are both optional, can have any format, and will be
|
45
|
-
passed through unaltered.
|
46
|
-
|
47
|
-
Args:
|
48
|
-
tokenizer: A `keras_hub.models.BloomTokenizer` instance.
|
49
|
-
sequence_length: The length of the packed inputs.
|
50
|
-
add_start_token: If `True`, the preprocessor will prepend the tokenizer
|
51
|
-
start token to each input sequence.
|
52
|
-
add_end_token: If `True`, the preprocessor will append the tokenizer
|
53
|
-
end token to each input sequence.
|
54
|
-
|
55
|
-
Call arguments:
|
56
|
-
x: A string, `tf.Tensor` or list of python strings.
|
57
|
-
y: Any label data. Will be passed through unaltered.
|
58
|
-
sample_weight: Any label weight data. Will be passed through unaltered.
|
59
|
-
sequence_length: Pass to override the configured `sequence_length` of
|
60
|
-
the layer.
|
61
|
-
|
62
|
-
Examples:
|
63
|
-
|
64
|
-
Directly calling the layer on data.
|
65
|
-
```python
|
66
|
-
preprocessor = keras_hub.models.BloomPreprocessor.from_preset(
|
67
|
-
"bloom_560m_multi"
|
68
|
-
)
|
69
|
-
# Tokenize and pack a single sentence.
|
70
|
-
preprocessor("The quick brown fox jumped.")
|
71
|
-
|
72
|
-
# Tokenize a batch of single sentences.
|
73
|
-
preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
|
74
|
-
|
75
|
-
# Custom vocabulary.
|
76
|
-
features = ["a quick fox.", "a fox quick."]
|
77
|
-
vocab = {"<pad>": 0, "<s>":1, "</s>":2, "a": 3, "Ġquick": 4, "Ġfox": 5}
|
78
|
-
merges = ["Ġ q", "u i", "c k", "ui ck", "Ġq uick"]
|
79
|
-
merges += ["Ġ f", "o x", "Ġf ox"]
|
80
|
-
tokenizer = keras_hub.models.BloomTokenizer(
|
81
|
-
vocabulary=vocab,
|
82
|
-
merges=merges,
|
83
|
-
)
|
84
|
-
preprocessor = keras_hub.models.BloomPreprocessor(tokenizer=tokenizer)
|
85
|
-
preprocessor("The quick brown fox jumped.")
|
86
|
-
```
|
87
|
-
|
88
|
-
Mapping with `tf.data.Dataset`.
|
89
|
-
```python
|
90
|
-
preprocessor = keras_hub.models.BloomPreprocessor.from_preset(
|
91
|
-
"bloom_560m_multi"
|
92
|
-
)
|
93
|
-
|
94
|
-
text = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
|
95
|
-
label = tf.constant([1, 1])
|
96
|
-
|
97
|
-
# Map labeled single sentences.
|
98
|
-
ds = tf.data.Dataset.from_tensor_slices((text, label))
|
99
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
100
|
-
|
101
|
-
# Map unlabeled single sentences.
|
102
|
-
ds = tf.data.Dataset.from_tensor_slices(text)
|
103
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
104
|
-
```
|
105
|
-
"""
|
106
|
-
|
107
|
-
backbone_cls = BloomBackbone
|
108
|
-
tokenizer_cls = BloomTokenizer
|
109
|
-
|
110
|
-
def __init__(
|
111
|
-
self,
|
112
|
-
tokenizer,
|
113
|
-
sequence_length=1024,
|
114
|
-
add_start_token=True,
|
115
|
-
add_end_token=True,
|
116
|
-
**kwargs,
|
117
|
-
):
|
118
|
-
super().__init__(**kwargs)
|
119
|
-
self.tokenizer = tokenizer
|
120
|
-
self.packer = None
|
121
|
-
self.sequence_length = sequence_length
|
122
|
-
self.add_start_token = add_start_token
|
123
|
-
self.add_end_token = add_end_token
|
124
|
-
|
125
|
-
def build(self, input_shape):
|
126
|
-
# Defer packer creation to `build()` so that we can be sure tokenizer
|
127
|
-
# assets have loaded when restoring a saved model.
|
128
|
-
self.packer = StartEndPacker(
|
129
|
-
start_value=self.tokenizer.start_token_id,
|
130
|
-
end_value=self.tokenizer.end_token_id,
|
131
|
-
pad_value=self.tokenizer.pad_token_id,
|
132
|
-
sequence_length=self.sequence_length,
|
133
|
-
return_padding_mask=True,
|
134
|
-
)
|
135
|
-
self.built = True
|
136
|
-
|
137
|
-
@preprocessing_function
|
138
|
-
def call(
|
139
|
-
self,
|
140
|
-
x,
|
141
|
-
y=None,
|
142
|
-
sample_weight=None,
|
143
|
-
sequence_length=None,
|
144
|
-
):
|
145
|
-
sequence_length = sequence_length or self.sequence_length
|
146
|
-
token_ids, padding_mask = self.packer(
|
147
|
-
self.tokenizer(x),
|
148
|
-
sequence_length=sequence_length,
|
149
|
-
add_start_value=self.add_start_token,
|
150
|
-
add_end_value=self.add_end_token,
|
151
|
-
)
|
152
|
-
x = {
|
153
|
-
"token_ids": token_ids,
|
154
|
-
"padding_mask": padding_mask,
|
155
|
-
}
|
156
|
-
return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
|
157
|
-
|
158
|
-
def get_config(self):
|
159
|
-
config = super().get_config()
|
160
|
-
config.update(
|
161
|
-
{
|
162
|
-
"sequence_length": self.sequence_length,
|
163
|
-
"add_start_token": self.add_start_token,
|
164
|
-
"add_end_token": self.add_end_token,
|
165
|
-
}
|
166
|
-
)
|
167
|
-
return config
|
168
|
-
|
169
|
-
@property
|
170
|
-
def sequence_length(self):
|
171
|
-
"""The padded length of model input sequences."""
|
172
|
-
return self._sequence_length
|
173
|
-
|
174
|
-
@sequence_length.setter
|
175
|
-
def sequence_length(self, value):
|
176
|
-
self._sequence_length = value
|
177
|
-
if self.packer is not None:
|
178
|
-
self.packer.sequence_length = value
|
@@ -1,155 +0,0 @@
|
|
1
|
-
# Copyright 2024 The KerasHub Authors
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# https://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
|
15
|
-
import keras
|
16
|
-
|
17
|
-
from keras_hub.src.api_export import keras_hub_export
|
18
|
-
from keras_hub.src.layers.preprocessing.multi_segment_packer import (
|
19
|
-
MultiSegmentPacker,
|
20
|
-
)
|
21
|
-
from keras_hub.src.models.electra.electra_backbone import ElectraBackbone
|
22
|
-
from keras_hub.src.models.electra.electra_tokenizer import ElectraTokenizer
|
23
|
-
from keras_hub.src.models.preprocessor import Preprocessor
|
24
|
-
from keras_hub.src.utils.tensor_utils import preprocessing_function
|
25
|
-
|
26
|
-
|
27
|
-
@keras_hub_export("keras_hub.models.ElectraPreprocessor")
|
28
|
-
class ElectraPreprocessor(Preprocessor):
|
29
|
-
"""A ELECTRA preprocessing layer which tokenizes and packs inputs.
|
30
|
-
|
31
|
-
This preprocessing layer will do three things:
|
32
|
-
|
33
|
-
1. Tokenize any number of input segments using the `tokenizer`.
|
34
|
-
2. Pack the inputs together using a `keras_hub.layers.MultiSegmentPacker`.
|
35
|
-
with the appropriate `"[CLS]"`, `"[SEP]"` and `"[PAD]"` tokens.
|
36
|
-
3. Construct a dictionary of with keys `"token_ids"` and `"padding_mask"`,
|
37
|
-
that can be passed directly to a ELECTRA model.
|
38
|
-
|
39
|
-
This layer can be used directly with `tf.data.Dataset.map` to preprocess
|
40
|
-
string data in the `(x, y, sample_weight)` format used by
|
41
|
-
`keras.Model.fit`.
|
42
|
-
|
43
|
-
Args:
|
44
|
-
tokenizer: A `keras_hub.models.ElectraTokenizer` instance.
|
45
|
-
sequence_length: The length of the packed inputs.
|
46
|
-
truncate: string. The algorithm to truncate a list of batched segments
|
47
|
-
to fit within `sequence_length`. The value can be either
|
48
|
-
`round_robin` or `waterfall`:
|
49
|
-
- `"round_robin"`: Available space is assigned one token at a
|
50
|
-
time in a round-robin fashion to the inputs that still need
|
51
|
-
some, until the limit is reached.
|
52
|
-
- `"waterfall"`: The allocation of the budget is done using a
|
53
|
-
"waterfall" algorithm that allocates quota in a
|
54
|
-
left-to-right manner and fills up the buckets until we run
|
55
|
-
out of budget. It supports an arbitrary number of segments.
|
56
|
-
|
57
|
-
Call arguments:
|
58
|
-
x: A tensor of single string sequences, or a tuple of multiple
|
59
|
-
tensor sequences to be packed together. Inputs may be batched or
|
60
|
-
unbatched. For single sequences, raw python inputs will be converted
|
61
|
-
to tensors. For multiple sequences, pass tensors directly.
|
62
|
-
y: Any label data. Will be passed through unaltered.
|
63
|
-
sample_weight: Any label weight data. Will be passed through unaltered.
|
64
|
-
|
65
|
-
Examples:
|
66
|
-
|
67
|
-
Directly calling the layer on data.
|
68
|
-
```python
|
69
|
-
preprocessor = keras_hub.models.ElectraPreprocessor.from_preset(
|
70
|
-
"electra_base_discriminator_en"
|
71
|
-
)
|
72
|
-
preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
|
73
|
-
|
74
|
-
# Custom vocabulary.
|
75
|
-
vocab = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
|
76
|
-
vocab += ["The", "quick", "brown", "fox", "jumped", "."]
|
77
|
-
tokenizer = keras_hub.models.ElectraTokenizer(vocabulary=vocab)
|
78
|
-
preprocessor = keras_hub.models.ElectraPreprocessor(tokenizer)
|
79
|
-
preprocessor("The quick brown fox jumped.")
|
80
|
-
```
|
81
|
-
|
82
|
-
Mapping with `tf.data.Dataset`.
|
83
|
-
```python
|
84
|
-
preprocessor = keras_hub.models.ElectraPreprocessor.from_preset(
|
85
|
-
"electra_base_discriminator_en"
|
86
|
-
)
|
87
|
-
|
88
|
-
first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
|
89
|
-
second = tf.constant(["The fox tripped.", "Oh look, a whale."])
|
90
|
-
label = tf.constant([1, 1])
|
91
|
-
# Map labeled single sentences.
|
92
|
-
ds = tf.data.Dataset.from_tensor_slices((first, label))
|
93
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
94
|
-
|
95
|
-
|
96
|
-
# Map unlabeled single sentences.
|
97
|
-
ds = tf.data.Dataset.from_tensor_slices(first)
|
98
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
99
|
-
|
100
|
-
# Map labeled sentence pairs.
|
101
|
-
ds = tf.data.Dataset.from_tensor_slices(((first, second), label))
|
102
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
103
|
-
# Map unlabeled sentence pairs.
|
104
|
-
ds = tf.data.Dataset.from_tensor_slices((first, second))
|
105
|
-
|
106
|
-
# Watch out for tf.data's default unpacking of tuples here!
|
107
|
-
# Best to invoke the `preprocessor` directly in this case.
|
108
|
-
ds = ds.map(
|
109
|
-
lambda first, second: preprocessor(x=(first, second)),
|
110
|
-
num_parallel_calls=tf.data.AUTOTUNE,
|
111
|
-
)
|
112
|
-
```
|
113
|
-
"""
|
114
|
-
|
115
|
-
backbone_cls = ElectraBackbone
|
116
|
-
tokenizer_cls = ElectraTokenizer
|
117
|
-
|
118
|
-
def __init__(
|
119
|
-
self,
|
120
|
-
tokenizer,
|
121
|
-
sequence_length=512,
|
122
|
-
truncate="round_robin",
|
123
|
-
**kwargs,
|
124
|
-
):
|
125
|
-
super().__init__(**kwargs)
|
126
|
-
self.tokenizer = tokenizer
|
127
|
-
self.packer = MultiSegmentPacker(
|
128
|
-
start_value=self.tokenizer.cls_token_id,
|
129
|
-
end_value=self.tokenizer.sep_token_id,
|
130
|
-
pad_value=self.tokenizer.pad_token_id,
|
131
|
-
truncate=truncate,
|
132
|
-
sequence_length=sequence_length,
|
133
|
-
)
|
134
|
-
|
135
|
-
def get_config(self):
|
136
|
-
config = super().get_config()
|
137
|
-
config.update(
|
138
|
-
{
|
139
|
-
"sequence_length": self.packer.sequence_length,
|
140
|
-
"truncate": self.packer.truncate,
|
141
|
-
}
|
142
|
-
)
|
143
|
-
return config
|
144
|
-
|
145
|
-
@preprocessing_function
|
146
|
-
def call(self, x, y=None, sample_weight=None):
|
147
|
-
x = x if isinstance(x, tuple) else (x,)
|
148
|
-
x = tuple(self.tokenizer(segment) for segment in x)
|
149
|
-
token_ids, segment_ids = self.packer(x)
|
150
|
-
x = {
|
151
|
-
"token_ids": token_ids,
|
152
|
-
"segment_ids": segment_ids,
|
153
|
-
"padding_mask": token_ids != self.tokenizer.pad_token_id,
|
154
|
-
}
|
155
|
-
return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
|
@@ -1,180 +0,0 @@
|
|
1
|
-
# Copyright 2024 The KerasHub Authors
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# https://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
|
15
|
-
|
16
|
-
import keras
|
17
|
-
|
18
|
-
from keras_hub.src.api_export import keras_hub_export
|
19
|
-
from keras_hub.src.layers.preprocessing.start_end_packer import StartEndPacker
|
20
|
-
from keras_hub.src.models.falcon.falcon_backbone import FalconBackbone
|
21
|
-
from keras_hub.src.models.falcon.falcon_tokenizer import FalconTokenizer
|
22
|
-
from keras_hub.src.models.preprocessor import Preprocessor
|
23
|
-
from keras_hub.src.utils.tensor_utils import preprocessing_function
|
24
|
-
|
25
|
-
|
26
|
-
@keras_hub_export("keras_hub.models.FalconPreprocessor")
|
27
|
-
class FalconPreprocessor(Preprocessor):
|
28
|
-
"""Falcon preprocessing layer which tokenizes and packs inputs.
|
29
|
-
|
30
|
-
This preprocessing layer will do 2 things:
|
31
|
-
|
32
|
-
- Tokenize the inputs using the `tokenizer`.
|
33
|
-
- Construct a dictionary with keys `"token_ids"`, `"padding_mask"`, that can
|
34
|
-
be passed directly to a `keras_hub.models.FalconBackbone`.
|
35
|
-
|
36
|
-
This layer can be used directly with `tf.data.Dataset.map` to preprocess
|
37
|
-
string data in the `(x, y, sample_weight)` format used by
|
38
|
-
`keras.Model.fit`.
|
39
|
-
|
40
|
-
The call method of this layer accepts three arguments, `x`, `y`, and
|
41
|
-
`sample_weight`. `x` can be a python string or tensor representing a single
|
42
|
-
segment, a list of python strings representing a batch of single segments,
|
43
|
-
or a list of tensors representing multiple segments to be packed together.
|
44
|
-
`y` and `sample_weight` are both optional, can have any format, and will be
|
45
|
-
passed through unaltered.
|
46
|
-
|
47
|
-
`FalconPreprocessor` forces the input to have only one segment, as Falcon is
|
48
|
-
mainly used for generation tasks. For tasks having multi-segment inputs
|
49
|
-
like "glue/mnli", please use a model designed for classification purposes
|
50
|
-
such as BERT or RoBERTa.
|
51
|
-
|
52
|
-
Args:
|
53
|
-
tokenizer: A `keras_hub.models.FalconTokenizer` instance.
|
54
|
-
sequence_length: The length of the packed inputs.
|
55
|
-
add_start_token: If `True`, the preprocessor will prepend the tokenizer
|
56
|
-
start token to each input sequence.
|
57
|
-
add_end_token: If `True`, the preprocessor will append the tokenizer
|
58
|
-
end token to each input sequence.
|
59
|
-
|
60
|
-
Call arguments:
|
61
|
-
x: A string, `tf.Tensor` or list of python strings.
|
62
|
-
y: Any label data. Will be passed through unaltered.
|
63
|
-
sample_weight: Any label weight data. Will be passed through unaltered.
|
64
|
-
sequence_length: Pass to override the configured `sequence_length` of
|
65
|
-
the layer.
|
66
|
-
|
67
|
-
Examples:
|
68
|
-
|
69
|
-
Directly calling the layer on data.
|
70
|
-
```python
|
71
|
-
preprocessor = keras_hub.models.FalconPreprocessor.from_preset("falcon_rw_1b")
|
72
|
-
|
73
|
-
# Tokenize and pack a single sentence.
|
74
|
-
preprocessor("The quick brown fox jumped.")
|
75
|
-
|
76
|
-
# Tokenize a batch of single sentences.
|
77
|
-
preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
|
78
|
-
|
79
|
-
# Custom vocabulary.
|
80
|
-
features = ["a quick fox.", "a fox quick."]
|
81
|
-
vocab = {"<|endoftext|>": 0, "a": 4, "Ġquick": 5, "Ġfox": 6}
|
82
|
-
merges = ["Ġ q", "u i", "c k", "ui ck", "Ġq uick"]
|
83
|
-
merges += ["Ġ f", "o x", "Ġf ox"]
|
84
|
-
tokenizer = keras_hub.models.FalconTokenizer(
|
85
|
-
vocabulary=vocab,
|
86
|
-
merges=merges,
|
87
|
-
)
|
88
|
-
preprocessor = keras_hub.models.FalconPreprocessor(tokenizer=tokenizer)
|
89
|
-
preprocessor("The quick brown fox jumped.")
|
90
|
-
```
|
91
|
-
|
92
|
-
Mapping with `tf.data.Dataset`.
|
93
|
-
```python
|
94
|
-
preprocessor = keras_hub.models.FalconPreprocessor.from_preset("falcon_rw_1b")
|
95
|
-
|
96
|
-
text = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
|
97
|
-
label = tf.constant([1, 1])
|
98
|
-
|
99
|
-
# Map labeled single sentences.
|
100
|
-
ds = tf.data.Dataset.from_tensor_slices((text, label))
|
101
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
102
|
-
|
103
|
-
# Map unlabeled single sentences.
|
104
|
-
ds = tf.data.Dataset.from_tensor_slices(text)
|
105
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
106
|
-
```
|
107
|
-
"""
|
108
|
-
|
109
|
-
backbone_cls = FalconBackbone
|
110
|
-
tokenizer_cls = FalconTokenizer
|
111
|
-
|
112
|
-
def __init__(
|
113
|
-
self,
|
114
|
-
tokenizer,
|
115
|
-
sequence_length=1024,
|
116
|
-
add_start_token=True,
|
117
|
-
add_end_token=True,
|
118
|
-
**kwargs,
|
119
|
-
):
|
120
|
-
super().__init__(**kwargs)
|
121
|
-
self.tokenizer = tokenizer
|
122
|
-
self.packer = None
|
123
|
-
self.sequence_length = sequence_length
|
124
|
-
self.add_start_token = add_start_token
|
125
|
-
self.add_end_token = add_end_token
|
126
|
-
|
127
|
-
def build(self, input_shape):
|
128
|
-
# Defer packer creation to `build()` so that we can be sure tokenizer
|
129
|
-
# assets have loaded when restoring a saved model.
|
130
|
-
self.packer = StartEndPacker(
|
131
|
-
start_value=self.tokenizer.start_token_id,
|
132
|
-
end_value=self.tokenizer.end_token_id,
|
133
|
-
pad_value=self.tokenizer.pad_token_id,
|
134
|
-
sequence_length=self.sequence_length,
|
135
|
-
return_padding_mask=True,
|
136
|
-
)
|
137
|
-
self.built = True
|
138
|
-
|
139
|
-
@preprocessing_function
|
140
|
-
def call(
|
141
|
-
self,
|
142
|
-
x,
|
143
|
-
y=None,
|
144
|
-
sample_weight=None,
|
145
|
-
sequence_length=None,
|
146
|
-
):
|
147
|
-
sequence_length = sequence_length or self.sequence_length
|
148
|
-
token_ids, padding_mask = self.packer(
|
149
|
-
self.tokenizer(x),
|
150
|
-
sequence_length=sequence_length,
|
151
|
-
add_start_value=self.add_start_token,
|
152
|
-
add_end_value=self.add_end_token,
|
153
|
-
)
|
154
|
-
x = {
|
155
|
-
"token_ids": token_ids,
|
156
|
-
"padding_mask": padding_mask,
|
157
|
-
}
|
158
|
-
return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
|
159
|
-
|
160
|
-
def get_config(self):
|
161
|
-
config = super().get_config()
|
162
|
-
config.update(
|
163
|
-
{
|
164
|
-
"sequence_length": self.sequence_length,
|
165
|
-
"add_start_token": self.add_start_token,
|
166
|
-
"add_end_token": self.add_end_token,
|
167
|
-
}
|
168
|
-
)
|
169
|
-
return config
|
170
|
-
|
171
|
-
@property
|
172
|
-
def sequence_length(self):
|
173
|
-
"""The padded length of model input sequences."""
|
174
|
-
return self._sequence_length
|
175
|
-
|
176
|
-
@sequence_length.setter
|
177
|
-
def sequence_length(self, value):
|
178
|
-
self._sequence_length = value
|
179
|
-
if self.packer is not None:
|
180
|
-
self.packer.sequence_length = value
|
@@ -1,184 +0,0 @@
|
|
1
|
-
# Copyright 2024 The KerasHub Authors
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# https://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
|
15
|
-
|
16
|
-
import keras
|
17
|
-
|
18
|
-
from keras_hub.src.api_export import keras_hub_export
|
19
|
-
from keras_hub.src.layers.preprocessing.start_end_packer import StartEndPacker
|
20
|
-
from keras_hub.src.models.gemma.gemma_backbone import GemmaBackbone
|
21
|
-
from keras_hub.src.models.gemma.gemma_tokenizer import GemmaTokenizer
|
22
|
-
from keras_hub.src.models.preprocessor import Preprocessor
|
23
|
-
from keras_hub.src.utils.tensor_utils import preprocessing_function
|
24
|
-
|
25
|
-
|
26
|
-
@keras_hub_export("keras_hub.models.GemmaPreprocessor")
|
27
|
-
class GemmaPreprocessor(Preprocessor):
|
28
|
-
"""Gemma preprocessing layer which tokenizes and packs inputs.
|
29
|
-
|
30
|
-
This preprocessing layer will do 2 things:
|
31
|
-
|
32
|
-
- Tokenize the inputs using the `tokenizer`.
|
33
|
-
- Construct a dictionary with keys `"token_ids"`, `"padding_mask"`, that can
|
34
|
-
be passed directly to a `keras_hub.models.GemmaBackbone`.
|
35
|
-
|
36
|
-
This layer can be used directly with `tf.data.Dataset.map` to preprocess
|
37
|
-
string data in the `(x, y, sample_weight)` format used by
|
38
|
-
`keras.Model.fit`.
|
39
|
-
|
40
|
-
The call method of this layer accepts three arguments, `x`, `y`, and
|
41
|
-
`sample_weight`. `x` can be a python string or tensor representing a single
|
42
|
-
segment, a list of python strings representing a batch of single segments,
|
43
|
-
or a list of tensors representing multiple segments to be packed together.
|
44
|
-
`y` and `sample_weight` are both optional, can have any format, and will be
|
45
|
-
passed through unaltered.
|
46
|
-
|
47
|
-
`GemmaPreprocessor` expects the input to have only one segment, as Gemma is
|
48
|
-
mainly used for generation tasks. For tasks having multi-segment inputs
|
49
|
-
please combine inputs into a single string input before passing to the
|
50
|
-
preprocessor layer.
|
51
|
-
|
52
|
-
Args:
|
53
|
-
tokenizer: A `keras_hub.models.GemmaTokenizer` instance.
|
54
|
-
sequence_length: The length of the packed inputs.
|
55
|
-
add_start_token: If `True`, the preprocessor will prepend the tokenizer
|
56
|
-
start token to each input sequence.
|
57
|
-
add_end_token: If `True`, the preprocessor will append the tokenizer
|
58
|
-
end token to each input sequence.
|
59
|
-
|
60
|
-
Call arguments:
|
61
|
-
x: A string, `tf.Tensor` or list of python strings.
|
62
|
-
y: Any label data. Will be passed through unaltered.
|
63
|
-
sample_weight: Any label weight data. Will be passed through unaltered.
|
64
|
-
sequence_length: Pass to override the configured `sequence_length` of
|
65
|
-
the layer.
|
66
|
-
|
67
|
-
Examples:
|
68
|
-
|
69
|
-
Directly calling the layer on data.
|
70
|
-
```python
|
71
|
-
preprocessor = keras_hub.models.GemmaPreprocessor.from_preset(
|
72
|
-
"gemma_2b_en"
|
73
|
-
)
|
74
|
-
|
75
|
-
# Tokenize and pack a single sentence.
|
76
|
-
preprocessor("The quick brown fox jumped.")
|
77
|
-
|
78
|
-
# Tokenize a batch of sentences.
|
79
|
-
preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
|
80
|
-
|
81
|
-
# Custom vocabulary.
|
82
|
-
bytes_io = io.BytesIO()
|
83
|
-
ds = tf.data.Dataset.from_tensor_slices(["The quick brown fox jumped."])
|
84
|
-
sentencepiece.SentencePieceTrainer.train(
|
85
|
-
sentence_iterator=ds.as_numpy_iterator(),
|
86
|
-
model_writer=bytes_io,
|
87
|
-
vocab_size=8,
|
88
|
-
model_type="WORD",
|
89
|
-
pad_id=0,
|
90
|
-
bos_id=1,
|
91
|
-
eos_id=2,
|
92
|
-
unk_id=3,
|
93
|
-
pad_piece="<pad>",
|
94
|
-
bos_piece="<bos>",
|
95
|
-
eos_piece="<eos>",
|
96
|
-
unk_piece="<unk>",
|
97
|
-
)
|
98
|
-
tokenizer = keras_hub.models.GemmaTokenizer(
|
99
|
-
proto=bytes_io.getvalue(),
|
100
|
-
)
|
101
|
-
preprocessor = keras_hub.models.GemmaPreprocessor(tokenizer=tokenizer)
|
102
|
-
preprocessor("The quick brown fox jumped.")
|
103
|
-
```
|
104
|
-
|
105
|
-
Apply preprocessing to a `tf.data.Dataset`.
|
106
|
-
```python
|
107
|
-
preprocessor = keras_hub.models.GemmaPreprocessor.from_preset(
|
108
|
-
"gemma_2b_en"
|
109
|
-
)
|
110
|
-
|
111
|
-
text = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
|
112
|
-
label = tf.constant([1, 1])
|
113
|
-
|
114
|
-
# Map labeled single sentences.
|
115
|
-
ds = tf.data.Dataset.from_tensor_slices((text, label))
|
116
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
117
|
-
|
118
|
-
# Map unlabeled single sentences.
|
119
|
-
ds = tf.data.Dataset.from_tensor_slices(text)
|
120
|
-
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
|
121
|
-
```
|
122
|
-
"""
|
123
|
-
|
124
|
-
backbone_cls = GemmaBackbone
|
125
|
-
tokenizer_cls = GemmaTokenizer
|
126
|
-
|
127
|
-
def __init__(
|
128
|
-
self,
|
129
|
-
tokenizer,
|
130
|
-
sequence_length=1024,
|
131
|
-
add_start_token=True,
|
132
|
-
add_end_token=True,
|
133
|
-
**kwargs,
|
134
|
-
):
|
135
|
-
super().__init__(**kwargs)
|
136
|
-
|
137
|
-
self.tokenizer = tokenizer
|
138
|
-
self.sequence_length = sequence_length
|
139
|
-
self.add_start_token = add_start_token
|
140
|
-
self.add_end_token = add_end_token
|
141
|
-
|
142
|
-
def build(self, input_shape):
|
143
|
-
# Defer packer creation to `build()` so that we can be sure tokenizer
|
144
|
-
# assets have loaded when restoring a saved model.
|
145
|
-
self.packer = StartEndPacker(
|
146
|
-
start_value=self.tokenizer.start_token_id,
|
147
|
-
end_value=self.tokenizer.end_token_id,
|
148
|
-
pad_value=self.tokenizer.pad_token_id,
|
149
|
-
sequence_length=self.sequence_length,
|
150
|
-
return_padding_mask=True,
|
151
|
-
)
|
152
|
-
self.built = True
|
153
|
-
|
154
|
-
@preprocessing_function
|
155
|
-
def call(
|
156
|
-
self,
|
157
|
-
x,
|
158
|
-
y=None,
|
159
|
-
sample_weight=None,
|
160
|
-
sequence_length=None,
|
161
|
-
):
|
162
|
-
sequence_length = sequence_length or self.sequence_length
|
163
|
-
token_ids, padding_mask = self.packer(
|
164
|
-
self.tokenizer(x),
|
165
|
-
sequence_length=sequence_length,
|
166
|
-
add_start_value=self.add_start_token,
|
167
|
-
add_end_value=self.add_end_token,
|
168
|
-
)
|
169
|
-
x = {
|
170
|
-
"token_ids": token_ids,
|
171
|
-
"padding_mask": padding_mask,
|
172
|
-
}
|
173
|
-
return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
|
174
|
-
|
175
|
-
def get_config(self):
|
176
|
-
config = super().get_config()
|
177
|
-
config.update(
|
178
|
-
{
|
179
|
-
"sequence_length": self.sequence_length,
|
180
|
-
"add_start_token": self.add_start_token,
|
181
|
-
"add_end_token": self.add_end_token,
|
182
|
-
}
|
183
|
-
)
|
184
|
-
return config
|