keras-hub-nightly 0.15.0.dev20240911134614__py3-none-any.whl → 0.16.0.dev20240915160609__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.
Files changed (36) hide show
  1. keras_hub/api/models/__init__.py +22 -17
  2. keras_hub/src/models/albert/albert_text_classifier.py +6 -1
  3. keras_hub/src/models/bert/bert_text_classifier.py +6 -1
  4. keras_hub/src/models/deberta_v3/deberta_v3_text_classifier.py +6 -1
  5. keras_hub/src/models/distil_bert/distil_bert_text_classifier.py +6 -1
  6. keras_hub/src/models/f_net/f_net_text_classifier.py +6 -1
  7. keras_hub/src/models/gpt2/gpt2_preprocessor.py +7 -78
  8. keras_hub/src/models/pali_gemma/pali_gemma_tokenizer.py +1 -1
  9. keras_hub/src/models/preprocessor.py +1 -5
  10. keras_hub/src/models/resnet/resnet_backbone.py +3 -16
  11. keras_hub/src/models/resnet/resnet_image_classifier.py +17 -0
  12. keras_hub/src/models/resnet/resnet_presets.py +12 -12
  13. keras_hub/src/models/roberta/roberta_text_classifier.py +6 -1
  14. keras_hub/src/models/task.py +6 -6
  15. keras_hub/src/models/text_classifier.py +12 -1
  16. keras_hub/src/models/xlm_roberta/xlm_roberta_text_classifier.py +6 -1
  17. keras_hub/src/tests/test_case.py +13 -0
  18. keras_hub/src/utils/preset_utils.py +14 -32
  19. keras_hub/src/utils/timm/convert_resnet.py +0 -1
  20. keras_hub/src/utils/timm/preset_loader.py +6 -7
  21. keras_hub/src/version_utils.py +1 -1
  22. {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev20240915160609.dist-info}/METADATA +1 -1
  23. {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev20240915160609.dist-info}/RECORD +25 -36
  24. {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev20240915160609.dist-info}/WHEEL +1 -1
  25. keras_hub/src/models/bart/bart_preprocessor.py +0 -264
  26. keras_hub/src/models/bloom/bloom_preprocessor.py +0 -178
  27. keras_hub/src/models/electra/electra_preprocessor.py +0 -155
  28. keras_hub/src/models/falcon/falcon_preprocessor.py +0 -180
  29. keras_hub/src/models/gemma/gemma_preprocessor.py +0 -184
  30. keras_hub/src/models/gpt_neo_x/gpt_neo_x_preprocessor.py +0 -138
  31. keras_hub/src/models/llama/llama_preprocessor.py +0 -182
  32. keras_hub/src/models/llama3/llama3_preprocessor.py +0 -23
  33. keras_hub/src/models/mistral/mistral_preprocessor.py +0 -183
  34. keras_hub/src/models/opt/opt_preprocessor.py +0 -181
  35. keras_hub/src/models/phi3/phi3_preprocessor.py +0 -183
  36. {keras_hub_nightly-0.15.0.dev20240911134614.dist-info → keras_hub_nightly-0.16.0.dev20240915160609.dist-info}/top_level.txt +0 -0
@@ -1,264 +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.bart.bart_backbone import BartBackbone
21
- from keras_hub.src.models.bart.bart_tokenizer import BartTokenizer
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.BartPreprocessor")
27
- class BartPreprocessor(Preprocessor):
28
- """A BART preprocessing layer which tokenizes and packs inputs.
29
-
30
- This preprocessing layer will do three things:
31
-
32
- 1. Tokenize both encoder inputs and decoder inputs using the `tokenizer`.
33
- Both inputs can contain only one segment.
34
- 2. Add the appropriate special tokens - `"<s>"`, `"</s>"` and `"<pad>"`.
35
- 3. Construct a dictionary with keys `"encoder_token_ids"`,
36
- `"encoder_padding_mask"`, `"decoder_token_ids"`, `"decoder_padding_mask"`
37
- that can be passed directly to a BART model.
38
-
39
- Args:
40
- tokenizer: A `keras_hub.models.BartTokenizer` instance.
41
- encoder_sequence_length: The length of the packed encoder inputs.
42
- decoder_sequence_length: The length of the packed decoder inputs.
43
-
44
- Call arguments:
45
- x: A dictionary with `encoder_text` and `decoder_text` as its keys.
46
- Each value in the dictionary should be a tensor of single string
47
- sequences. Inputs may be batched or unbatched. Raw python inputs
48
- will be converted to tensors.
49
- y: Any label data. Will be passed through unaltered.
50
- sample_weight: Any label weight data. Will be passed through unaltered.
51
-
52
- Examples:
53
-
54
- Directly calling the layer on data.
55
- ```python
56
- preprocessor = keras_hub.models.BartPreprocessor.from_preset("bart_base_en")
57
-
58
- # Preprocess unbatched inputs.
59
- inputs = {
60
- "encoder_text": "The fox was sleeping.",
61
- "decoder_text": "The fox was awake."
62
- }
63
- preprocessor(inputs)
64
-
65
- # Preprocess batched inputs.
66
- inputs = {
67
- "encoder_text": ["The fox was sleeping.", "The lion was quiet."],
68
- "decoder_text": ["The fox was awake.", "The lion was roaring."]
69
- }
70
- preprocessor(inputs)
71
-
72
- # Custom vocabulary.
73
- vocab = {
74
- "<s>": 0,
75
- "<pad>": 1,
76
- "</s>": 2,
77
- "Ġafter": 5,
78
- "noon": 6,
79
- "Ġsun": 7,
80
- }
81
- merges = ["Ġ a", "Ġ s", "Ġ n", "e r", "n o", "o n", "Ġs u", "Ġa f", "no on"]
82
- merges += ["Ġsu n", "Ġaf t", "Ġaft er"]
83
-
84
- tokenizer = keras_hub.models.BartTokenizer(
85
- vocabulary=vocab,
86
- merges=merges,
87
- )
88
- preprocessor = keras_hub.models.BartPreprocessor(
89
- tokenizer=tokenizer,
90
- encoder_sequence_length=20,
91
- decoder_sequence_length=10,
92
- )
93
- inputs = {
94
- "encoder_text": "The fox was sleeping.",
95
- "decoder_text": "The fox was awake."
96
- }
97
- preprocessor(inputs)
98
- ```
99
-
100
- Mapping with `tf.data.Dataset`.
101
- ```python
102
- preprocessor = keras_hub.models.BartPreprocessor.from_preset("bart_base_en")
103
-
104
- # Map labeled single sentences.
105
- features = {
106
- "encoder_text": tf.constant(
107
- ["The fox was sleeping.", "The lion was quiet."]
108
- ),
109
- "decoder_text": tf.constant(
110
- ["The fox was awake.", "The lion was silent."]
111
- )
112
- }
113
- labels = tf.constant(["True", "False"])
114
- ds = tf.data.Dataset.from_tensor_slices((features, labels))
115
- ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
116
-
117
- # Map unlabeled single sentences.
118
- features = {
119
- "encoder_text": tf.constant(
120
- ["The fox was sleeping.", "The lion was quiet."]
121
- ),
122
- "decoder_text": tf.constant(
123
- ["The fox was awake.", "The lion was roaring."]
124
- )
125
- }
126
- ds = tf.data.Dataset.from_tensor_slices(features)
127
- ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
128
- ```
129
- """
130
-
131
- backbone_cls = BartBackbone
132
- tokenizer_cls = BartTokenizer
133
-
134
- def __init__(
135
- self,
136
- tokenizer,
137
- encoder_sequence_length=1024,
138
- decoder_sequence_length=1024,
139
- **kwargs,
140
- ):
141
- super().__init__(**kwargs)
142
- self.tokenizer = tokenizer
143
- self.encoder_packer = None
144
- self.decoder_packer = None
145
- self.encoder_sequence_length = encoder_sequence_length
146
- self.decoder_sequence_length = decoder_sequence_length
147
-
148
- def build(self, input_shape):
149
- # Defer packer creation to `build()` so that we can be sure tokenizer
150
- # assets have loaded when restoring a saved model.
151
-
152
- # TODO: Use `MultiSegmentPacker` instead of `StartEndPacker` once we
153
- # want to move to multi-segment packing and have improved
154
- # `MultiSegmentPacker`'s performance.
155
- self.encoder_packer = StartEndPacker(
156
- start_value=self.tokenizer.start_token_id,
157
- end_value=self.tokenizer.end_token_id,
158
- pad_value=self.tokenizer.pad_token_id,
159
- sequence_length=self.encoder_sequence_length,
160
- return_padding_mask=True,
161
- )
162
-
163
- # The decoder is packed a bit differently; the format is as follows:
164
- # `[end_token_id, start_token_id, tokens..., end_token_id, padding...]`.
165
- self.decoder_packer = StartEndPacker(
166
- start_value=[
167
- self.tokenizer.end_token_id,
168
- self.tokenizer.start_token_id,
169
- ],
170
- end_value=self.tokenizer.end_token_id,
171
- pad_value=self.tokenizer.pad_token_id,
172
- sequence_length=self.decoder_sequence_length,
173
- return_padding_mask=True,
174
- )
175
- self.built = True
176
-
177
- @preprocessing_function
178
- def call(
179
- self,
180
- x,
181
- y=None,
182
- sample_weight=None,
183
- *,
184
- encoder_sequence_length=None,
185
- decoder_sequence_length=None,
186
- # `sequence_length` is an alias for `decoder_sequence_length`
187
- sequence_length=None,
188
- ):
189
- if not (
190
- isinstance(x, dict)
191
- and all(k in x for k in ("encoder_text", "decoder_text"))
192
- ):
193
- raise ValueError(
194
- '`x` must be a dictionary, containing the keys `"encoder_text"`'
195
- f' and `"decoder_text"`. Received x={x}.'
196
- )
197
-
198
- if encoder_sequence_length is None:
199
- encoder_sequence_length = self.encoder_sequence_length
200
- decoder_sequence_length = decoder_sequence_length or sequence_length
201
- if decoder_sequence_length is None:
202
- decoder_sequence_length = self.decoder_sequence_length
203
-
204
- encoder_inputs = self.tokenizer(x["encoder_text"])
205
- encoder_token_ids, encoder_padding_mask = self.encoder_packer(
206
- encoder_inputs,
207
- sequence_length=encoder_sequence_length,
208
- )
209
-
210
- decoder_inputs = self.tokenizer(x["decoder_text"])
211
- decoder_token_ids, decoder_padding_mask = self.decoder_packer(
212
- decoder_inputs,
213
- sequence_length=decoder_sequence_length,
214
- )
215
-
216
- x = {
217
- "encoder_token_ids": encoder_token_ids,
218
- "encoder_padding_mask": encoder_padding_mask,
219
- "decoder_token_ids": decoder_token_ids,
220
- "decoder_padding_mask": decoder_padding_mask,
221
- }
222
-
223
- return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
224
-
225
- def get_config(self):
226
- config = super().get_config()
227
- config.update(
228
- {
229
- "encoder_sequence_length": self.encoder_sequence_length,
230
- "decoder_sequence_length": self.decoder_sequence_length,
231
- }
232
- )
233
- return config
234
-
235
- @property
236
- def encoder_sequence_length(self):
237
- """The padded length of encoder input sequences."""
238
- return self._encoder_sequence_length
239
-
240
- @encoder_sequence_length.setter
241
- def encoder_sequence_length(self, value):
242
- self._encoder_sequence_length = value
243
- if self.encoder_packer is not None:
244
- self.encoder_packer.sequence_length = value
245
-
246
- @property
247
- def decoder_sequence_length(self):
248
- """The padded length of decoder input sequences."""
249
- return self._decoder_sequence_length
250
-
251
- @decoder_sequence_length.setter
252
- def decoder_sequence_length(self, value):
253
- self._decoder_sequence_length = value
254
- if self.decoder_packer is not None:
255
- self.decoder_packer.sequence_length = value
256
-
257
- @property
258
- def sequence_length(self):
259
- """Alias for `decoder_sequence_length`."""
260
- return self.decoder_sequence_length
261
-
262
- @sequence_length.setter
263
- def sequence_length(self, value):
264
- self.decoder_sequence_length = value
@@ -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)