keras-hub-nightly 0.22.0.dev202508100425__py3-none-any.whl → 0.22.0.dev202508110431__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.
Potentially problematic release.
This version of keras-hub-nightly might be problematic. Click here for more details.
- keras_hub/models/__init__.py +16 -0
- keras_hub/src/models/esm/__init__.py +0 -0
- keras_hub/src/models/esm/esm_attention.py +95 -0
- keras_hub/src/models/esm/esm_backbone.py +229 -0
- keras_hub/src/models/esm/esm_classifier.py +184 -0
- keras_hub/src/models/esm/esm_classifier_preprocessor.py +135 -0
- keras_hub/src/models/esm/esm_encoder.py +134 -0
- keras_hub/src/models/esm/esm_masked_plm.py +117 -0
- keras_hub/src/models/esm/esm_masked_plm_preprocessor.py +143 -0
- keras_hub/src/models/esm/esm_presets.py +0 -0
- keras_hub/src/models/esm/esm_tokenizer.py +82 -0
- keras_hub/src/models/roformer_v2/roformer_v2_attention.py +2 -1
- keras_hub/src/utils/transformers/convert_esm.py +159 -0
- keras_hub/src/utils/transformers/preset_loader.py +3 -0
- keras_hub/src/version.py +1 -1
- keras_hub/tokenizers/__init__.py +1 -0
- {keras_hub_nightly-0.22.0.dev202508100425.dist-info → keras_hub_nightly-0.22.0.dev202508110431.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.22.0.dev202508100425.dist-info → keras_hub_nightly-0.22.0.dev202508110431.dist-info}/RECORD +20 -9
- {keras_hub_nightly-0.22.0.dev202508100425.dist-info → keras_hub_nightly-0.22.0.dev202508110431.dist-info}/WHEEL +0 -0
- {keras_hub_nightly-0.22.0.dev202508100425.dist-info → keras_hub_nightly-0.22.0.dev202508110431.dist-info}/top_level.txt +0 -0
|
@@ -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)
|
|
File without changes
|
|
@@ -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
|
+
)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import keras
|
|
2
2
|
from keras import initializers
|
|
3
3
|
from keras import ops
|
|
4
|
+
from packaging import version
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
class RoformerNorm(keras.layers.Layer):
|
|
@@ -179,7 +180,7 @@ class RoformerAttention(keras.layers.Layer):
|
|
|
179
180
|
vw = ops.reshape(vw, (b, s, self.heads, self.head_size))
|
|
180
181
|
|
|
181
182
|
qw, kw = self.rotary_embedding_layer([qw, kw])
|
|
182
|
-
if keras.__version__ < "3.6":
|
|
183
|
+
if version.parse(keras.__version__) < version.parse("3.6"):
|
|
183
184
|
raise ("Please make sure your Keras version is >=3.6.")
|
|
184
185
|
flash_attention = keras.config.is_flash_attention_enabled()
|
|
185
186
|
attention_mask = ops.reshape(attention_mask, [b, 1, s, 1])
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from keras_hub.src.models.esm.esm_backbone import ESMBackbone
|
|
4
|
+
from keras_hub.src.utils.preset_utils import get_file
|
|
5
|
+
|
|
6
|
+
backbone_cls = ESMBackbone
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def convert_backbone_config(transformers_config):
|
|
10
|
+
return {
|
|
11
|
+
"vocabulary_size": transformers_config["vocab_size"],
|
|
12
|
+
"num_layers": transformers_config["num_hidden_layers"],
|
|
13
|
+
"num_heads": transformers_config["num_attention_heads"],
|
|
14
|
+
"hidden_dim": transformers_config["hidden_size"],
|
|
15
|
+
"intermediate_dim": transformers_config["intermediate_size"],
|
|
16
|
+
"dropout": transformers_config["hidden_dropout_prob"],
|
|
17
|
+
"position_embedding_type": transformers_config[
|
|
18
|
+
"position_embedding_type"
|
|
19
|
+
],
|
|
20
|
+
"pad_token_id": transformers_config["pad_token_id"],
|
|
21
|
+
"max_sequence_length": transformers_config.get(
|
|
22
|
+
"max_position_embeddings", None
|
|
23
|
+
),
|
|
24
|
+
"layer_norm_eps": transformers_config.get("layer_norm_eps", 1e-12),
|
|
25
|
+
"use_pre_layer_norm": transformers_config.get(
|
|
26
|
+
"emb_layer_norm_before", False
|
|
27
|
+
),
|
|
28
|
+
"activation": transformers_config.get("activation", "gelu"),
|
|
29
|
+
"max_wavelength": transformers_config.get("max_wavelength", 10000),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def transpose_and_reshape(x, shape):
|
|
34
|
+
return np.reshape(np.transpose(x), shape)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def convert_weights(backbone, loader, transformers_config):
|
|
38
|
+
# Embedding layer
|
|
39
|
+
loader.port_weight(
|
|
40
|
+
keras_variable=backbone.get_layer("token_embedding").embeddings,
|
|
41
|
+
hf_weight_key="embeddings.word_embeddings.weight",
|
|
42
|
+
)
|
|
43
|
+
if transformers_config["position_embedding_type"] == "absolute":
|
|
44
|
+
loader.port_weight(
|
|
45
|
+
keras_variable=backbone.get_layer(
|
|
46
|
+
"position_embedding"
|
|
47
|
+
).position_embeddings,
|
|
48
|
+
hf_weight_key="embeddings.position_embeddings.weight",
|
|
49
|
+
)
|
|
50
|
+
if transformers_config.get("emb_layer_norm_before", False):
|
|
51
|
+
loader.port_weight(
|
|
52
|
+
keras_variable=backbone.get_layer("emb_layer_norm").gamma,
|
|
53
|
+
hf_weight_key="embeddings.layer_norm.weight",
|
|
54
|
+
)
|
|
55
|
+
loader.port_weight(
|
|
56
|
+
keras_variable=backbone.get_layer("emb_layer_norm").beta,
|
|
57
|
+
hf_weight_key="embeddings.layer_norm.bias",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
loader.port_weight(
|
|
61
|
+
keras_variable=backbone.output_layer_norm.gamma,
|
|
62
|
+
hf_weight_key="encoder.emb_layer_norm_after.weight",
|
|
63
|
+
)
|
|
64
|
+
loader.port_weight(
|
|
65
|
+
keras_variable=backbone.output_layer_norm.beta,
|
|
66
|
+
hf_weight_key="encoder.emb_layer_norm_after.bias",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Attention blocks
|
|
70
|
+
for i in range(backbone.num_layers):
|
|
71
|
+
block = backbone.get_layer(f"transformer_layer_{i}")
|
|
72
|
+
attn = block.attention_layer
|
|
73
|
+
hf_prefix = "encoder.layer."
|
|
74
|
+
# Attention layers
|
|
75
|
+
loader.port_weight(
|
|
76
|
+
keras_variable=attn.q_dense.kernel,
|
|
77
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.query.weight",
|
|
78
|
+
hook_fn=transpose_and_reshape,
|
|
79
|
+
)
|
|
80
|
+
loader.port_weight(
|
|
81
|
+
keras_variable=attn.q_dense.bias,
|
|
82
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.query.bias",
|
|
83
|
+
hook_fn=lambda hf_tensor, shape: np.reshape(hf_tensor, shape),
|
|
84
|
+
)
|
|
85
|
+
loader.port_weight(
|
|
86
|
+
keras_variable=attn.k_dense.kernel,
|
|
87
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.key.weight",
|
|
88
|
+
hook_fn=transpose_and_reshape,
|
|
89
|
+
)
|
|
90
|
+
loader.port_weight(
|
|
91
|
+
keras_variable=attn.k_dense.bias,
|
|
92
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.key.bias",
|
|
93
|
+
hook_fn=lambda hf_tensor, shape: np.reshape(hf_tensor, shape),
|
|
94
|
+
)
|
|
95
|
+
loader.port_weight(
|
|
96
|
+
keras_variable=attn.v_dense.kernel,
|
|
97
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.value.weight",
|
|
98
|
+
hook_fn=transpose_and_reshape,
|
|
99
|
+
)
|
|
100
|
+
loader.port_weight(
|
|
101
|
+
keras_variable=attn.v_dense.bias,
|
|
102
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.self.value.bias",
|
|
103
|
+
hook_fn=lambda hf_tensor, shape: np.reshape(hf_tensor, shape),
|
|
104
|
+
)
|
|
105
|
+
loader.port_weight(
|
|
106
|
+
keras_variable=attn.o_dense.kernel,
|
|
107
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.output.dense.weight",
|
|
108
|
+
hook_fn=transpose_and_reshape,
|
|
109
|
+
)
|
|
110
|
+
loader.port_weight(
|
|
111
|
+
keras_variable=attn.o_dense.bias,
|
|
112
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.output.dense.bias",
|
|
113
|
+
hook_fn=lambda hf_tensor, shape: np.reshape(hf_tensor, shape),
|
|
114
|
+
)
|
|
115
|
+
# Attention layer norm.
|
|
116
|
+
loader.port_weight(
|
|
117
|
+
keras_variable=block.attention_norm.gamma,
|
|
118
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.LayerNorm.weight",
|
|
119
|
+
)
|
|
120
|
+
loader.port_weight(
|
|
121
|
+
keras_variable=block.attention_norm.beta,
|
|
122
|
+
hf_weight_key=f"{hf_prefix}{i}.attention.LayerNorm.bias",
|
|
123
|
+
)
|
|
124
|
+
# MLP layers
|
|
125
|
+
loader.port_weight(
|
|
126
|
+
keras_variable=block.feedforward_intermediate_dense.kernel,
|
|
127
|
+
hf_weight_key=f"{hf_prefix}{i}.intermediate.dense.weight",
|
|
128
|
+
hook_fn=lambda hf_tensor, _: np.transpose(hf_tensor, axes=(1, 0)),
|
|
129
|
+
)
|
|
130
|
+
loader.port_weight(
|
|
131
|
+
keras_variable=block.feedforward_intermediate_dense.bias,
|
|
132
|
+
hf_weight_key=f"{hf_prefix}{i}.intermediate.dense.bias",
|
|
133
|
+
)
|
|
134
|
+
loader.port_weight(
|
|
135
|
+
keras_variable=block.feedforward_output_dense.kernel,
|
|
136
|
+
hf_weight_key=f"{hf_prefix}{i}.output.dense.weight",
|
|
137
|
+
hook_fn=lambda hf_tensor, _: np.transpose(hf_tensor, axes=(1, 0)),
|
|
138
|
+
)
|
|
139
|
+
loader.port_weight(
|
|
140
|
+
keras_variable=block.feedforward_output_dense.bias,
|
|
141
|
+
hf_weight_key=f"{hf_prefix}{i}.output.dense.bias",
|
|
142
|
+
)
|
|
143
|
+
# Output layer norm.
|
|
144
|
+
loader.port_weight(
|
|
145
|
+
keras_variable=block.feedforward_norm.gamma,
|
|
146
|
+
hf_weight_key=f"{hf_prefix}{i}.LayerNorm.weight",
|
|
147
|
+
)
|
|
148
|
+
loader.port_weight(
|
|
149
|
+
keras_variable=block.feedforward_norm.beta,
|
|
150
|
+
hf_weight_key=f"{hf_prefix}{i}.LayerNorm.bias",
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def convert_tokenizer(cls, preset, **kwargs):
|
|
155
|
+
return cls(
|
|
156
|
+
get_file(preset, "vocab.txt"),
|
|
157
|
+
lowercase=False,
|
|
158
|
+
**kwargs,
|
|
159
|
+
)
|
|
@@ -9,6 +9,7 @@ from keras_hub.src.utils.transformers import convert_bert
|
|
|
9
9
|
from keras_hub.src.utils.transformers import convert_deit
|
|
10
10
|
from keras_hub.src.utils.transformers import convert_dinov2
|
|
11
11
|
from keras_hub.src.utils.transformers import convert_distilbert
|
|
12
|
+
from keras_hub.src.utils.transformers import convert_esm
|
|
12
13
|
from keras_hub.src.utils.transformers import convert_gemma
|
|
13
14
|
from keras_hub.src.utils.transformers import convert_gpt2
|
|
14
15
|
from keras_hub.src.utils.transformers import convert_llama3
|
|
@@ -38,6 +39,8 @@ class TransformersPresetLoader(PresetLoader):
|
|
|
38
39
|
self.converter = convert_distilbert
|
|
39
40
|
elif model_type in ("dinov2", "dinov2_with_registers"):
|
|
40
41
|
self.converter = convert_dinov2
|
|
42
|
+
elif model_type == "esm":
|
|
43
|
+
self.converter = convert_esm
|
|
41
44
|
elif model_type in ("gemma", "gemma2"):
|
|
42
45
|
self.converter = convert_gemma
|
|
43
46
|
elif model_type == "gpt2":
|
keras_hub/src/version.py
CHANGED