keras-hub-nightly 0.21.0.dev202505050407__py3-none-any.whl → 0.21.0.dev202505070407__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/models/__init__.py +21 -0
- keras_hub/src/models/backbone.py +5 -2
- keras_hub/src/models/cspnet/cspnet_backbone.py +51 -26
- keras_hub/src/models/cspnet/cspnet_presets.py +38 -3
- keras_hub/src/models/mixtral/mixtral_attention.py +263 -0
- keras_hub/src/models/mixtral/mixtral_backbone.py +207 -0
- keras_hub/src/models/mixtral/mixtral_causal_lm.py +281 -0
- keras_hub/src/models/mixtral/mixtral_causal_lm_preprocessor.py +76 -0
- keras_hub/src/models/mixtral/mixtral_decoder.py +494 -0
- keras_hub/src/models/mixtral/mixtral_layer_norm.py +34 -0
- keras_hub/src/models/mixtral/mixtral_tokenizer.py +21 -0
- keras_hub/src/models/qwen/qwen_attention.py +3 -1
- keras_hub/src/models/qwen/qwen_presets.py +61 -0
- keras_hub/src/models/qwen_moe/__init__.py +0 -0
- keras_hub/src/models/qwen_moe/qwen_moe_attention.py +377 -0
- keras_hub/src/models/qwen_moe/qwen_moe_backbone.py +373 -0
- keras_hub/src/models/qwen_moe/qwen_moe_causal_lm.py +350 -0
- keras_hub/src/models/qwen_moe/qwen_moe_causal_lm_preprocessor.py +17 -0
- keras_hub/src/models/qwen_moe/qwen_moe_decoder.py +625 -0
- keras_hub/src/models/qwen_moe/qwen_moe_layernorm.py +32 -0
- keras_hub/src/models/qwen_moe/qwen_moe_tokenizer.py +46 -0
- keras_hub/src/models/retinanet/retinanet_image_converter.py +0 -13
- keras_hub/src/models/retinanet/retinanet_presets.py +2 -2
- keras_hub/src/models/segformer/segformer_image_segmenter_preprocessor.py +0 -18
- keras_hub/src/models/segformer/segformer_presets.py +12 -12
- keras_hub/src/models/task.py +5 -2
- keras_hub/src/utils/keras_utils.py +11 -0
- keras_hub/src/utils/preset_utils.py +69 -9
- keras_hub/src/utils/tensor_utils.py +27 -1
- keras_hub/src/utils/timm/convert_cspnet.py +94 -23
- keras_hub/src/utils/timm/preset_loader.py +6 -6
- keras_hub/src/utils/transformers/convert_mixtral.py +139 -0
- keras_hub/src/utils/transformers/convert_qwen_moe.py +253 -0
- keras_hub/src/utils/transformers/preset_loader.py +6 -0
- keras_hub/src/version.py +1 -1
- keras_hub/tokenizers/__init__.py +6 -0
- {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/RECORD +40 -22
- {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/WHEEL +0 -0
- {keras_hub_nightly-0.21.0.dev202505050407.dist-info → keras_hub_nightly-0.21.0.dev202505070407.dist-info}/top_level.txt +0 -0
keras_hub/models/__init__.py
CHANGED
@@ -348,6 +348,18 @@ from keras_hub.src.models.mit.mit_image_classifier import (
|
|
348
348
|
from keras_hub.src.models.mit.mit_image_classifier_preprocessor import (
|
349
349
|
MiTImageClassifierPreprocessor as MiTImageClassifierPreprocessor,
|
350
350
|
)
|
351
|
+
from keras_hub.src.models.mixtral.mixtral_backbone import (
|
352
|
+
MixtralBackbone as MixtralBackbone,
|
353
|
+
)
|
354
|
+
from keras_hub.src.models.mixtral.mixtral_causal_lm import (
|
355
|
+
MixtralCausalLM as MixtralCausalLM,
|
356
|
+
)
|
357
|
+
from keras_hub.src.models.mixtral.mixtral_causal_lm_preprocessor import (
|
358
|
+
MixtralCausalLMPreprocessor as MixtralCausalLMPreprocessor,
|
359
|
+
)
|
360
|
+
from keras_hub.src.models.mixtral.mixtral_tokenizer import (
|
361
|
+
MixtralTokenizer as MixtralTokenizer,
|
362
|
+
)
|
351
363
|
from keras_hub.src.models.mobilenet.mobilenet_backbone import (
|
352
364
|
MobileNetBackbone as MobileNetBackbone,
|
353
365
|
)
|
@@ -420,6 +432,15 @@ from keras_hub.src.models.qwen.qwen_tokenizer import (
|
|
420
432
|
from keras_hub.src.models.qwen.qwen_tokenizer import (
|
421
433
|
QwenTokenizer as QwenTokenizer,
|
422
434
|
)
|
435
|
+
from keras_hub.src.models.qwen_moe.qwen_moe_backbone import (
|
436
|
+
QwenMoeBackbone as QwenMoeBackbone,
|
437
|
+
)
|
438
|
+
from keras_hub.src.models.qwen_moe.qwen_moe_causal_lm import (
|
439
|
+
QwenMoeCausalLM as QwenMoeCausalLM,
|
440
|
+
)
|
441
|
+
from keras_hub.src.models.qwen_moe.qwen_moe_causal_lm_preprocessor import (
|
442
|
+
QwenMoeCausalLMPreprocessor as QwenMoeCausalLMPreprocessor,
|
443
|
+
)
|
423
444
|
from keras_hub.src.models.resnet.resnet_backbone import (
|
424
445
|
ResNetBackbone as ResNetBackbone,
|
425
446
|
)
|
keras_hub/src/models/backbone.py
CHANGED
@@ -177,14 +177,17 @@ class Backbone(keras.Model):
|
|
177
177
|
)
|
178
178
|
return loader.load_backbone(backbone_cls, load_weights, **kwargs)
|
179
179
|
|
180
|
-
def save_to_preset(self, preset_dir):
|
180
|
+
def save_to_preset(self, preset_dir, max_shard_size=10):
|
181
181
|
"""Save backbone to a preset directory.
|
182
182
|
|
183
183
|
Args:
|
184
184
|
preset_dir: The path to the local model preset directory.
|
185
|
+
max_shard_size: `int` or `float`. Maximum size in GB for each
|
186
|
+
sharded file. If `None`, no sharding will be done. Defaults to
|
187
|
+
`10`.
|
185
188
|
"""
|
186
189
|
saver = get_preset_saver(preset_dir)
|
187
|
-
saver.save_backbone(self)
|
190
|
+
saver.save_backbone(self, max_shard_size=max_shard_size)
|
188
191
|
|
189
192
|
def get_lora_target_names(self):
|
190
193
|
"""Returns list of layer names which are to be LoRA-fied.
|
@@ -81,7 +81,7 @@ class CSPNetBackbone(FeaturePyramidBackbone):
|
|
81
81
|
|
82
82
|
# Pretrained backbone
|
83
83
|
model = keras_hub.models.CSPNetBackbone.from_preset(
|
84
|
-
"
|
84
|
+
"csp_darknet_53_ra_imagenet"
|
85
85
|
)
|
86
86
|
model(input_data)
|
87
87
|
|
@@ -357,18 +357,6 @@ def bottleneck_block(
|
|
357
357
|
dtype=dtype,
|
358
358
|
name=f"{name}_bottleneck_block_bn_3",
|
359
359
|
)(x)
|
360
|
-
if activation == "leaky_relu":
|
361
|
-
x = layers.LeakyReLU(
|
362
|
-
negative_slope=0.01,
|
363
|
-
dtype=dtype,
|
364
|
-
name=f"{name}_bottleneck_block_activation_3",
|
365
|
-
)(x)
|
366
|
-
else:
|
367
|
-
x = layers.Activation(
|
368
|
-
activation,
|
369
|
-
dtype=dtype,
|
370
|
-
name=f"{name}_bottleneck_block_activation_3",
|
371
|
-
)(x)
|
372
360
|
|
373
361
|
x = layers.add(
|
374
362
|
[x, shortcut], dtype=dtype, name=f"{name}_bottleneck_block_add"
|
@@ -673,6 +661,13 @@ def cross_stage(
|
|
673
661
|
name=f"{name}_csp_activation_1",
|
674
662
|
)(x)
|
675
663
|
else:
|
664
|
+
if strides > 1:
|
665
|
+
x = layers.ZeroPadding2D(
|
666
|
+
1,
|
667
|
+
data_format=data_format,
|
668
|
+
dtype=dtype,
|
669
|
+
name=f"{name}_csp_conv_pad_1",
|
670
|
+
)(x)
|
676
671
|
x = layers.Conv2D(
|
677
672
|
filters=down_chs,
|
678
673
|
kernel_size=3,
|
@@ -882,6 +877,13 @@ def cross_stage3(
|
|
882
877
|
name=f"{name}_cs3_activation_1",
|
883
878
|
)(x)
|
884
879
|
else:
|
880
|
+
if strides > 1:
|
881
|
+
x = layers.ZeroPadding2D(
|
882
|
+
1,
|
883
|
+
data_format=data_format,
|
884
|
+
dtype=dtype,
|
885
|
+
name=f"{name}_cs3_conv_pad_1",
|
886
|
+
)(x)
|
885
887
|
x = layers.Conv2D(
|
886
888
|
filters=down_chs,
|
887
889
|
kernel_size=3,
|
@@ -1062,6 +1064,13 @@ def dark_stage(
|
|
1062
1064
|
name=f"{name}_dark_activation_1",
|
1063
1065
|
)(x)
|
1064
1066
|
else:
|
1067
|
+
if strides > 1:
|
1068
|
+
x = layers.ZeroPadding2D(
|
1069
|
+
1,
|
1070
|
+
data_format=data_format,
|
1071
|
+
dtype=dtype,
|
1072
|
+
name=f"{name}_dark_conv_pad_1",
|
1073
|
+
)(x)
|
1065
1074
|
x = layers.Conv2D(
|
1066
1075
|
filters=filters,
|
1067
1076
|
kernel_size=3,
|
@@ -1091,18 +1100,18 @@ def dark_stage(
|
|
1091
1100
|
dtype=dtype,
|
1092
1101
|
name=f"{name}_dark_activation_1",
|
1093
1102
|
)(x)
|
1094
|
-
|
1095
|
-
|
1096
|
-
|
1097
|
-
|
1098
|
-
|
1099
|
-
|
1100
|
-
|
1101
|
-
|
1102
|
-
|
1103
|
-
|
1104
|
-
|
1105
|
-
|
1103
|
+
for i in range(depth):
|
1104
|
+
x = block_fn(
|
1105
|
+
filters=block_channels,
|
1106
|
+
dilation=dilation,
|
1107
|
+
bottle_ratio=bottle_ratio,
|
1108
|
+
groups=groups,
|
1109
|
+
activation=activation,
|
1110
|
+
data_format=data_format,
|
1111
|
+
channel_axis=channel_axis,
|
1112
|
+
dtype=dtype,
|
1113
|
+
name=f"{name}_block_{i}",
|
1114
|
+
)(x)
|
1106
1115
|
return x
|
1107
1116
|
|
1108
1117
|
return apply
|
@@ -1135,6 +1144,13 @@ def create_csp_stem(
|
|
1135
1144
|
or (i == last_idx and strides > 2 and not pooling)
|
1136
1145
|
else 1
|
1137
1146
|
)
|
1147
|
+
if conv_strides > 1:
|
1148
|
+
x = layers.ZeroPadding2D(
|
1149
|
+
(kernel_size - 1) // 2,
|
1150
|
+
data_format=data_format,
|
1151
|
+
dtype=dtype,
|
1152
|
+
name=f"csp_stem_pad_{i}",
|
1153
|
+
)(x)
|
1138
1154
|
x = layers.Conv2D(
|
1139
1155
|
filters=chs,
|
1140
1156
|
kernel_size=kernel_size,
|
@@ -1167,10 +1183,19 @@ def create_csp_stem(
|
|
1167
1183
|
|
1168
1184
|
if pooling == "max":
|
1169
1185
|
assert strides > 2
|
1186
|
+
# Use manual padding to handle edge case scenario to ignore zero's
|
1187
|
+
# as max value instead consider negative values from Leaky Relu type
|
1188
|
+
# of activations.
|
1189
|
+
pad_width = [[1, 1], [1, 1]]
|
1190
|
+
if data_format == "channels_last":
|
1191
|
+
pad_width += [[0, 0]]
|
1192
|
+
else:
|
1193
|
+
pad_width = [[0, 0]] + pad_width
|
1194
|
+
pad_width = [[0, 0]] + pad_width
|
1195
|
+
x = ops.pad(x, pad_width=pad_width, constant_values=float("-inf"))
|
1170
1196
|
x = layers.MaxPooling2D(
|
1171
1197
|
pool_size=3,
|
1172
1198
|
strides=2,
|
1173
|
-
padding="same",
|
1174
1199
|
data_format=data_format,
|
1175
1200
|
dtype=dtype,
|
1176
1201
|
name="csp_stem_pool",
|
@@ -6,11 +6,46 @@ backbone_presets = {
|
|
6
6
|
"description": (
|
7
7
|
"A CSP-DarkNet (Cross-Stage-Partial) image classification model"
|
8
8
|
" pre-trained on the Randomly Augmented ImageNet 1k dataset at "
|
9
|
-
"a
|
9
|
+
"a 256x256 resolution."
|
10
10
|
),
|
11
|
-
"params":
|
11
|
+
"params": 27642184,
|
12
12
|
"path": "cspnet",
|
13
13
|
},
|
14
|
-
"kaggle_handle": "kaggle://keras/cspdarknet/keras/csp_darknet_53_ra_imagenet/
|
14
|
+
"kaggle_handle": "kaggle://keras/cspdarknet/keras/csp_darknet_53_ra_imagenet/2",
|
15
|
+
},
|
16
|
+
"csp_resnext_50_ra_imagenet": {
|
17
|
+
"metadata": {
|
18
|
+
"description": (
|
19
|
+
"A CSP-ResNeXt (Cross-Stage-Partial) image classification model"
|
20
|
+
" pre-trained on the Randomly Augmented ImageNet 1k dataset at "
|
21
|
+
"a 256x256 resolution."
|
22
|
+
),
|
23
|
+
"params": 20569896,
|
24
|
+
"path": "cspnet",
|
25
|
+
},
|
26
|
+
"kaggle_handle": "kaggle://keras/cspdarknet/keras/csp_resnext_50_ra_imagenet/1",
|
27
|
+
},
|
28
|
+
"csp_resnet_50_ra_imagenet": {
|
29
|
+
"metadata": {
|
30
|
+
"description": (
|
31
|
+
"A CSP-ResNet (Cross-Stage-Partial) image classification model"
|
32
|
+
" pre-trained on the Randomly Augmented ImageNet 1k dataset at "
|
33
|
+
"a 256x256 resolution."
|
34
|
+
),
|
35
|
+
"params": 21616168,
|
36
|
+
"path": "cspnet",
|
37
|
+
},
|
38
|
+
"kaggle_handle": "kaggle://keras/cspdarknet/keras/csp_resnet_50_ra_imagenet/1",
|
39
|
+
},
|
40
|
+
"darknet_53_imagenet": {
|
41
|
+
"metadata": {
|
42
|
+
"description": (
|
43
|
+
"A DarkNet image classification model pre-trained on the"
|
44
|
+
"ImageNet 1k dataset at a 256x256 resolution."
|
45
|
+
),
|
46
|
+
"params": 41609928,
|
47
|
+
"path": "cspnet",
|
48
|
+
},
|
49
|
+
"kaggle_handle": "kaggle://keras/cspdarknet/keras/darknet_53_imagenet/1",
|
15
50
|
},
|
16
51
|
}
|
@@ -0,0 +1,263 @@
|
|
1
|
+
import inspect
|
2
|
+
import math
|
3
|
+
|
4
|
+
import keras
|
5
|
+
from keras import ops
|
6
|
+
|
7
|
+
from keras_hub.src.layers.modeling.rotary_embedding import RotaryEmbedding
|
8
|
+
from keras_hub.src.utils.keras_utils import clone_initializer
|
9
|
+
from keras_hub.src.utils.keras_utils import fused_attention_op_available
|
10
|
+
from keras_hub.src.utils.keras_utils import gpu_supports_fused_attention_op
|
11
|
+
from keras_hub.src.utils.keras_utils import running_on_gpu
|
12
|
+
from keras_hub.src.utils.keras_utils import running_on_tpu
|
13
|
+
|
14
|
+
|
15
|
+
class CachedMixtralAttention(keras.layers.Layer):
|
16
|
+
"""A cached grounded query attention layer with sliding window."""
|
17
|
+
|
18
|
+
def __init__(
|
19
|
+
self,
|
20
|
+
num_query_heads,
|
21
|
+
num_key_value_heads,
|
22
|
+
rope_max_wavelength=10000,
|
23
|
+
rope_scaling_factor=1.0,
|
24
|
+
kernel_initializer="glorot_uniform",
|
25
|
+
sliding_window=512,
|
26
|
+
dropout=0,
|
27
|
+
**kwargs,
|
28
|
+
):
|
29
|
+
super().__init__(**kwargs)
|
30
|
+
self._num_query_heads = num_query_heads
|
31
|
+
self._num_key_value_heads = num_key_value_heads
|
32
|
+
self._sliding_window = sliding_window
|
33
|
+
self._dropout = dropout
|
34
|
+
|
35
|
+
self._num_key_value_groups = num_query_heads // num_key_value_heads
|
36
|
+
self._rope_max_wavelength = rope_max_wavelength
|
37
|
+
|
38
|
+
self._kernel_initializer = keras.initializers.get(
|
39
|
+
clone_initializer(kernel_initializer)
|
40
|
+
)
|
41
|
+
|
42
|
+
self._rope_scaling_factor = rope_scaling_factor
|
43
|
+
|
44
|
+
def build(self, inputs_shape):
|
45
|
+
# Einsum variables:
|
46
|
+
# b = batch size
|
47
|
+
# q = query length
|
48
|
+
# k = key/value length
|
49
|
+
# m = model dim
|
50
|
+
# u = num query heads
|
51
|
+
# v = num key/value heads
|
52
|
+
# h = head dim
|
53
|
+
self._hidden_dim = inputs_shape[-1]
|
54
|
+
self._head_dim = self._hidden_dim // self._num_query_heads
|
55
|
+
self._inv_norm_factor = 1.0 / math.sqrt(self._head_dim)
|
56
|
+
|
57
|
+
self.query_dense = keras.layers.EinsumDense(
|
58
|
+
equation="bqm,muh->bquh",
|
59
|
+
output_shape=(None, self._num_query_heads, self._head_dim),
|
60
|
+
kernel_initializer=self._kernel_initializer,
|
61
|
+
dtype=self.dtype_policy,
|
62
|
+
name="query",
|
63
|
+
)
|
64
|
+
self.query_dense.build(inputs_shape)
|
65
|
+
|
66
|
+
self.key_dense = keras.layers.EinsumDense(
|
67
|
+
equation="bkm,mvh->bkvh",
|
68
|
+
output_shape=(
|
69
|
+
None,
|
70
|
+
self._num_key_value_heads,
|
71
|
+
self._head_dim,
|
72
|
+
),
|
73
|
+
kernel_initializer=self._kernel_initializer,
|
74
|
+
dtype=self.dtype_policy,
|
75
|
+
name="key",
|
76
|
+
)
|
77
|
+
self.key_dense.build(inputs_shape)
|
78
|
+
|
79
|
+
self.value_dense = keras.layers.EinsumDense(
|
80
|
+
equation="bkm,mvh->bkvh",
|
81
|
+
output_shape=(
|
82
|
+
None,
|
83
|
+
self._num_key_value_heads,
|
84
|
+
self._head_dim,
|
85
|
+
),
|
86
|
+
kernel_initializer=self._kernel_initializer,
|
87
|
+
dtype=self.dtype_policy,
|
88
|
+
name="value",
|
89
|
+
)
|
90
|
+
self.value_dense.build(inputs_shape)
|
91
|
+
|
92
|
+
self._softmax = keras.layers.Softmax(
|
93
|
+
axis=-1,
|
94
|
+
dtype="float32",
|
95
|
+
name="attention_softmax",
|
96
|
+
)
|
97
|
+
|
98
|
+
self._dropout_layer = keras.layers.Dropout(
|
99
|
+
rate=self._dropout,
|
100
|
+
dtype=self.dtype_policy,
|
101
|
+
)
|
102
|
+
|
103
|
+
self._output_dense = keras.layers.EinsumDense(
|
104
|
+
equation="bquh,uhm->bqm",
|
105
|
+
output_shape=(None, self._hidden_dim),
|
106
|
+
kernel_initializer=self._kernel_initializer,
|
107
|
+
dtype=self.dtype_policy,
|
108
|
+
name="attention_output",
|
109
|
+
)
|
110
|
+
self._output_dense.build(
|
111
|
+
(None, None, self._num_query_heads, self._head_dim)
|
112
|
+
)
|
113
|
+
|
114
|
+
self.rotary_embedding_layer = RotaryEmbedding(
|
115
|
+
max_wavelength=self._rope_max_wavelength,
|
116
|
+
scaling_factor=self._rope_scaling_factor,
|
117
|
+
dtype=self.dtype_policy,
|
118
|
+
)
|
119
|
+
|
120
|
+
self._dot_product_equation = "bquh,bkuh->buqk"
|
121
|
+
self._combine_equation = "buqk,bkuh->bquh"
|
122
|
+
|
123
|
+
self.built = True
|
124
|
+
|
125
|
+
def call(
|
126
|
+
self,
|
127
|
+
hidden_states,
|
128
|
+
attention_mask=None,
|
129
|
+
cache=None,
|
130
|
+
cache_update_index=None,
|
131
|
+
training=None,
|
132
|
+
):
|
133
|
+
start_index = (
|
134
|
+
cache_update_index if cache_update_index is not None else 0
|
135
|
+
)
|
136
|
+
|
137
|
+
query = self.query_dense(hidden_states)
|
138
|
+
|
139
|
+
# Compute RoPE for queries
|
140
|
+
query = self.rotary_embedding_layer(query, start_index=start_index)
|
141
|
+
|
142
|
+
def _compute_key_value(x):
|
143
|
+
key, value = self.key_dense(x), self.value_dense(x)
|
144
|
+
# Compute RoPE for keys
|
145
|
+
key = self.rotary_embedding_layer(key, start_index=start_index)
|
146
|
+
return key, value
|
147
|
+
|
148
|
+
if cache is not None:
|
149
|
+
key_cache = cache[:, 0, ...]
|
150
|
+
value_cache = cache[:, 1, ...]
|
151
|
+
if cache_update_index is None:
|
152
|
+
key = key_cache
|
153
|
+
value = value_cache
|
154
|
+
else:
|
155
|
+
key_update, value_update = _compute_key_value(hidden_states)
|
156
|
+
start = [0, cache_update_index, 0, 0]
|
157
|
+
key = ops.slice_update(key_cache, start, key_update)
|
158
|
+
value = ops.slice_update(value_cache, start, value_update)
|
159
|
+
cache = ops.stack((key, value), axis=1)
|
160
|
+
else:
|
161
|
+
if cache_update_index is not None:
|
162
|
+
raise ValueError(
|
163
|
+
"`cache_update_index` should not be set if `cache` is "
|
164
|
+
f"`None`. Received: cache={cache}, "
|
165
|
+
f"cache_update_index={cache_update_index}"
|
166
|
+
)
|
167
|
+
key, value = _compute_key_value(hidden_states)
|
168
|
+
|
169
|
+
# [batch_shape, seq_len, num_key_value_heads, head_dim]
|
170
|
+
# -> [batch_shape, seq_len, num_heads, head_dim]
|
171
|
+
key = ops.repeat(key, repeats=self._num_key_value_groups, axis=2)
|
172
|
+
value = ops.repeat(value, repeats=self._num_key_value_groups, axis=2)
|
173
|
+
|
174
|
+
attention_output = self._compute_attention(
|
175
|
+
query, key, value, attention_mask
|
176
|
+
)
|
177
|
+
|
178
|
+
attention_output = self._dropout_layer(
|
179
|
+
attention_output, training=training
|
180
|
+
)
|
181
|
+
|
182
|
+
attention_output = self._output_dense(attention_output)
|
183
|
+
|
184
|
+
if cache is not None:
|
185
|
+
return attention_output, cache
|
186
|
+
return attention_output
|
187
|
+
|
188
|
+
def _masked_softmax(self, attention_scores, attention_mask=None):
|
189
|
+
if attention_mask is not None:
|
190
|
+
return self._softmax(
|
191
|
+
attention_scores, attention_mask[:, None, :, :]
|
192
|
+
)
|
193
|
+
return self._softmax(attention_scores)
|
194
|
+
|
195
|
+
def _use_fused_attention_op(self):
|
196
|
+
if not fused_attention_op_available():
|
197
|
+
return False
|
198
|
+
if self.dropout > 0.0:
|
199
|
+
return False
|
200
|
+
if running_on_gpu():
|
201
|
+
# GPU never supports softcap in the fused op.
|
202
|
+
if self.logit_soft_cap is not None:
|
203
|
+
return False
|
204
|
+
return gpu_supports_fused_attention_op()
|
205
|
+
elif running_on_tpu():
|
206
|
+
# TPU supports softcap with on keras >= 3.10.
|
207
|
+
sig = inspect.signature(ops.dot_product_attention)
|
208
|
+
return "attn_logits_soft_cap" in sig.parameters
|
209
|
+
else:
|
210
|
+
return False
|
211
|
+
|
212
|
+
def _compute_attention(self, query, key, value, attention_mask=None):
|
213
|
+
if self._use_fused_attention_op():
|
214
|
+
if attention_mask is not None:
|
215
|
+
attention_mask = ops.expand_dims(attention_mask, axis=1)
|
216
|
+
attention_mask = ops.cast(attention_mask, dtype="bool")
|
217
|
+
|
218
|
+
if self.logit_soft_cap:
|
219
|
+
kwargs = {"attn_logits_soft_cap": self.logit_soft_cap}
|
220
|
+
else:
|
221
|
+
kwargs = {}
|
222
|
+
|
223
|
+
attention_output = ops.dot_product_attention(
|
224
|
+
query,
|
225
|
+
key,
|
226
|
+
value,
|
227
|
+
mask=attention_mask,
|
228
|
+
scale=self._inv_norm_factor,
|
229
|
+
**kwargs,
|
230
|
+
)
|
231
|
+
return attention_output
|
232
|
+
|
233
|
+
attention_scores = ops.einsum(self._dot_product_equation, query, key)
|
234
|
+
attention_scores = ops.multiply(
|
235
|
+
attention_scores,
|
236
|
+
ops.cast(self._inv_norm_factor, self.compute_dtype),
|
237
|
+
)
|
238
|
+
attention_scores = self._masked_softmax(
|
239
|
+
attention_scores, attention_mask
|
240
|
+
)
|
241
|
+
attention_scores = ops.cast(attention_scores, self.compute_dtype)
|
242
|
+
attention_output = ops.einsum(
|
243
|
+
self._combine_equation, attention_scores, value
|
244
|
+
)
|
245
|
+
|
246
|
+
return attention_output
|
247
|
+
|
248
|
+
def get_config(self):
|
249
|
+
config = super().get_config()
|
250
|
+
config.update(
|
251
|
+
{
|
252
|
+
"num_query_heads": self._num_query_heads,
|
253
|
+
"num_key_value_heads": self._num_key_value_heads,
|
254
|
+
"rope_max_wavelength": self._rope_max_wavelength,
|
255
|
+
"rope_scaling_factor": self._rope_scaling_factor,
|
256
|
+
"kernel_initializer": keras.initializers.serialize(
|
257
|
+
self._kernel_initializer
|
258
|
+
),
|
259
|
+
"sliding_window": self._sliding_window,
|
260
|
+
"dropout": self._dropout,
|
261
|
+
}
|
262
|
+
)
|
263
|
+
return config
|