keras-hub-nightly 0.22.0.dev202505290412__py3-none-any.whl → 0.22.0.dev202505310408__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/layers/__init__.py +3 -0
- keras_hub/models/__init__.py +16 -0
- keras_hub/src/models/deit/__init__.py +0 -0
- keras_hub/src/models/deit/deit_backbone.py +154 -0
- keras_hub/src/models/deit/deit_image_classifier.py +171 -0
- keras_hub/src/models/deit/deit_image_classifier_preprocessor.py +12 -0
- keras_hub/src/models/deit/deit_image_converter.py +8 -0
- keras_hub/src/models/deit/deit_layers.py +519 -0
- keras_hub/src/models/deit/deit_presets.py +49 -0
- keras_hub/src/models/mixtral/mixtral_presets.py +4 -4
- keras_hub/src/models/qwen/qwen_presets.py +6 -6
- keras_hub/src/models/qwen3/qwen3_attention.py +369 -0
- keras_hub/src/models/qwen3/qwen3_backbone.py +191 -0
- keras_hub/src/models/qwen3/qwen3_causal_lm_preprocessor.py +10 -0
- keras_hub/src/models/qwen3/qwen3_decoder.py +309 -0
- keras_hub/src/models/qwen3/qwen3_layernorm.py +38 -0
- keras_hub/src/models/qwen3/qwen3_tokenizer.py +48 -0
- keras_hub/src/models/qwen_moe/qwen_moe_presets.py +2 -2
- keras_hub/src/utils/transformers/convert_deit.py +155 -0
- keras_hub/src/utils/transformers/convert_qwen3.py +145 -0
- keras_hub/src/utils/transformers/preset_loader.py +7 -1
- keras_hub/src/version.py +1 -1
- {keras_hub_nightly-0.22.0.dev202505290412.dist-info → keras_hub_nightly-0.22.0.dev202505310408.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.22.0.dev202505290412.dist-info → keras_hub_nightly-0.22.0.dev202505310408.dist-info}/RECORD +26 -11
- {keras_hub_nightly-0.22.0.dev202505290412.dist-info → keras_hub_nightly-0.22.0.dev202505310408.dist-info}/WHEEL +0 -0
- {keras_hub_nightly-0.22.0.dev202505290412.dist-info → keras_hub_nightly-0.22.0.dev202505310408.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,309 @@
|
|
1
|
+
import keras
|
2
|
+
from keras import ops
|
3
|
+
|
4
|
+
from keras_hub.src.layers.modeling.transformer_layer_utils import (
|
5
|
+
compute_causal_mask,
|
6
|
+
)
|
7
|
+
from keras_hub.src.layers.modeling.transformer_layer_utils import (
|
8
|
+
merge_padding_and_attention_mask,
|
9
|
+
)
|
10
|
+
from keras_hub.src.models.qwen3.qwen3_attention import Qwen3Attention
|
11
|
+
from keras_hub.src.models.qwen3.qwen3_layernorm import Qwen3LayerNorm
|
12
|
+
from keras_hub.src.utils.keras_utils import clone_initializer
|
13
|
+
|
14
|
+
|
15
|
+
class Qwen3TransformerDecoder(keras.layers.Layer):
|
16
|
+
"""A Transformer decoder layer for the Qwen3 backbone.
|
17
|
+
|
18
|
+
This layer implements a Transformer decoder block that includes
|
19
|
+
self-attention with optional sliding window attention and a feed-forward
|
20
|
+
network.
|
21
|
+
|
22
|
+
Args:
|
23
|
+
intermediate_dim: Output dimension of the first dense layer in the
|
24
|
+
feed-forward network.
|
25
|
+
num_query_heads: Number of query attention heads.
|
26
|
+
num_key_value_heads: Number of key/value attention heads (for GQA).
|
27
|
+
rope_max_wavelength: Maximum wavelength for RoPE (Rotary Position
|
28
|
+
Embedding).
|
29
|
+
rope_scaling_factor: Scaling factor for RoPE, used for extending
|
30
|
+
context length.
|
31
|
+
activation: Activation function to use in the feed-forward network.
|
32
|
+
layer_norm_epsilon: Small float added to variance to avoid dividing
|
33
|
+
by zero in layer norm.
|
34
|
+
kernel_initializer: Initializer for the kernel weights.
|
35
|
+
dropout: Dropout rate for attention and hidden layers.
|
36
|
+
sliding_window_size: Size of the sliding window for attention when
|
37
|
+
enabled.
|
38
|
+
**kwargs: Additional keyword arguments to pass to the Layer.
|
39
|
+
"""
|
40
|
+
|
41
|
+
def __init__(
|
42
|
+
self,
|
43
|
+
intermediate_dim,
|
44
|
+
num_query_heads,
|
45
|
+
num_key_value_heads,
|
46
|
+
head_dim,
|
47
|
+
rope_max_wavelength=10000,
|
48
|
+
rope_scaling_factor=1.0,
|
49
|
+
activation="silu",
|
50
|
+
layer_norm_epsilon=1e-5,
|
51
|
+
kernel_initializer="glorot_uniform",
|
52
|
+
dropout=0.0,
|
53
|
+
sliding_window_size=None,
|
54
|
+
**kwargs,
|
55
|
+
):
|
56
|
+
super().__init__(**kwargs)
|
57
|
+
self.intermediate_dim = intermediate_dim
|
58
|
+
self.num_query_heads = num_query_heads
|
59
|
+
self.num_key_value_heads = num_key_value_heads
|
60
|
+
self.head_dim = head_dim
|
61
|
+
|
62
|
+
self.rope_max_wavelength = rope_max_wavelength
|
63
|
+
self.rope_scaling_factor = rope_scaling_factor
|
64
|
+
|
65
|
+
self.dropout = dropout
|
66
|
+
|
67
|
+
self.sliding_window_size = sliding_window_size
|
68
|
+
|
69
|
+
self.activation = keras.activations.get(activation)
|
70
|
+
self.layer_norm_epsilon = layer_norm_epsilon
|
71
|
+
self.kernel_initializer = keras.initializers.get(kernel_initializer)
|
72
|
+
|
73
|
+
self.supports_masking = True
|
74
|
+
|
75
|
+
def build(self, decoder_sequence_shape):
|
76
|
+
self._decoder_sequence_shape = decoder_sequence_shape
|
77
|
+
self.hidden_dim = decoder_sequence_shape[-1]
|
78
|
+
|
79
|
+
# Self attention layer.
|
80
|
+
self._self_attention_layer = Qwen3Attention(
|
81
|
+
num_query_heads=self.num_query_heads,
|
82
|
+
num_key_value_heads=self.num_key_value_heads,
|
83
|
+
rope_max_wavelength=self.rope_max_wavelength,
|
84
|
+
head_dim=self.head_dim,
|
85
|
+
rope_scaling_factor=self.rope_scaling_factor,
|
86
|
+
kernel_initializer=clone_initializer(self.kernel_initializer),
|
87
|
+
dropout=self.dropout,
|
88
|
+
sliding_window_size=self.sliding_window_size,
|
89
|
+
dtype=self.dtype_policy,
|
90
|
+
name="self_attention",
|
91
|
+
)
|
92
|
+
self._self_attention_layer.build(decoder_sequence_shape)
|
93
|
+
|
94
|
+
self._self_attention_layernorm = Qwen3LayerNorm(
|
95
|
+
epsilon=self.layer_norm_epsilon,
|
96
|
+
dtype=self.dtype_policy,
|
97
|
+
name="self_attention_layernorm",
|
98
|
+
)
|
99
|
+
|
100
|
+
self._self_attention_layernorm.build(decoder_sequence_shape)
|
101
|
+
self._self_attention_dropout = keras.layers.Dropout(
|
102
|
+
rate=self.dropout,
|
103
|
+
dtype=self.dtype_policy,
|
104
|
+
name="self_attention_dropout",
|
105
|
+
)
|
106
|
+
|
107
|
+
# Feedforward layers.
|
108
|
+
self._feedforward_intermediate_dense = keras.layers.Dense(
|
109
|
+
self.intermediate_dim,
|
110
|
+
kernel_initializer=clone_initializer(self.kernel_initializer),
|
111
|
+
use_bias=False,
|
112
|
+
dtype=self.dtype_policy,
|
113
|
+
name="feedforward_intermediate_dense",
|
114
|
+
)
|
115
|
+
self._feedforward_intermediate_dense.build(decoder_sequence_shape)
|
116
|
+
|
117
|
+
self._feedforward_gate_dense = keras.layers.Dense(
|
118
|
+
self.intermediate_dim,
|
119
|
+
kernel_initializer=clone_initializer(self.kernel_initializer),
|
120
|
+
use_bias=False,
|
121
|
+
dtype=self.dtype_policy,
|
122
|
+
name="feedforward_gate_dense",
|
123
|
+
)
|
124
|
+
self._feedforward_gate_dense.build(decoder_sequence_shape)
|
125
|
+
|
126
|
+
self._feedforward_output_dense = keras.layers.Dense(
|
127
|
+
self.hidden_dim,
|
128
|
+
kernel_initializer=clone_initializer(self.kernel_initializer),
|
129
|
+
use_bias=False,
|
130
|
+
dtype=self.dtype_policy,
|
131
|
+
name="feedforward_output_dense",
|
132
|
+
)
|
133
|
+
|
134
|
+
self._feedforward_output_dense.build(
|
135
|
+
self._feedforward_gate_dense.compute_output_shape(
|
136
|
+
decoder_sequence_shape
|
137
|
+
)
|
138
|
+
)
|
139
|
+
|
140
|
+
self._feedforward_layernorm = Qwen3LayerNorm(
|
141
|
+
epsilon=self.layer_norm_epsilon,
|
142
|
+
dtype=self.dtype_policy,
|
143
|
+
name="feedforward_layernorm",
|
144
|
+
)
|
145
|
+
self._feedforward_layernorm.build(decoder_sequence_shape)
|
146
|
+
|
147
|
+
self.built = True
|
148
|
+
|
149
|
+
def call(
|
150
|
+
self,
|
151
|
+
decoder_sequence,
|
152
|
+
decoder_padding_mask=None,
|
153
|
+
decoder_attention_mask=None,
|
154
|
+
self_attention_cache=None,
|
155
|
+
self_attention_cache_update_index=None,
|
156
|
+
training=None,
|
157
|
+
):
|
158
|
+
"""Forward pass for the decoder layer.
|
159
|
+
|
160
|
+
Args:
|
161
|
+
decoder_sequence: Input tensor of shape [batch_size, seq_length,
|
162
|
+
hidden_size].
|
163
|
+
decoder_padding_mask: Mask tensor for padding tokens.
|
164
|
+
decoder_attention_mask: Additional attention mask.
|
165
|
+
self_attention_cache: Optional cached key and value tensors for
|
166
|
+
self-attention.
|
167
|
+
self_attention_cache_update_index: Index at which to update the
|
168
|
+
cache.
|
169
|
+
training: Boolean indicating whether in training mode.
|
170
|
+
|
171
|
+
Returns:
|
172
|
+
decoder_output: Output tensor after applying transformer decoder
|
173
|
+
block.
|
174
|
+
self_attention_cache: Updated cache tensors (if cache is provided).
|
175
|
+
"""
|
176
|
+
self_attention_mask = self._compute_self_attention_mask(
|
177
|
+
decoder_sequence=decoder_sequence,
|
178
|
+
decoder_padding_mask=decoder_padding_mask,
|
179
|
+
decoder_attention_mask=decoder_attention_mask,
|
180
|
+
self_attention_cache=self_attention_cache,
|
181
|
+
self_attention_cache_update_index=self_attention_cache_update_index,
|
182
|
+
)
|
183
|
+
residual = decoder_sequence
|
184
|
+
|
185
|
+
x = self._self_attention_layernorm(decoder_sequence)
|
186
|
+
|
187
|
+
# Self attention block.
|
188
|
+
x = self._self_attention_layer(
|
189
|
+
hidden_states=x,
|
190
|
+
attention_mask=self_attention_mask,
|
191
|
+
cache=self_attention_cache,
|
192
|
+
cache_update_index=self_attention_cache_update_index,
|
193
|
+
)
|
194
|
+
|
195
|
+
if self_attention_cache is not None:
|
196
|
+
x, self_attention_cache = x
|
197
|
+
|
198
|
+
x = self._self_attention_dropout(x, training=training)
|
199
|
+
|
200
|
+
x = x + residual
|
201
|
+
residual = x
|
202
|
+
|
203
|
+
x = self._feedforward_layernorm(x)
|
204
|
+
gate_output = self._feedforward_gate_dense(x)
|
205
|
+
|
206
|
+
# Note that we run the activation function in full 32-bit
|
207
|
+
# precision since this is what `torch.nn.functional.silu`
|
208
|
+
# does. Internally, `torch.nn.functional.silu` converts the
|
209
|
+
# inputs to float32, computes SiLU, and converts the outputs
|
210
|
+
# back to compute dtype.
|
211
|
+
# CPU Kernel: https://github.com/pytorch/pytorch/blob/35c493f2cf9b623bfdc7e6b34dc1cb39690a7919/aten/src/ATen/native/cpu/Activation.cpp#L1221-L1235 # noqa: E501
|
212
|
+
# CUDA Kernel: https://github.com/pytorch/pytorch/blob/35c493f2cf9b623bfdc7e6b34dc1cb39690a7919/aten/src/ATen/native/cuda/ActivationSiluKernel.cu # noqa: E501
|
213
|
+
gate_output = ops.cast(gate_output, "float32")
|
214
|
+
gate_output = self.activation(gate_output)
|
215
|
+
gate_output = ops.cast(gate_output, self.compute_dtype)
|
216
|
+
|
217
|
+
x = self._feedforward_intermediate_dense(x)
|
218
|
+
|
219
|
+
x = self._feedforward_output_dense(ops.multiply(x, gate_output))
|
220
|
+
|
221
|
+
decoder_output = x + residual
|
222
|
+
|
223
|
+
if self_attention_cache is not None:
|
224
|
+
return decoder_output, self_attention_cache
|
225
|
+
return decoder_output
|
226
|
+
|
227
|
+
def _compute_self_attention_mask(
|
228
|
+
self,
|
229
|
+
decoder_sequence,
|
230
|
+
decoder_padding_mask,
|
231
|
+
decoder_attention_mask,
|
232
|
+
self_attention_cache,
|
233
|
+
self_attention_cache_update_index,
|
234
|
+
):
|
235
|
+
"""Computes the self-attention mask combining causal, padding and
|
236
|
+
attention masks.
|
237
|
+
|
238
|
+
Args:
|
239
|
+
decoder_sequence: Input tensor.
|
240
|
+
decoder_padding_mask: Mask tensor for padding tokens.
|
241
|
+
decoder_attention_mask: Additional attention mask.
|
242
|
+
self_attention_cache: Optional cached key and value tensors.
|
243
|
+
self_attention_cache_update_index: Index at which to update the
|
244
|
+
cache.
|
245
|
+
|
246
|
+
Returns:
|
247
|
+
Combined attention mask tensor.
|
248
|
+
"""
|
249
|
+
decoder_mask = merge_padding_and_attention_mask(
|
250
|
+
decoder_sequence, decoder_padding_mask, decoder_attention_mask
|
251
|
+
)
|
252
|
+
batch_size = ops.shape(decoder_sequence)[0]
|
253
|
+
input_length = output_length = ops.shape(decoder_sequence)[1]
|
254
|
+
# We need to handle a rectangular causal mask when doing cached
|
255
|
+
# decoding. For generative inference, `decoder_sequence` will
|
256
|
+
# generally be length 1, and `cache` will be the full generation length.
|
257
|
+
if self_attention_cache is not None:
|
258
|
+
input_length = ops.shape(self_attention_cache)[2]
|
259
|
+
|
260
|
+
cache_update_index = (
|
261
|
+
0
|
262
|
+
if self_attention_cache_update_index is None
|
263
|
+
else self_attention_cache_update_index
|
264
|
+
)
|
265
|
+
|
266
|
+
causal_mask = compute_causal_mask(
|
267
|
+
batch_size, input_length, output_length, cache_update_index
|
268
|
+
)
|
269
|
+
|
270
|
+
return (
|
271
|
+
ops.minimum(decoder_mask, causal_mask)
|
272
|
+
if decoder_mask is not None
|
273
|
+
else causal_mask
|
274
|
+
)
|
275
|
+
|
276
|
+
def compute_output_shape(self, decoder_sequence_shape):
|
277
|
+
"""Computes the output shape of the layer.
|
278
|
+
|
279
|
+
Args:
|
280
|
+
decoder_sequence_shape: Shape of the decoder sequence input.
|
281
|
+
|
282
|
+
Returns:
|
283
|
+
Output shape, which is the same as the input shape.
|
284
|
+
"""
|
285
|
+
return decoder_sequence_shape
|
286
|
+
|
287
|
+
def get_config(self):
|
288
|
+
"""Returns the config of the layer.
|
289
|
+
|
290
|
+
Returns:
|
291
|
+
Dictionary containing the parameters used to initialize this layer.
|
292
|
+
"""
|
293
|
+
config = super().get_config()
|
294
|
+
config.update(
|
295
|
+
{
|
296
|
+
"intermediate_dim": self.intermediate_dim,
|
297
|
+
"num_query_heads": self.num_query_heads,
|
298
|
+
"rope_max_wavelength": self.rope_max_wavelength,
|
299
|
+
"rope_scaling_factor": self.rope_scaling_factor,
|
300
|
+
"num_key_value_heads": self.num_key_value_heads,
|
301
|
+
"activation": keras.activations.serialize(self.activation),
|
302
|
+
"layer_norm_epsilon": self.layer_norm_epsilon,
|
303
|
+
"kernel_initializer": keras.initializers.serialize(
|
304
|
+
self.kernel_initializer
|
305
|
+
),
|
306
|
+
"dropout": self.dropout,
|
307
|
+
}
|
308
|
+
)
|
309
|
+
return config
|
@@ -0,0 +1,38 @@
|
|
1
|
+
import keras
|
2
|
+
from keras import ops
|
3
|
+
|
4
|
+
|
5
|
+
class Qwen3LayerNorm(keras.layers.Layer):
|
6
|
+
"""A normalization layer for Qwen that implements RMS normalization."""
|
7
|
+
|
8
|
+
def __init__(self, head_dim=None, epsilon=1e-6, **kwargs):
|
9
|
+
super().__init__(**kwargs)
|
10
|
+
self.head_dim = head_dim
|
11
|
+
self.epsilon = epsilon
|
12
|
+
|
13
|
+
def build(self, input_shape):
|
14
|
+
if self.head_dim:
|
15
|
+
dim = self.head_dim
|
16
|
+
else:
|
17
|
+
dim = input_shape[-1]
|
18
|
+
|
19
|
+
self.scale = self.add_weight(
|
20
|
+
name="scale",
|
21
|
+
trainable=True,
|
22
|
+
shape=(dim,),
|
23
|
+
initializer="ones",
|
24
|
+
dtype=self.variable_dtype,
|
25
|
+
)
|
26
|
+
self.built = True
|
27
|
+
|
28
|
+
def call(self, x):
|
29
|
+
input_dtype = x.dtype
|
30
|
+
x = ops.cast(x, "float32")
|
31
|
+
var = ops.mean(ops.power(x, 2), axis=-1, keepdims=True)
|
32
|
+
x = x * ops.rsqrt(var + self.epsilon)
|
33
|
+
return ops.cast(x * self.scale, input_dtype)
|
34
|
+
|
35
|
+
def get_config(self):
|
36
|
+
config = super().get_config()
|
37
|
+
config.update({"epsilon": self.epsilon})
|
38
|
+
return config
|
@@ -0,0 +1,48 @@
|
|
1
|
+
from keras_hub.src.api_export import keras_hub_export
|
2
|
+
from keras_hub.src.models.qwen3.qwen3_backbone import Qwen3Backbone
|
3
|
+
from keras_hub.src.tokenizers.byte_pair_tokenizer import BytePairTokenizer
|
4
|
+
|
5
|
+
|
6
|
+
@keras_hub_export(
|
7
|
+
"keras_hub.models.Qwen3Tokenizer",
|
8
|
+
)
|
9
|
+
class Qwen3Tokenizer(BytePairTokenizer):
|
10
|
+
"""Tokenizer for Qwen3 models.
|
11
|
+
|
12
|
+
This tokenizer implements byte-pair encoding (BPE) for Qwen3 models,
|
13
|
+
handling special tokens like BOS (beginning of sequence) and EOS (end of
|
14
|
+
sequence).
|
15
|
+
|
16
|
+
Args:
|
17
|
+
vocabulary: Dictionary mapping tokens to token IDs, or path to
|
18
|
+
vocabulary file.
|
19
|
+
merges: List of BPE merges, or path to merges file.
|
20
|
+
bos_token: Beginning of sequence token. Defaults to None.
|
21
|
+
eos_token: End of sequence token. Defaults to "<|endoftext|>".
|
22
|
+
misc_special_tokens: Set of additional special tokens. Defaults to
|
23
|
+
empty set.
|
24
|
+
"""
|
25
|
+
|
26
|
+
backbone_cls = Qwen3Backbone
|
27
|
+
|
28
|
+
def __init__(
|
29
|
+
self,
|
30
|
+
vocabulary=None,
|
31
|
+
merges=None,
|
32
|
+
**kwargs,
|
33
|
+
):
|
34
|
+
# Add EOS token
|
35
|
+
eos_token = "<|im_end|>"
|
36
|
+
self._add_special_token(eos_token, "end_token")
|
37
|
+
|
38
|
+
pad_token = "<|endoftext|>"
|
39
|
+
self._add_special_token(pad_token, "pad_token")
|
40
|
+
|
41
|
+
self.start_token_id = None
|
42
|
+
self.start_token = None
|
43
|
+
|
44
|
+
super().__init__(
|
45
|
+
vocabulary=vocabulary,
|
46
|
+
merges=merges,
|
47
|
+
**kwargs,
|
48
|
+
)
|
@@ -4,8 +4,8 @@ backbone_presets = {
|
|
4
4
|
"qwen1.5_moe_2.7b_en": {
|
5
5
|
"metadata": {
|
6
6
|
"description": (
|
7
|
-
"24-layer Qwen MoE model with 2.7 billion active parameters "
|
8
|
-
"and 8 experts per MoE layer."
|
7
|
+
"24-layer Qwen MoE model with 2.7 billion active parameters "
|
8
|
+
"and 8 experts per MoE layer."
|
9
9
|
),
|
10
10
|
"params": 14315784192,
|
11
11
|
"path": "qwen-1.5-moe",
|
@@ -0,0 +1,155 @@
|
|
1
|
+
import numpy as np
|
2
|
+
|
3
|
+
from keras_hub.src.models.deit.deit_backbone import DeiTBackbone
|
4
|
+
|
5
|
+
backbone_cls = DeiTBackbone
|
6
|
+
|
7
|
+
|
8
|
+
def convert_backbone_config(transformers_config):
|
9
|
+
image_size = transformers_config["image_size"]
|
10
|
+
return {
|
11
|
+
"image_shape": (image_size, image_size, 3),
|
12
|
+
"patch_size": transformers_config["patch_size"],
|
13
|
+
"num_layers": transformers_config["num_hidden_layers"],
|
14
|
+
"num_heads": transformers_config["num_attention_heads"],
|
15
|
+
"hidden_dim": transformers_config["hidden_size"],
|
16
|
+
"intermediate_dim": transformers_config["intermediate_size"],
|
17
|
+
"dropout_rate": transformers_config["hidden_dropout_prob"],
|
18
|
+
"attention_dropout": transformers_config[
|
19
|
+
"attention_probs_dropout_prob"
|
20
|
+
],
|
21
|
+
"layer_norm_epsilon": transformers_config["layer_norm_eps"],
|
22
|
+
}
|
23
|
+
|
24
|
+
|
25
|
+
def convert_weights(backbone, loader, transformers_config):
|
26
|
+
def port_ln(keras_variable, weight_key):
|
27
|
+
loader.port_weight(keras_variable.gamma, f"{weight_key}.weight")
|
28
|
+
loader.port_weight(keras_variable.beta, f"{weight_key}.bias")
|
29
|
+
|
30
|
+
def port_dense(keras_variable, weight_key):
|
31
|
+
loader.port_weight(
|
32
|
+
keras_variable.kernel,
|
33
|
+
f"{weight_key}.weight",
|
34
|
+
hook_fn=lambda x, _: x.T,
|
35
|
+
)
|
36
|
+
if keras_variable.bias is not None:
|
37
|
+
loader.port_weight(keras_variable.bias, f"{weight_key}.bias")
|
38
|
+
|
39
|
+
def port_mha(keras_variable, weight_key, num_heads, hidden_dim):
|
40
|
+
# query
|
41
|
+
loader.port_weight(
|
42
|
+
keras_variable.query_dense.kernel,
|
43
|
+
f"{weight_key}.attention.query.weight",
|
44
|
+
hook_fn=lambda x, _: np.reshape(
|
45
|
+
x.T, (hidden_dim, num_heads, hidden_dim // num_heads)
|
46
|
+
),
|
47
|
+
)
|
48
|
+
loader.port_weight(
|
49
|
+
keras_variable.query_dense.bias,
|
50
|
+
f"{weight_key}.attention.query.bias",
|
51
|
+
hook_fn=lambda x, _: np.reshape(
|
52
|
+
x, (num_heads, hidden_dim // num_heads)
|
53
|
+
),
|
54
|
+
)
|
55
|
+
# key
|
56
|
+
loader.port_weight(
|
57
|
+
keras_variable.key_dense.kernel,
|
58
|
+
f"{weight_key}.attention.key.weight",
|
59
|
+
hook_fn=lambda x, _: np.reshape(
|
60
|
+
x.T, (hidden_dim, num_heads, hidden_dim // num_heads)
|
61
|
+
),
|
62
|
+
)
|
63
|
+
loader.port_weight(
|
64
|
+
keras_variable.key_dense.bias,
|
65
|
+
f"{weight_key}.attention.key.bias",
|
66
|
+
hook_fn=lambda x, _: np.reshape(
|
67
|
+
x, (num_heads, hidden_dim // num_heads)
|
68
|
+
),
|
69
|
+
)
|
70
|
+
# value
|
71
|
+
loader.port_weight(
|
72
|
+
keras_variable.value_dense.kernel,
|
73
|
+
f"{weight_key}.attention.value.weight",
|
74
|
+
hook_fn=lambda x, _: np.reshape(
|
75
|
+
x.T, (hidden_dim, num_heads, hidden_dim // num_heads)
|
76
|
+
),
|
77
|
+
)
|
78
|
+
loader.port_weight(
|
79
|
+
keras_variable.value_dense.bias,
|
80
|
+
f"{weight_key}.attention.value.bias",
|
81
|
+
hook_fn=lambda x, _: np.reshape(
|
82
|
+
x, (num_heads, hidden_dim // num_heads)
|
83
|
+
),
|
84
|
+
)
|
85
|
+
# output
|
86
|
+
loader.port_weight(
|
87
|
+
keras_variable.output_dense.kernel,
|
88
|
+
f"{weight_key}.output.dense.weight",
|
89
|
+
hook_fn=lambda x, _: np.reshape(
|
90
|
+
x.T, (num_heads, hidden_dim // num_heads, hidden_dim)
|
91
|
+
),
|
92
|
+
)
|
93
|
+
loader.port_weight(
|
94
|
+
keras_variable.output_dense.bias, f"{weight_key}.output.dense.bias"
|
95
|
+
)
|
96
|
+
|
97
|
+
loader.port_weight(
|
98
|
+
keras_variable=backbone.layers[1].patch_embedding.kernel,
|
99
|
+
hf_weight_key="deit.embeddings.patch_embeddings.projection.weight",
|
100
|
+
hook_fn=lambda x, _: np.transpose(x, (2, 3, 1, 0)),
|
101
|
+
)
|
102
|
+
|
103
|
+
loader.port_weight(
|
104
|
+
backbone.layers[1].patch_embedding.bias,
|
105
|
+
"deit.embeddings.patch_embeddings.projection.bias",
|
106
|
+
)
|
107
|
+
|
108
|
+
loader.port_weight(
|
109
|
+
backbone.layers[1].class_token,
|
110
|
+
"deit.embeddings.cls_token",
|
111
|
+
)
|
112
|
+
|
113
|
+
loader.port_weight(
|
114
|
+
backbone.layers[1].distillation_token,
|
115
|
+
"deit.embeddings.distillation_token",
|
116
|
+
)
|
117
|
+
|
118
|
+
loader.port_weight(
|
119
|
+
backbone.layers[1].position_embedding,
|
120
|
+
"deit.embeddings.position_embeddings",
|
121
|
+
)
|
122
|
+
|
123
|
+
encoder_layers = backbone.layers[2].encoder_layers
|
124
|
+
for i, encoder_block in enumerate(encoder_layers):
|
125
|
+
prefix = "deit.encoder.layer"
|
126
|
+
num_heads = encoder_block.num_heads
|
127
|
+
hidden_dim = encoder_block.hidden_dim
|
128
|
+
|
129
|
+
port_mha(
|
130
|
+
encoder_block.mha,
|
131
|
+
f"{prefix}.{i}.attention",
|
132
|
+
num_heads,
|
133
|
+
hidden_dim,
|
134
|
+
)
|
135
|
+
port_ln(encoder_block.layer_norm_1, f"{prefix}.{i}.layernorm_before")
|
136
|
+
port_ln(encoder_block.layer_norm_2, f"{prefix}.{i}.layernorm_after")
|
137
|
+
|
138
|
+
port_dense(encoder_block.mlp.dense, f"{prefix}.{i}.intermediate.dense")
|
139
|
+
port_dense(
|
140
|
+
encoder_block.output_layer.dense, f"{prefix}.{i}.output.dense"
|
141
|
+
)
|
142
|
+
port_ln(backbone.layers[2].layer_norm, "deit.layernorm")
|
143
|
+
|
144
|
+
|
145
|
+
def convert_head(task, loader, transformers_config):
|
146
|
+
prefix = "cls_classifier."
|
147
|
+
loader.port_weight(
|
148
|
+
task.output_dense.kernel,
|
149
|
+
hf_weight_key=prefix + "weight",
|
150
|
+
hook_fn=lambda x, _: x.T,
|
151
|
+
)
|
152
|
+
loader.port_weight(
|
153
|
+
task.output_dense.bias,
|
154
|
+
hf_weight_key=prefix + "bias",
|
155
|
+
)
|