keras-hub 0.21.1.dev0__py3-none-any.whl → 0.22.0.dev0__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 (94) hide show
  1. keras_hub/layers/__init__.py +9 -0
  2. keras_hub/models/__init__.py +47 -0
  3. keras_hub/src/layers/modeling/transformer_encoder.py +6 -3
  4. keras_hub/src/layers/preprocessing/multi_segment_packer.py +17 -3
  5. keras_hub/src/layers/preprocessing/start_end_packer.py +24 -6
  6. keras_hub/src/models/backbone.py +13 -10
  7. keras_hub/src/models/clip/clip_backbone.py +3 -102
  8. keras_hub/src/models/clip/clip_layers.py +295 -0
  9. keras_hub/src/models/clip/clip_preprocessor.py +57 -48
  10. keras_hub/src/models/clip/clip_text_encoder.py +2 -2
  11. keras_hub/src/models/clip/clip_vision_encoder.py +3 -3
  12. keras_hub/src/models/deit/__init__.py +5 -0
  13. keras_hub/src/models/deit/deit_backbone.py +154 -0
  14. keras_hub/src/models/deit/deit_image_classifier.py +171 -0
  15. keras_hub/src/models/deit/deit_image_classifier_preprocessor.py +12 -0
  16. keras_hub/src/models/deit/deit_image_converter.py +8 -0
  17. keras_hub/src/models/deit/deit_layers.py +519 -0
  18. keras_hub/src/models/deit/deit_presets.py +49 -0
  19. keras_hub/src/models/dinov2/__init__.py +5 -0
  20. keras_hub/src/models/dinov2/dinov2_backbone.py +228 -0
  21. keras_hub/src/models/dinov2/dinov2_image_converter.py +8 -0
  22. keras_hub/src/models/dinov2/dinov2_layers.py +886 -0
  23. keras_hub/src/models/dinov2/dinov2_presets.py +89 -0
  24. keras_hub/src/models/esm/__init__.py +5 -0
  25. keras_hub/src/models/esm/esm_attention.py +95 -0
  26. keras_hub/src/models/esm/esm_backbone.py +229 -0
  27. keras_hub/src/models/esm/esm_classifier.py +184 -0
  28. keras_hub/src/models/esm/esm_classifier_preprocessor.py +135 -0
  29. keras_hub/src/models/esm/esm_encoder.py +134 -0
  30. keras_hub/src/models/esm/esm_masked_plm.py +117 -0
  31. keras_hub/src/models/esm/esm_masked_plm_preprocessor.py +143 -0
  32. keras_hub/src/models/esm/esm_presets.py +53 -0
  33. keras_hub/src/models/esm/esm_tokenizer.py +82 -0
  34. keras_hub/src/models/flux/flux_text_to_image_preprocessor.py +6 -2
  35. keras_hub/src/models/gemma/gemma_attention.py +1 -1
  36. keras_hub/src/models/gemma3/gemma3_backbone.py +2 -2
  37. keras_hub/src/models/gemma3/gemma3_interleave_embeddings.py +1 -1
  38. keras_hub/src/models/hgnetv2/__init__.py +5 -0
  39. keras_hub/src/models/hgnetv2/hgnetv2_backbone.py +193 -0
  40. keras_hub/src/models/hgnetv2/hgnetv2_encoder.py +148 -0
  41. keras_hub/src/models/hgnetv2/hgnetv2_image_classifier.py +216 -0
  42. keras_hub/src/models/hgnetv2/hgnetv2_image_classifier_preprocessor.py +14 -0
  43. keras_hub/src/models/hgnetv2/hgnetv2_image_converter.py +8 -0
  44. keras_hub/src/models/hgnetv2/hgnetv2_layers.py +918 -0
  45. keras_hub/src/models/hgnetv2/hgnetv2_presets.py +58 -0
  46. keras_hub/src/models/llama3/llama3_presets.py +3 -3
  47. keras_hub/src/models/mistral/mistral_presets.py +17 -1
  48. keras_hub/src/models/mixtral/mixtral_presets.py +2 -2
  49. keras_hub/src/models/mobilenet/mobilenet_presets.py +4 -4
  50. keras_hub/src/models/pali_gemma/pali_gemma_backbone.py +2 -2
  51. keras_hub/src/models/pali_gemma/pali_gemma_causal_lm.py +2 -2
  52. keras_hub/src/models/pali_gemma/pali_gemma_presets.py +17 -17
  53. keras_hub/src/models/qwen3/__init__.py +5 -0
  54. keras_hub/src/models/qwen3/qwen3_attention.py +369 -0
  55. keras_hub/src/models/qwen3/qwen3_backbone.py +191 -0
  56. keras_hub/src/models/qwen3/qwen3_causal_lm.py +390 -0
  57. keras_hub/src/models/qwen3/qwen3_causal_lm_preprocessor.py +10 -0
  58. keras_hub/src/models/qwen3/qwen3_decoder.py +309 -0
  59. keras_hub/src/models/qwen3/qwen3_layernorm.py +38 -0
  60. keras_hub/src/models/qwen3/qwen3_presets.py +73 -0
  61. keras_hub/src/models/qwen3/qwen3_tokenizer.py +48 -0
  62. keras_hub/src/models/qwen_moe/qwen_moe_attention.py +1 -0
  63. keras_hub/src/models/qwen_moe/qwen_moe_presets.py +2 -2
  64. keras_hub/src/models/roformer_v2/roformer_v2_attention.py +0 -2
  65. keras_hub/src/models/stable_diffusion_3/flow_match_euler_discrete_scheduler.py +16 -7
  66. keras_hub/src/models/stable_diffusion_3/mmdit.py +61 -4
  67. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_backbone.py +31 -32
  68. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_image_to_image.py +1 -0
  69. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_inpaint.py +1 -0
  70. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_text_to_image.py +1 -0
  71. keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_text_to_image_preprocessor.py +6 -2
  72. keras_hub/src/models/vit/vit_backbone.py +31 -11
  73. keras_hub/src/models/vit/vit_image_converter.py +0 -70
  74. keras_hub/src/models/vit/vit_layers.py +33 -18
  75. keras_hub/src/models/vit/vit_presets.py +11 -11
  76. keras_hub/src/utils/keras_utils.py +17 -0
  77. keras_hub/src/utils/preset_utils.py +19 -4
  78. keras_hub/src/utils/tensor_utils.py +14 -0
  79. keras_hub/src/utils/transformers/convert_deit.py +155 -0
  80. keras_hub/src/utils/transformers/convert_dinov2.py +180 -0
  81. keras_hub/src/utils/transformers/convert_esm.py +159 -0
  82. keras_hub/src/utils/transformers/convert_llama3.py +6 -0
  83. keras_hub/src/utils/transformers/convert_qwen3.py +145 -0
  84. keras_hub/src/utils/transformers/export/gemma.py +89 -0
  85. keras_hub/src/utils/transformers/export/hf_exporter.py +98 -0
  86. keras_hub/src/utils/transformers/preset_loader.py +14 -2
  87. keras_hub/src/version.py +1 -1
  88. keras_hub/tokenizers/__init__.py +1 -0
  89. {keras_hub-0.21.1.dev0.dist-info → keras_hub-0.22.0.dev0.dist-info}/METADATA +4 -4
  90. {keras_hub-0.21.1.dev0.dist-info → keras_hub-0.22.0.dev0.dist-info}/RECORD +92 -48
  91. keras_hub/src/models/clip/clip_encoder_block.py +0 -111
  92. keras_hub/src/models/clip/clip_vision_embedding.py +0 -101
  93. {keras_hub-0.21.1.dev0.dist-info → keras_hub-0.22.0.dev0.dist-info}/WHEEL +0 -0
  94. {keras_hub-0.21.1.dev0.dist-info → keras_hub-0.22.0.dev0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,135 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.layers.preprocessing.start_end_packer import StartEndPacker
5
+ from keras_hub.src.models.esm.esm_backbone import ESMBackbone
6
+ from keras_hub.src.models.esm.esm_tokenizer import ESMTokenizer
7
+ from keras_hub.src.models.text_classifier_preprocessor import (
8
+ TextClassifierPreprocessor,
9
+ )
10
+ from keras_hub.src.utils.tensor_utils import preprocessing_function
11
+
12
+
13
+ @keras_hub_export("keras_hub.models.ESMProteinClassifierPreprocessor")
14
+ class ESMProteinClassifierPreprocessor(TextClassifierPreprocessor):
15
+ """A ESM preprocessing layer which tokenizes and packs inputs.
16
+
17
+ This preprocessing layer will do three things:
18
+
19
+ 1. Tokenize any number of input segments using the `tokenizer`.
20
+ 2. Pack the inputs together using a `keras_hub.layers.StartEndPacker`.
21
+ with the appropriate start, end and pad tokens.
22
+ 3. Construct a dictionary with the key `"token_ids"`, that can be passed
23
+ directly to an ESM model.
24
+ This layer can be used directly with `tf.data.Dataset.map` to preprocess
25
+ string data in the `(x, y, sample_weight)` format used by
26
+ `keras.Model.fit`.
27
+
28
+ Args:
29
+ tokenizer: A `keras_hub.models.ESMTokenizer` instance.
30
+ sequence_length: The length of the packed inputs.
31
+ truncate: string. The algorithm to truncate a list of batched segments
32
+ to fit within `sequence_length`. The value can be either
33
+ `round_robin` or `waterfall`:
34
+ - `"round_robin"`: Available space is assigned one token at a
35
+ time in a round-robin fashion to the inputs that still need
36
+ some, until the limit is reached.
37
+ - `"waterfall"`: The allocation of the budget is done using a
38
+ "waterfall" algorithm that allocates quota in a
39
+ left-to-right manner and fills up the buckets until we run
40
+ out of budget. It supports an arbitrary number of segments.
41
+
42
+ Call arguments:
43
+ x: A tensor of single string sequences, or a tuple of multiple
44
+ tensor sequences to be packed together. Inputs may be batched or
45
+ unbatched. For single sequences, raw python inputs will be converted
46
+ to tensors. For multiple sequences, pass tensors directly.
47
+ y: Any label data. Will be passed through unaltered.
48
+ sample_weight: Any label weight data. Will be passed through unaltered.
49
+
50
+ Examples:
51
+
52
+ Directly calling the layer on data.
53
+ ```python
54
+ preprocessor = keras_hub.models.ESMProteinClassifierPreprocessor.from_preset
55
+ (
56
+ hf://facebook/esm2_t6_8M_UR50D
57
+ )
58
+
59
+ # Tokenize and pack a single sentence.
60
+ preprocessor("The quick brown fox jumped.")
61
+
62
+ # Tokenize a batch of single sentences.
63
+ preprocessor(["The quick brown fox jumped.", "Call me Ishmael."])
64
+
65
+ # Preprocess a batch of sentence pairs.
66
+ # When handling multiple sequences, always convert to tensors first!
67
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
68
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
69
+ preprocessor((first, second))
70
+
71
+ # Custom vocabulary.
72
+ vocab = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
73
+ vocab += ["The", "quick", "brown", "fox", "jumped", "."]
74
+ tokenizer = keras_hub.models.ESMTokenizer(vocabulary=vocab)
75
+ preprocessor =
76
+ keras_hub.models.ESMProteinClassifierPreprocessor(tokenizer)
77
+ preprocessor("The quick brown fox jumped.")
78
+ ```
79
+
80
+ Mapping with `tf.data.Dataset`.
81
+ ```python
82
+ preprocessor = keras_hub.models.ESMProteinClassifierPreprocessor.from_preset
83
+ (
84
+ hf://facebook/esm2_t6_8M_UR50D
85
+ )
86
+
87
+ first = tf.constant(["The quick brown fox jumped.", "Call me Ishmael."])
88
+ second = tf.constant(["The fox tripped.", "Oh look, a whale."])
89
+ label = tf.constant([1, 1])
90
+
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
+ # Map unlabeled single sentences.
96
+ ds = tf.data.Dataset.from_tensor_slices(first)
97
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
98
+
99
+ # Map labeled sentence pairs.
100
+ ds = tf.data.Dataset.from_tensor_slices(((first, second), label))
101
+ ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
102
+
103
+ # Map unlabeled sentence pairs.
104
+ ds = tf.data.Dataset.from_tensor_slices((first, second))
105
+ # Watch out for tf.data's default unpacking of tuples here!
106
+ # Best to invoke the `preprocessor` directly in this case.
107
+ ds = ds.map(
108
+ lambda first, second: preprocessor(x=(first, second)),
109
+ num_parallel_calls=tf.data.AUTOTUNE,
110
+ )
111
+ ```
112
+ """
113
+
114
+ backbone_cls = ESMBackbone
115
+ tokenizer_cls = ESMTokenizer
116
+
117
+ def build(self, input_shape):
118
+ super().build(input_shape)
119
+ # Defer masker creation to `build()` so that we can be sure tokenizer
120
+ # assets have loaded when restoring a saved model.
121
+ self.packer = StartEndPacker(
122
+ start_value=self.tokenizer.start_token_id,
123
+ end_value=self.tokenizer.end_token_id,
124
+ pad_value=self.tokenizer.pad_token_id,
125
+ sequence_length=self.sequence_length,
126
+ )
127
+
128
+ @preprocessing_function
129
+ def call(self, x, y=None, sample_weight=None):
130
+ x = self.tokenizer(x)
131
+ token_ids = self.packer(x)
132
+ x = {
133
+ "token_ids": token_ids,
134
+ }
135
+ return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
@@ -0,0 +1,134 @@
1
+ import keras
2
+ from keras import activations
3
+ from keras import initializers
4
+
5
+ from keras_hub.src.models.esm.esm_attention import EsmSelfAttention
6
+
7
+
8
+ class ESMEncoder(keras.layers.Layer):
9
+ """MultiHeadAttention by ESM
10
+
11
+ Referred to the implementation of HuggingFace.
12
+ reference:
13
+ https://github.com/huggingface/transformers/
14
+ blob/main/src/transformers/models/esm/modeling_esm.py
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ heads,
20
+ head_size,
21
+ intermediate_size=None,
22
+ max_wavelength=10000,
23
+ dropout=0,
24
+ activation="gelu",
25
+ use_bias=False,
26
+ kernel_initializer="glorot_uniform",
27
+ layer_norm_eps=1e-12,
28
+ use_rotary=True,
29
+ **kwargs,
30
+ ):
31
+ super().__init__(**kwargs)
32
+ self.heads = heads
33
+ self.head_size = head_size
34
+ self.intermediate_size = intermediate_size
35
+ self.use_bias = use_bias
36
+ self.kernel_initializer = initializers.get(kernel_initializer)
37
+ self.max_wavelength = max_wavelength
38
+ self.dropout = dropout
39
+ self.activation = activations.get(activation)
40
+ self.layer_norm_eps = layer_norm_eps
41
+ self.use_rotary = use_rotary
42
+
43
+ def build(self, input_shape):
44
+ super().build(input_shape)
45
+ self.attention_layer = EsmSelfAttention(
46
+ heads=self.heads,
47
+ head_size=self.head_size,
48
+ use_bias=self.use_bias,
49
+ max_wavelength=self.max_wavelength,
50
+ kernel_initializer=self.kernel_initializer,
51
+ dtype=self.dtype_policy,
52
+ use_rotary=self.use_rotary,
53
+ name="attention_layer",
54
+ )
55
+ self.attention_layer.build(input_shape)
56
+
57
+ self.dropout_layer = keras.layers.Dropout(
58
+ rate=self.dropout,
59
+ dtype=self.dtype_policy,
60
+ name="self_attention_dropout",
61
+ )
62
+ self.dropout_layer.build([])
63
+
64
+ # Feedforward layers.
65
+ self.feedforward_intermediate_dense = keras.layers.Dense(
66
+ self.intermediate_size,
67
+ kernel_initializer=self.kernel_initializer,
68
+ use_bias=self.use_bias,
69
+ dtype=self.dtype_policy,
70
+ activation=self.activation,
71
+ name="feedforward_intermediate_dense",
72
+ )
73
+ self.feedforward_intermediate_dense.build(input_shape)
74
+
75
+ self.feedforward_output_dense = keras.layers.Dense(
76
+ input_shape[-1],
77
+ kernel_initializer=self.kernel_initializer,
78
+ use_bias=self.use_bias,
79
+ dtype=self.dtype_policy,
80
+ name="feedforward_output_dense",
81
+ )
82
+
83
+ self.feedforward_output_dense.build(
84
+ [None, None, self.intermediate_size]
85
+ )
86
+
87
+ self.attention_norm = keras.layers.LayerNormalization(
88
+ epsilon=self.layer_norm_eps,
89
+ name="attention_norm",
90
+ dtype=self.dtype_policy,
91
+ )
92
+ self.attention_norm.build(input_shape)
93
+
94
+ self.feedforward_norm = keras.layers.LayerNormalization(
95
+ epsilon=self.layer_norm_eps,
96
+ name="ffn_norm",
97
+ dtype=self.dtype_policy,
98
+ )
99
+ self.feedforward_norm.build(input_shape)
100
+
101
+ def call(self, x, attention_mask=None):
102
+ attention_output = self.attention_layer(
103
+ self.attention_norm(self.dropout_layer(x)),
104
+ attention_mask=attention_mask,
105
+ )
106
+ residual = x + attention_output
107
+
108
+ x = self.feedforward_norm(self.dropout_layer(residual))
109
+ intermediate_output = self.feedforward_intermediate_dense(x)
110
+ feedforward_output = self.feedforward_output_dense(intermediate_output)
111
+ return residual + self.dropout_layer(feedforward_output)
112
+
113
+ def compute_output_shape(self, input_shape):
114
+ return input_shape
115
+
116
+ def get_config(self):
117
+ config = super().get_config()
118
+ config.update(
119
+ {
120
+ "heads": self.heads,
121
+ "head_size": self.head_size,
122
+ "intermediate_size": self.intermediate_size,
123
+ "max_wavelength": self.max_wavelength,
124
+ "use_bias": self.use_bias,
125
+ "activation": activations.serialize(self.activation),
126
+ "dropout": self.dropout,
127
+ "layer_norm_eps": self.layer_norm_eps,
128
+ "use_rotary": self.use_rotary,
129
+ "kernel_initializer": initializers.serialize(
130
+ self.kernel_initializer
131
+ ),
132
+ }
133
+ )
134
+ return config
@@ -0,0 +1,117 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.layers.modeling.masked_lm_head import MaskedLMHead
5
+ from keras_hub.src.models.esm.esm_backbone import ESMBackbone
6
+ from keras_hub.src.models.esm.esm_backbone import esm2_kernel_initializer
7
+ from keras_hub.src.models.esm.esm_masked_plm_preprocessor import (
8
+ ESMMaskedPLMPreprocessor,
9
+ )
10
+ from keras_hub.src.models.masked_lm import MaskedLM
11
+
12
+
13
+ @keras_hub_export(
14
+ ["keras_hub.models.ESM2MaskedPLM", "keras_hub.models.ESMMaskedPLM"]
15
+ )
16
+ class ESMMaskedPLM(MaskedLM):
17
+ """An end-to-end ESM2 model for the masked protein language modeling task.
18
+
19
+ This model will train ESM2 on a masked protein language modeling task.
20
+ The model will predict labels for a number of masked tokens in the
21
+ input data. For usage of this model with pre-trained weights, see the
22
+ `from_preset()` method.
23
+
24
+ This model can optionally be configured with a `preprocessor` layer, in
25
+ which case inputs can be raw string features during `fit()`, `predict()`,
26
+ and `evaluate()`. Inputs will be tokenized and dynamically masked during
27
+ training and evaluation. This is done by default when creating the model
28
+ with `from_preset()`.
29
+
30
+
31
+ Args:
32
+ backbone: A `keras_hub.models.ESM2Backbone` instance.
33
+ preprocessor: A `keras_hub.models.ESM2MaskedPLMPreprocessor` or
34
+ `None`. If `None`, this model will not apply preprocessing, and
35
+ inputs should be preprocessed before calling the model.
36
+
37
+ Examples:
38
+
39
+ Raw string data.
40
+ ```python
41
+ features = ["The quick brown fox jumped.", "I forgot my homework."]
42
+
43
+ # Pretrained protein language model.
44
+ masked_lm = keras_hub.models.ESM2MaskedPLM.from_preset(
45
+ "hf://facebook/esm2_t6_8M_UR50D",
46
+ )
47
+ masked_lm.fit(x=features, batch_size=2)
48
+
49
+ # Re-compile (e.g., with a new learning rate).
50
+ masked_lm.compile(
51
+ loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
52
+ optimizer=keras.optimizers.Adam(5e-5),
53
+ jit_compile=True,
54
+ )
55
+ # Access backbone programmatically (e.g., to change `trainable`).
56
+ masked_lm.backbone.trainable = False
57
+ # Fit again.
58
+ masked_lm.fit(x=features, batch_size=2)
59
+ ```
60
+
61
+ Preprocessed integer data.
62
+ ```python
63
+ # Create a preprocessed dataset where 0 is the mask token.
64
+ features = {
65
+ "token_ids": np.array([[1, 2, 0, 4, 0, 6, 7, 8]] * 2),
66
+ "mask_positions": np.array([[2, 4]] * 2)
67
+ }
68
+ # Labels are the original masked values.
69
+ labels = [[3, 5]] * 2
70
+
71
+ masked_lm = keras_hub.models.ESM2MaskedPLM.from_preset(
72
+ 'hf://facebook/esm2_t6_8M_UR50D',
73
+ preprocessor=None,
74
+ )
75
+
76
+ masked_lm.fit(x=features, y=labels, batch_size=2)
77
+ ```
78
+ """
79
+
80
+ backbone_cls = ESMBackbone
81
+ preprocessor_cls = ESMMaskedPLMPreprocessor
82
+
83
+ def __init__(
84
+ self,
85
+ backbone,
86
+ preprocessor=None,
87
+ **kwargs,
88
+ ):
89
+ # === Layers ===
90
+ self.backbone = backbone
91
+ self.preprocessor = preprocessor
92
+ self.masked_lm_head = MaskedLMHead(
93
+ vocabulary_size=backbone.vocabulary_size,
94
+ intermediate_activation=backbone.activation,
95
+ kernel_initializer=esm2_kernel_initializer(),
96
+ dtype=backbone.dtype_policy,
97
+ layer_norm_epsilon=backbone.layer_norm_eps,
98
+ name="mlm_head",
99
+ )
100
+
101
+ # === Functional Model ===
102
+ inputs = {
103
+ **backbone.input,
104
+ "mask_positions": keras.Input(
105
+ shape=(None,), dtype="int32", name="mask_positions"
106
+ ),
107
+ }
108
+ backbone_outputs = backbone(backbone.input)
109
+
110
+ outputs = self.masked_lm_head(
111
+ backbone_outputs, inputs["mask_positions"]
112
+ )
113
+ super().__init__(
114
+ inputs=inputs,
115
+ outputs=outputs,
116
+ **kwargs,
117
+ )
@@ -0,0 +1,143 @@
1
+ import keras
2
+
3
+ from keras_hub.src.api_export import keras_hub_export
4
+ from keras_hub.src.layers.preprocessing.masked_lm_mask_generator import (
5
+ MaskedLMMaskGenerator,
6
+ )
7
+ from keras_hub.src.layers.preprocessing.start_end_packer import StartEndPacker
8
+ from keras_hub.src.models.esm.esm_backbone import ESMBackbone
9
+ from keras_hub.src.models.esm.esm_tokenizer import ESMTokenizer
10
+ from keras_hub.src.models.masked_lm_preprocessor import MaskedLMPreprocessor
11
+ from keras_hub.src.utils.tensor_utils import preprocessing_function
12
+
13
+
14
+ @keras_hub_export("keras_hub.models.ESMMaskedPLMPreprocessor")
15
+ class ESMMaskedPLMPreprocessor(MaskedLMPreprocessor):
16
+ """ESM 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.ESMMaskedPLM` 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.ESMMaskedPLM` task model.
30
+
31
+ Args:
32
+ tokenizer: A `keras_hub.models.ESMTokenizer` 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.ESMMaskedPLMPreprocessor.from_preset(
69
+ hf://facebook/esm2_t6_8M_UR50D
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.ESMMaskedPLMPreprocessor.from_preset(
88
+ hf://facebook/esm2_t6_8M_UR50D
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 = ESMBackbone
110
+ tokenizer_cls = ESMTokenizer
111
+
112
+ def build(self, input_shape):
113
+ super().build(input_shape)
114
+ # Defer masker creation to `build()` so that we can be sure tokenizer
115
+ # assets have loaded when restoring a saved model.
116
+ self.packer = StartEndPacker(
117
+ start_value=self.tokenizer.start_token_id,
118
+ end_value=self.tokenizer.end_token_id,
119
+ pad_value=self.tokenizer.pad_token_id,
120
+ sequence_length=self.sequence_length,
121
+ )
122
+ self.masker = MaskedLMMaskGenerator(
123
+ mask_selection_rate=self.mask_selection_rate,
124
+ mask_selection_length=self.mask_selection_length,
125
+ mask_token_rate=self.mask_token_rate,
126
+ random_token_rate=self.random_token_rate,
127
+ vocabulary_size=self.tokenizer.vocabulary_size(),
128
+ mask_token_id=self.tokenizer.mask_token_id,
129
+ unselectable_token_ids=self.tokenizer.special_token_ids,
130
+ )
131
+
132
+ @preprocessing_function
133
+ def call(self, x, y=None, sample_weight=None):
134
+ x = self.tokenizer(x)
135
+ token_ids = self.packer(x)
136
+ masker_outputs = self.masker(token_ids)
137
+ x = {
138
+ "token_ids": masker_outputs["token_ids"],
139
+ "mask_positions": masker_outputs["mask_positions"],
140
+ }
141
+ y = masker_outputs["mask_ids"]
142
+ sample_weight = masker_outputs["mask_weights"]
143
+ return keras.utils.pack_x_y_sample_weight(x, y, sample_weight)
@@ -0,0 +1,53 @@
1
+ """ESM model preset configurations."""
2
+
3
+ # Metadata for loading pretrained model weights.
4
+ backbone_presets = {
5
+ "esm2_t6_8M": {
6
+ "metadata": {
7
+ "description": (
8
+ "6 transformer layers version of the ESM-2 protein language "
9
+ "model, trained on the UniRef50 clustered protein sequence "
10
+ "dataset."
11
+ ),
12
+ "params": 7_408_960,
13
+ "path": "esm",
14
+ },
15
+ "kaggle_handle": "kaggle://keras/esm-2/keras/esm2_t6_8M/1",
16
+ },
17
+ "esm2_t12_35M": {
18
+ "metadata": {
19
+ "description": (
20
+ "12 transformer layers version of the ESM-2 protein language "
21
+ "model, trained on the UniRef50 clustered protein sequence "
22
+ "dataset."
23
+ ),
24
+ "params": 33_269_280,
25
+ "path": "esm",
26
+ },
27
+ "kaggle_handle": "kaggle://keras/esm-2/keras/esm2_t12_35M/1",
28
+ },
29
+ "esm2_t30_150M": {
30
+ "metadata": {
31
+ "description": (
32
+ "30 transformer layers version of the ESM-2 protein language "
33
+ "model, trained on the UniRef50 clustered protein sequence "
34
+ "dataset."
35
+ ),
36
+ "params": 147_728_000,
37
+ "path": "esm",
38
+ },
39
+ "kaggle_handle": "kaggle://keras/esm-2/keras/esm2_t30_150M/1",
40
+ },
41
+ "esm2_t33_650M": {
42
+ "metadata": {
43
+ "description": (
44
+ "33 transformer layers version of the ESM-2 protein language "
45
+ "model, trained on the UniRef50 clustered protein sequence "
46
+ "dataset."
47
+ ),
48
+ "params": 649_400_320,
49
+ "path": "esm",
50
+ },
51
+ "kaggle_handle": "kaggle://keras/esm-2/keras/esm2_t33_650M/1",
52
+ },
53
+ }
@@ -0,0 +1,82 @@
1
+ from keras_hub.src.api_export import keras_hub_export
2
+ from keras_hub.src.models.esm.esm_backbone import ESMBackbone
3
+ from keras_hub.src.tokenizers.word_piece_tokenizer import WordPieceTokenizer
4
+
5
+
6
+ @keras_hub_export(
7
+ [
8
+ "keras_hub.tokenizers.ESMTokenizer",
9
+ "keras_hub.models.ESMTokenizer",
10
+ ]
11
+ )
12
+ class ESMTokenizer(WordPieceTokenizer):
13
+ """A ESM tokenizer using WordPiece subword segmentation.
14
+
15
+ This tokenizer class will tokenize raw strings into integer sequences and
16
+ is based on `keras_hub.tokenizers.WordPieceTokenizer`. Unlike the
17
+ underlying tokenizer, it will check for special tokens needed by ESM
18
+ models and provides a `from_preset()` method to automatically download
19
+ a matching vocabulary for a ESM preset.
20
+
21
+ If input is a batch of strings (rank > 0), the layer will output a
22
+ `tf.RaggedTensor` where the last dimension of the output is ragged.
23
+
24
+ If input is a scalar string (rank == 0), the layer will output a dense
25
+ `tf.Tensor` with static shape `[None]`.
26
+
27
+ Args:
28
+ vocabulary: A list of strings or a string filename path. If
29
+ passing a list, each element of the list should be a single word
30
+ piece token string. If passing a filename, the file should be a
31
+ plain text file containing a single word piece token per line.
32
+ lowercase: If `True`, the input text will be first lowered before
33
+ tokenization.
34
+ special_tokens_in_strings: bool. A bool to indicate if the tokenizer
35
+ should expect special tokens in input strings that should be
36
+ tokenized and mapped correctly to their ids. Defaults to False.
37
+
38
+ Examples:
39
+ ```python
40
+ # Unbatched input.
41
+ tokenizer = keras_hub.models.ESMTokenizer.from_preset(
42
+ "hf://facebook/esm2_t6_8M_UR50D",
43
+ )
44
+ tokenizer("The quick brown fox jumped.")
45
+
46
+ # Batched input.
47
+ tokenizer(["The quick brown fox jumped.", "The fox slept."])
48
+
49
+ # Detokenization.
50
+ tokenizer.detokenize(tokenizer("The quick brown fox jumped."))
51
+
52
+ # Custom vocabulary.
53
+ vocab = ["[UNK]", "<cls>", "<eos>", "<pad>", "<mask>"]
54
+ vocab += ["The", "quick", "brown", "fox", "jumped", "."]
55
+ tokenizer = keras_hub.models.ESMTokenizer(vocabulary=vocab)
56
+ tokenizer("The quick brown fox jumped.")
57
+ ```
58
+ """
59
+
60
+ backbone_cls = ESMBackbone
61
+
62
+ def __init__(
63
+ self,
64
+ vocabulary=None,
65
+ lowercase=False,
66
+ oov_token="<unk>",
67
+ **kwargs,
68
+ ):
69
+ self._add_special_token("<cls>", "cls_token")
70
+ self._add_special_token("<eos>", "sep_token")
71
+ self._add_special_token("<pad>", "pad_token")
72
+ self._add_special_token("<mask>", "mask_token")
73
+ # Also add `tokenizer.start_token` and `tokenizer.end_token` for
74
+ # compatibility with other tokenizers.
75
+ self._add_special_token("<cls>", "start_token")
76
+ self._add_special_token("<eos>", "end_token")
77
+ super().__init__(
78
+ vocabulary=vocabulary,
79
+ lowercase=lowercase,
80
+ oov_token=oov_token,
81
+ **kwargs,
82
+ )
@@ -43,9 +43,13 @@ class FluxTextToImagePreprocessor(Preprocessor):
43
43
 
44
44
  def generate_preprocess(self, x):
45
45
  token_ids = {}
46
- token_ids["clip_l"] = self.clip_l_preprocessor(x)["token_ids"]
46
+ token_ids["clip_l"] = self.clip_l_preprocessor(
47
+ {"prompts": x, "images": None}
48
+ )["token_ids"]
47
49
  if self.t5_preprocessor is not None:
48
- token_ids["t5"] = self.t5_preprocessor(x)["token_ids"]
50
+ token_ids["t5"] = self.t5_preprocessor(
51
+ {"prompts": x, "images": None}
52
+ )["token_ids"]
49
53
  return token_ids
50
54
 
51
55
  def get_config(self):