Opt-AI commited on
Commit
c8b83fc
·
verified ·
1 Parent(s): 11eab6b

Upload 8 files

Browse files
config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_sliding_window_pattern": 6,
3
+ "architectures": [
4
+ "GearForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "attn_logit_softcapping": null,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_gear.GearConfig",
11
+ "AutoModelForCausalLM": "modeling_gear.GearForCausalLM"
12
+ },
13
+ "bos_token_id": 1,
14
+ "conv_L_cache": 4,
15
+ "dtype": "bfloat16",
16
+ "eos_token_id": 2,
17
+ "final_logit_softcapping": null,
18
+ "head_dim": 64,
19
+ "hidden_activation": "relu6",
20
+ "hidden_size": 128,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 272,
23
+ "layer_types": [
24
+ "conv_mixer",
25
+ "conv_mixer",
26
+ "full_attention",
27
+ "conv_mixer",
28
+ "conv_mixer"
29
+ ],
30
+ "max_position_embeddings": 512,
31
+ "model_type": "gear",
32
+ "num_attention_heads": 2,
33
+ "num_hidden_layers": 5,
34
+ "num_key_value_heads": 1,
35
+ "pad_token_id": 0,
36
+ "query_pre_attn_scalar": 64,
37
+ "rms_norm_eps": 1e-06,
38
+ "rope_local_base_freq": 10000,
39
+ "rope_scaling": null,
40
+ "rope_theta": 1000000,
41
+ "sliding_window": 512,
42
+ "transformers_version": "4.57.3",
43
+ "use_bidirectional_attention": false,
44
+ "use_cache": true,
45
+ "vocab_size": 2048
46
+ }
configuration_gear.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 OptAI Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
17
+ from transformers.modeling_rope_utils import rope_config_validation
18
+ from transformers.utils import logging
19
+
20
+
21
+ class GearConfig(PretrainedConfig):
22
+
23
+ model_type = "gear"
24
+ keys_to_ignore_at_inference = ["past_key_values"]
25
+ base_model_tp_plan = {
26
+ "layers.*.self_attn.q_proj": "colwise",
27
+ "layers.*.self_attn.k_proj": "colwise",
28
+ "layers.*.self_attn.v_proj": "colwise",
29
+ "layers.*.self_attn.o_proj": "rowwise",
30
+ "layers.*.mlp.gate_proj": "colwise",
31
+ "layers.*.mlp.up_proj": "colwise",
32
+ "layers.*.mlp.down_proj": "rowwise",
33
+ }
34
+ base_model_pp_plan = {
35
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
36
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
37
+ "norm": (["hidden_states"], ["hidden_states"]),
38
+ }
39
+
40
+ def __init__(
41
+ self,
42
+ vocab_size=125_184,
43
+ hidden_size=1152,
44
+ intermediate_size=6912,
45
+ num_hidden_layers=26,
46
+ num_attention_heads=4,
47
+ num_key_value_heads=1,
48
+ head_dim=256,
49
+ hidden_activation="gelu_pytorch_tanh",
50
+ max_position_embeddings=131_072,
51
+ initializer_range=0.02,
52
+ rms_norm_eps=1e-6,
53
+ use_cache=True,
54
+ pad_token_id=125032,
55
+ eos_token_id=125031,
56
+ bos_token_id=125030,
57
+ tie_word_embeddings=True,
58
+ rope_theta=1_000_000.0,
59
+ attention_bias=False,
60
+ attention_dropout=0.0,
61
+ query_pre_attn_scalar=256,
62
+ sliding_window=512,
63
+ layer_types=None,
64
+ final_logit_softcapping=None,
65
+ attn_logit_softcapping=None,
66
+ rope_scaling=None,
67
+ rope_local_base_freq=10_000.0,
68
+ use_bidirectional_attention=False,
69
+ conv_L_cache=3,
70
+ **kwargs,
71
+ ):
72
+ super().__init__(
73
+ pad_token_id=pad_token_id,
74
+ bos_token_id=bos_token_id,
75
+ eos_token_id=eos_token_id,
76
+ tie_word_embeddings=tie_word_embeddings,
77
+ **kwargs,
78
+ )
79
+ self.vocab_size = vocab_size
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.hidden_size = hidden_size
82
+ self.intermediate_size = intermediate_size
83
+ self.num_hidden_layers = num_hidden_layers
84
+ self.num_attention_heads = num_attention_heads
85
+ self.head_dim = head_dim
86
+ self.num_key_value_heads = num_key_value_heads
87
+ self.initializer_range = initializer_range
88
+ self.rms_norm_eps = rms_norm_eps
89
+ self.use_cache = use_cache
90
+ self.rope_theta = rope_theta
91
+ self.attention_bias = attention_bias
92
+ self.attention_dropout = attention_dropout
93
+ self.hidden_activation = hidden_activation
94
+ self.query_pre_attn_scalar = query_pre_attn_scalar
95
+ self.sliding_window = sliding_window
96
+ self.final_logit_softcapping = final_logit_softcapping
97
+ self.attn_logit_softcapping = attn_logit_softcapping
98
+ self.layer_types = layer_types
99
+ self.use_bidirectional_attention = use_bidirectional_attention
100
+ if use_bidirectional_attention:
101
+ self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
102
+
103
+ self.rope_local_base_freq = rope_local_base_freq
104
+ self.rope_scaling = rope_scaling
105
+ rope_config_validation(self)
106
+
107
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
108
+ self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
109
+
110
+ self.conv_L_cache = conv_L_cache
111
+
112
+
113
+ __all__ = ["GearConfig"]
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 2
6
+ ],
7
+ "pad_token_id": 0,
8
+ "transformers_version": "4.57.3",
9
+ "use_cache": false
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e81a1f63ac3adbe23d5f9ecfbf4bb63197cc6894068910895474ab1a2bb6437
3
+ size 2079152
modeling_gear.py ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Optional, Union, Any
3
+
4
+ import math
5
+ import copy
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+
11
+ from transformers.activations import ACT2FN
12
+ from transformers.cache_utils import Cache, DynamicCache
13
+ from transformers.generation import GenerationMixin
14
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
15
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
16
+ from transformers.modeling_layers import (
17
+ GenericForQuestionAnswering,
18
+ GenericForSequenceClassification,
19
+ GenericForTokenClassification,
20
+ GradientCheckpointingLayer,
21
+ )
22
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
23
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
24
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
25
+ from transformers.processing_utils import Unpack
26
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
27
+ from transformers.utils.generic import check_model_inputs
28
+ from transformers.utils.import_utils import is_causal_conv1d_available
29
+ from .configuration_gear import GearConfig
30
+
31
+ if is_causal_conv1d_available():
32
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
33
+ else:
34
+ causal_conv1d_fn, causal_conv1d_update = None, None
35
+
36
+ kernel_modules = (causal_conv1d_fn, causal_conv1d_update)
37
+ is_fast_path_available = all(kernel_modules)
38
+
39
+
40
+ class GearHybridKVConvCache:
41
+ """
42
+ Attention and conv cache for Gear.
43
+
44
+ It stores the Key and Value states as a list of tensors, one for each layer.
45
+ Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`.
46
+ Key-Value Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`.
47
+ """
48
+
49
+ # Override @property existing in Cache
50
+ max_batch_size = None
51
+ is_compileable = False
52
+ key_cache = None
53
+ value_cache = None
54
+
55
+ def __init__(
56
+ self,
57
+ config: GearConfig,
58
+ max_batch_size: int,
59
+ dtype: torch.dtype = torch.float32,
60
+ device: Union[torch.device, str, None] = None,
61
+ ):
62
+ self.key_cache = []
63
+ self.value_cache = []
64
+ self.max_batch_size = max_batch_size
65
+ self.layer_types = config.layer_types
66
+ self.first_attention_layer = self.layer_types.index("full_attention")
67
+ self.conv_L_cache = config.conv_L_cache
68
+ self._dtype = dtype
69
+
70
+ self.key_conv_cache: list[torch.Tensor] = []
71
+ self.value_conv_cache: list[torch.Tensor] = []
72
+ device = torch.device(device) if device is not None else None
73
+
74
+ for _ in range(config.num_hidden_layers):
75
+ key_conv_state = torch.zeros(
76
+ self.max_batch_size,
77
+ config.num_key_value_heads * config.head_dim,
78
+ self.conv_L_cache,
79
+ dtype=self._dtype,
80
+ device=device,
81
+ )
82
+ value_conv_state = torch.zeros_like(key_conv_state)
83
+
84
+ torch._dynamo.mark_static_address(key_conv_state)
85
+ torch._dynamo.mark_static_address(value_conv_state)
86
+
87
+ self.key_conv_cache.append(key_conv_state)
88
+ self.value_conv_cache.append(value_conv_state)
89
+
90
+
91
+ def update(
92
+ self,
93
+ key_states: torch.Tensor,
94
+ value_states: torch.Tensor,
95
+ layer_idx: int,
96
+ cache_kwargs: Optional[dict[str, Any]] = None,
97
+ ) -> tuple[torch.Tensor, torch.Tensor]:
98
+ """
99
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
100
+
101
+ Parameters:
102
+ key_states (`torch.Tensor`):
103
+ The new key states to cache.
104
+ value_states (`torch.Tensor`):
105
+ The new value states to cache.
106
+ layer_idx (`int`):
107
+ The index of the layer to cache the states for.
108
+ cache_kwargs (`Dict[str, Any]`, `optional`):
109
+ Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
110
+
111
+ Return:
112
+ A tuple containing the updated key and value states.
113
+ """
114
+ # Update the cache
115
+ if key_states is not None:
116
+ if len(self.key_cache) <= layer_idx:
117
+ # There may be skipped layers, fill them with empty lists
118
+ for _ in range(len(self.key_cache), layer_idx):
119
+ self.key_cache.append(torch.tensor([]))
120
+ self.value_cache.append(torch.tensor([]))
121
+ self.key_cache.append(key_states)
122
+ self.value_cache.append(value_states)
123
+ elif (
124
+ not self.key_cache[layer_idx].numel() # prefers not t.numel() to len(t) == 0 to export the model
125
+ ): # fills previously skipped layers; checking for tensor causes errors
126
+ self.key_cache[layer_idx] = key_states
127
+ self.value_cache[layer_idx] = value_states
128
+ else:
129
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
130
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
131
+
132
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
133
+
134
+ def reorder_cache(self, beam_idx: torch.LongTensor):
135
+ """Reorders the cache for beam search, given the selected beam indices."""
136
+ for layer_idx in range(len(self.key_cache)):
137
+ device = self.key_cache[layer_idx].device
138
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
139
+ device = self.value_cache[layer_idx].device
140
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
141
+
142
+ device = self.key_conv_cache[layer_idx].device
143
+ self.key_conv_cache[layer_idx] = self.key_conv_cache[layer_idx].index_select(0, beam_idx.to(device))
144
+ device = self.value_conv_cache[layer_idx].device
145
+ self.value_conv_cache[layer_idx] = self.value_conv_cache[layer_idx].index_select(0, beam_idx.to(device))
146
+
147
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
148
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
149
+ # take any layer that contains cache and not empty tensor
150
+ layer_idx = self.first_attention_layer if self.layer_types[layer_idx] != "full_attention" else layer_idx
151
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
152
+ return 0
153
+ return self.key_cache[layer_idx].shape[-2]
154
+
155
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
156
+ """
157
+ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
158
+ the given layer at `layer_idx`.
159
+ The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size),
160
+ for each layer.
161
+ """
162
+ full_mask_kv_offset = 0
163
+ query_length = cache_position.shape[0]
164
+ past_seen_tokens = self.get_seq_length()
165
+ kv_length = query_length + past_seen_tokens
166
+ return kv_length, full_mask_kv_offset
167
+
168
+ def crop(self, max_length: int):
169
+ """Crop the cache to the given length"""
170
+ if max_length < 0:
171
+ max_length = self.get_seq_length() - abs(max_length)
172
+
173
+ if self.get_seq_length() <= max_length:
174
+ return
175
+
176
+ for idx in range(len(self.key_cache)):
177
+ if self.key_cache[idx].numel():
178
+ self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
179
+ self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
180
+
181
+ def __len__(self) -> int:
182
+ return len(self.key_cache)
183
+
184
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
185
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
186
+
187
+ def reset(self):
188
+ for layer_idx in range(len(self.key_conv_cache)):
189
+ self.key_conv_cache[layer_idx].zero_()
190
+ self.value_conv_cache[layer_idx].zero_()
191
+
192
+
193
+
194
+ class GearTextScaledWordEmbedding(nn.Embedding):
195
+ """
196
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
197
+ """
198
+
199
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
200
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
201
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
202
+
203
+ def forward(self, input_ids: torch.Tensor):
204
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
205
+
206
+
207
+ class GearRMSNorm(nn.Module):
208
+ def __init__(self, dim: int, eps: float = 1e-6):
209
+ super().__init__()
210
+ self.eps = eps
211
+ self.weight = nn.Parameter(torch.zeros(dim))
212
+
213
+ def _norm(self, x):
214
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
215
+
216
+ def forward(self, x):
217
+ output = self._norm(x.float())
218
+ output = output * (1.0 + self.weight.float())
219
+
220
+ return output.type_as(x)
221
+
222
+ def extra_repr(self):
223
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
224
+
225
+
226
+ class GearRMSNormGated(nn.Module):
227
+ def __init__(self, config, hidden_size, eps=1e-6, **kwargs):
228
+ super().__init__()
229
+ self.weight = nn.Parameter(torch.ones(hidden_size))
230
+ self.eps = eps
231
+ self.act_fn = ACT2FN[config.hidden_activation]
232
+
233
+ def _norm(self, x):
234
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
235
+
236
+ def forward(self, x, gate=None):
237
+ # Norm before gate
238
+ output = self._norm(x.float())
239
+ output = output * (1.0 + self.weight.float())
240
+ output = output * self.act_fn(gate.float())
241
+
242
+ return output.type_as(x)
243
+
244
+
245
+ class GearMLP(nn.Module):
246
+ def __init__(self, config: GearConfig):
247
+ super().__init__()
248
+ self.config = config
249
+ self.hidden_size = config.hidden_size
250
+ self.intermediate_size = config.intermediate_size
251
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
252
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
253
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
254
+ self.act_fn = ACT2FN[config.hidden_activation]
255
+
256
+ def forward(self, x):
257
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
258
+ return down_proj
259
+
260
+
261
+ class GearRotaryEmbedding(nn.Module):
262
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
263
+
264
+ def __init__(self, config: GearConfig, device=None):
265
+ super().__init__()
266
+ # BC: "rope_type" was originally "type"
267
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
268
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
269
+ else:
270
+ self.rope_type = "default"
271
+
272
+ self.max_seq_len_cached = config.max_position_embeddings
273
+ self.original_max_seq_len = config.max_position_embeddings
274
+ self.config = config
275
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
276
+
277
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
278
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
279
+ self.original_inv_freq = self.inv_freq
280
+
281
+ @torch.no_grad()
282
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
283
+ def forward(self, x, position_ids):
284
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
285
+ position_ids_expanded = position_ids[:, None, :].float()
286
+
287
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
288
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
289
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
290
+ emb = torch.cat((freqs, freqs), dim=-1)
291
+ cos = emb.cos() * self.attention_scaling
292
+ sin = emb.sin() * self.attention_scaling
293
+
294
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
295
+
296
+
297
+ def rotate_half(x):
298
+ """Rotates half the hidden dims of the input."""
299
+ x1 = x[..., : x.shape[-1] // 2]
300
+ x2 = x[..., x.shape[-1] // 2 :]
301
+ return torch.cat((-x2, x1), dim=-1)
302
+
303
+
304
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
305
+ """Applies Rotary Position Embedding to the query and key tensors.
306
+
307
+ Args:
308
+ q (`torch.Tensor`): The query tensor.
309
+ k (`torch.Tensor`): The key tensor.
310
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
311
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
312
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
313
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
314
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
315
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
316
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
317
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
318
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
319
+ Returns:
320
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
321
+ """
322
+ cos = cos.unsqueeze(unsqueeze_dim)
323
+ sin = sin.unsqueeze(unsqueeze_dim)
324
+ q_embed = (q * cos) + (rotate_half(q) * sin)
325
+ k_embed = (k * cos) + (rotate_half(k) * sin)
326
+ return q_embed, k_embed
327
+
328
+
329
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
330
+ """
331
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
332
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
333
+ """
334
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
335
+ if n_rep == 1:
336
+ return hidden_states
337
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
338
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
339
+
340
+
341
+ def eager_attention_forward(
342
+ module: nn.Module,
343
+ query: torch.Tensor,
344
+ key: torch.Tensor,
345
+ value: torch.Tensor,
346
+ attention_mask: Optional[torch.Tensor],
347
+ dropout: float = 0.0,
348
+ scaling: Optional[float] = None,
349
+ softcap: Optional[float] = None,
350
+ **kwargs,
351
+ ) -> tuple[torch.Tensor, torch.Tensor]:
352
+ if scaling is None:
353
+ scaling = module.head_dim**-0.5
354
+
355
+ key_states = repeat_kv(key, module.num_key_value_groups)
356
+ value_states = repeat_kv(value, module.num_key_value_groups)
357
+
358
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
359
+
360
+ if softcap is not None:
361
+ attn_weights = attn_weights / softcap
362
+ attn_weights = torch.tanh(attn_weights)
363
+ attn_weights = attn_weights * softcap
364
+ if attention_mask is not None: # no matter the length, we just slice it
365
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
366
+ attn_weights = attn_weights + causal_mask
367
+
368
+ # upcast attention to fp32
369
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
370
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
371
+ attn_output = torch.matmul(attn_weights, value_states)
372
+ attn_output = attn_output.transpose(1, 2).contiguous()
373
+ return attn_output, attn_weights
374
+
375
+
376
+ class GearAttention(nn.Module):
377
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
378
+
379
+ def __init__(self, config: GearConfig, layer_idx: int):
380
+ super().__init__()
381
+ self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
382
+ self.config = config
383
+ self.layer_idx = layer_idx
384
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
385
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
386
+ self.scaling = config.query_pre_attn_scalar**-0.5
387
+ self.attention_dropout = self.config.attention_dropout
388
+ self.is_causal = not self.config.use_bidirectional_attention
389
+
390
+ self.q_proj = nn.Linear(
391
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
392
+ )
393
+ self.k_proj = nn.Linear(
394
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
395
+ )
396
+ self.v_proj = nn.Linear(
397
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
398
+ )
399
+ self.o_proj = nn.Linear(
400
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
401
+ )
402
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
403
+ self.sliding_window = config.sliding_window if self.is_sliding else None
404
+
405
+ self.q_norm = GearRMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
406
+ self.k_norm = GearRMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ position_embeddings: torch.Tensor,
412
+ attention_mask: Optional[torch.Tensor],
413
+ past_key_values: Optional[Cache] = None,
414
+ cache_position: Optional[torch.LongTensor] = None,
415
+ **kwargs: Unpack[FlashAttentionKwargs],
416
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
417
+ input_shape = hidden_states.shape[:-1]
418
+ hidden_shape = (*input_shape, -1, self.head_dim)
419
+
420
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
421
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
422
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
423
+
424
+ query_states = self.q_norm(query_states)
425
+ key_states = self.k_norm(key_states)
426
+
427
+ cos, sin = position_embeddings
428
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
429
+
430
+ if past_key_values is not None:
431
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
432
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
433
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
434
+
435
+ attention_interface: Callable = eager_attention_forward
436
+ if self.config._attn_implementation != "eager":
437
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
438
+
439
+ attn_output, attn_weights = attention_interface(
440
+ self,
441
+ query_states,
442
+ key_states,
443
+ value_states,
444
+ attention_mask,
445
+ dropout=self.attention_dropout if self.training else 0.0,
446
+ scaling=self.scaling,
447
+ sliding_window=self.sliding_window,
448
+ **kwargs,
449
+ )
450
+
451
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
452
+ attn_output = self.o_proj(attn_output)
453
+ return attn_output, attn_weights
454
+
455
+
456
+ class GearConvKVGatedMixer(nn.Module):
457
+ """Convolutional Key-Value Gated Mixer is using Key-Value Convolution State and Sigmoid Gating"""
458
+
459
+ def __init__(
460
+ self,
461
+ config: GearConfig,
462
+ layer_idx: int,
463
+ ):
464
+ super().__init__()
465
+ self.config = config
466
+ self.layer_idx = layer_idx
467
+ self.hidden_size = config.hidden_size
468
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
469
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
470
+ self.L_cache = config.conv_L_cache
471
+ self.bias = config.attention_bias
472
+
473
+ # self.adaptive_scaling = nn.Parameter(torch.tensor(1.0))
474
+
475
+ self.key_conv = nn.Conv1d(
476
+ in_channels=config.num_key_value_heads * self.head_dim,
477
+ out_channels=config.num_key_value_heads * self.head_dim,
478
+ kernel_size=self.L_cache,
479
+ groups=config.num_key_value_heads * self.head_dim,
480
+ bias=self.bias,
481
+ padding=self.L_cache - 1,
482
+ )
483
+ self.value_conv = nn.Conv1d(
484
+ in_channels=config.num_key_value_heads * self.head_dim,
485
+ out_channels=config.num_key_value_heads * self.head_dim,
486
+ kernel_size=self.L_cache,
487
+ groups=config.num_key_value_heads * self.head_dim,
488
+ bias=self.bias,
489
+ padding=self.L_cache - 1,
490
+ )
491
+
492
+ self.q_proj = nn.Linear(
493
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=self.bias
494
+ )
495
+ self.k_proj = nn.Linear(
496
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=self.bias
497
+ )
498
+ self.v_proj = nn.Linear(
499
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=self.bias
500
+ )
501
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=self.bias)
502
+
503
+ self.q_norm = GearRMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
504
+ self.k_norm = GearRMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
505
+
506
+ def apply_mask_to_padding_states(self, hidden_states, attention_mask):
507
+ """
508
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
509
+ """
510
+ # NOTE: attention mask is a 2D boolean tensor
511
+ if hidden_states.shape[1] == 1:
512
+ return hidden_states
513
+
514
+ if attention_mask is not None and attention_mask.dim() == 2 and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
515
+ dtype = hidden_states.dtype
516
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
517
+
518
+ return hidden_states
519
+
520
+ def expand_kv(self, kv_states):
521
+ # kv_states: [B, S, kv_heads * head_dim]
522
+ B, S, _ = kv_states.shape
523
+ kv_states = kv_states.view(B, S, self.config.num_key_value_heads, self.head_dim)
524
+ kv_states = kv_states[:, :, :, None, :].expand(
525
+ B,
526
+ S,
527
+ self.config.num_key_value_heads,
528
+ self.num_key_value_groups,
529
+ self.head_dim,
530
+ )
531
+ return kv_states.reshape(B, S, self.config.num_attention_heads * self.head_dim)
532
+
533
+ def cuda_kernels_forward(
534
+ self,
535
+ hidden_states: torch.Tensor,
536
+ past_key_values: GearHybridKVConvCache | None = None,
537
+ cache_position: torch.LongTensor | None = None,
538
+ attention_mask: torch.Tensor | None = None,
539
+ ):
540
+ input_shape = hidden_states.shape[:-1]
541
+ hidden_shape = (*input_shape, -1, self.head_dim)
542
+ hidden_states = self.apply_mask_to_padding_states(hidden_states, attention_mask)
543
+
544
+ query = self.q_proj(hidden_states).view(hidden_shape)
545
+ key = self.k_proj(hidden_states).view(hidden_shape)
546
+ value = self.v_proj(hidden_states).transpose(-1, -2)
547
+
548
+ query = self.q_norm(query).reshape(*input_shape, -1)
549
+ key = self.k_norm(key).reshape(*input_shape, -1).transpose(-1, -2)
550
+
551
+ key_conv_weights = self.key_conv.weight.view(self.key_conv.weight.size(0), self.key_conv.weight.size(2))
552
+ value_conv_weights = self.value_conv.weight.view(self.value_conv.weight.size(0), self.value_conv.weight.size(2))
553
+
554
+ if past_key_values is not None and cache_position[0] > 0:
555
+ key = causal_conv1d_update(
556
+ key.squeeze(-1),
557
+ past_key_values.key_conv_cache[self.layer_idx],
558
+ key_conv_weights,
559
+ self.key_conv.bias,
560
+ None,
561
+ )
562
+ value = causal_conv1d_update(
563
+ value.squeeze(-1),
564
+ past_key_values.value_conv_cache[self.layer_idx],
565
+ value_conv_weights,
566
+ self.value_conv.bias,
567
+ None,
568
+ )
569
+
570
+ key, value = key.unsqueeze(-1), value.unsqueeze(-1)
571
+ else:
572
+ if past_key_values is not None:
573
+ key_conv_state = nn.functional.pad(key, (self.L_cache - key.shape[-1], 0))
574
+ past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
575
+ value_conv_state = nn.functional.pad(value, (self.L_cache - value.shape[-1], 0))
576
+ past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
577
+
578
+ key = causal_conv1d_fn(key, key_conv_weights, self.key_conv.bias, activation=None)
579
+ value = causal_conv1d_fn(value, value_conv_weights, self.value_conv.bias, activation=None)
580
+
581
+ key = self.expand_kv(key.transpose(-1, -2))
582
+ value = self.expand_kv(value.transpose(-1, -2))
583
+
584
+ mixer_weights = torch.sigmoid(query * key)
585
+ core_mixer_out = mixer_weights * value
586
+
587
+ core_mixer_out = self.o_proj(core_mixer_out)
588
+ return core_mixer_out
589
+
590
+ def torch_native_forward(
591
+ self,
592
+ hidden_states: torch.Tensor,
593
+ past_key_values: GearHybridKVConvCache | None = None,
594
+ cache_position: torch.LongTensor | None = None,
595
+ attention_mask: torch.Tensor | None = None,
596
+ ):
597
+ seqlen = hidden_states.shape[1]
598
+
599
+ input_shape = hidden_states.shape[:-1]
600
+ hidden_shape = (*input_shape, -1, self.head_dim)
601
+ hidden_states = self.apply_mask_to_padding_states(hidden_states, attention_mask)
602
+
603
+ query = self.q_proj(hidden_states).view(hidden_shape)
604
+ key = self.k_proj(hidden_states).view(hidden_shape)
605
+ value = self.v_proj(hidden_states).transpose(-1, -2)
606
+
607
+ query = self.q_norm(query).reshape(*input_shape, -1)
608
+ key = self.k_norm(key).reshape(*input_shape, -1).transpose(-1, -2)
609
+
610
+ # NOTE: This native path is kept numerically close to the
611
+ # causal_conv1d fast path:
612
+ # - the new token always goes to the *last* cache slot (matching
613
+ # causal_conv1d_update semantics) instead of the previous
614
+ # clamped-cache_position behavior that misplaced the first
615
+ # decode steps.
616
+ # - depthwise reductions are accumulated in fp32 then cast back,
617
+ # matching the CUDA kernel which also accumulates in fp32.
618
+ if past_key_values is not None and cache_position[0] > 0:
619
+ key_conv_state = past_key_values.key_conv_cache[self.layer_idx]
620
+ key_conv_state = key_conv_state.roll(shifts=-1, dims=-1)
621
+ key_conv_state[:, :, -1] = key.squeeze(-1).to(
622
+ device=key_conv_state.device, dtype=key_conv_state.dtype
623
+ )
624
+ past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
625
+ key_fp32 = (
626
+ key_conv_state.to(key.device, dtype=torch.float32)
627
+ * self.key_conv.weight[:, 0, :].to(torch.float32)
628
+ ).sum(dim=-1)
629
+ key = key_fp32.to(self.k_proj.weight.dtype)
630
+
631
+ value_conv_state = past_key_values.value_conv_cache[self.layer_idx]
632
+ value_conv_state = value_conv_state.roll(shifts=-1, dims=-1)
633
+ value_conv_state[:, :, -1] = value.squeeze(-1).to(
634
+ device=value_conv_state.device, dtype=value_conv_state.dtype
635
+ )
636
+ past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
637
+ value_fp32 = (
638
+ value_conv_state.to(value.device, dtype=torch.float32)
639
+ * self.value_conv.weight[:, 0, :].to(torch.float32)
640
+ ).sum(dim=-1)
641
+ value = value_fp32.to(self.v_proj.weight.dtype)
642
+
643
+ if self.bias and self.key_conv.bias is not None:
644
+ key = key + self.key_conv.bias
645
+ if self.bias and self.value_conv.bias is not None:
646
+ value = value + self.value_conv.bias
647
+
648
+ key, value = key.unsqueeze(-1), value.unsqueeze(-1)
649
+ else:
650
+ if past_key_values is not None:
651
+ key_conv_state = nn.functional.pad(key, (self.L_cache - key.shape[-1], 0))
652
+ past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
653
+ value_conv_state = nn.functional.pad(value, (self.L_cache - value.shape[-1], 0))
654
+ past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
655
+
656
+ # Run conv in fp32 to match the CUDA kernel's accumulation
657
+ # precision; cast result back to the parameter dtype.
658
+ orig_dtype = self.k_proj.weight.dtype
659
+ key_fp = nn.functional.conv1d(
660
+ key.to(torch.float32),
661
+ self.key_conv.weight.to(torch.float32),
662
+ bias=(self.key_conv.bias.to(torch.float32)
663
+ if self.key_conv.bias is not None else None),
664
+ stride=self.key_conv.stride,
665
+ padding=self.key_conv.padding,
666
+ dilation=self.key_conv.dilation,
667
+ groups=self.key_conv.groups,
668
+ )
669
+ value_fp = nn.functional.conv1d(
670
+ value.to(torch.float32),
671
+ self.value_conv.weight.to(torch.float32),
672
+ bias=(self.value_conv.bias.to(torch.float32)
673
+ if self.value_conv.bias is not None else None),
674
+ stride=self.value_conv.stride,
675
+ padding=self.value_conv.padding,
676
+ dilation=self.value_conv.dilation,
677
+ groups=self.value_conv.groups,
678
+ )
679
+ key = key_fp[..., :seqlen].to(orig_dtype)
680
+ value = value_fp[..., :seqlen].to(orig_dtype)
681
+
682
+ key = self.expand_kv(key.transpose(-1, -2))
683
+ value = self.expand_kv(value.transpose(-1, -2))
684
+
685
+ mixer_weights = torch.sigmoid(query * key)
686
+ core_mixer_out = mixer_weights * value
687
+
688
+ core_mixer_out = self.o_proj(core_mixer_out)
689
+ return core_mixer_out
690
+
691
+ def forward(
692
+ self,
693
+ hidden_states: torch.Tensor,
694
+ past_key_values: Cache | None = None,
695
+ cache_position: torch.LongTensor = None,
696
+ attention_mask: torch.Tensor | None = None,
697
+ ):
698
+ if is_fast_path_available:
699
+ return self.cuda_kernels_forward(hidden_states, past_key_values, cache_position, attention_mask)
700
+ return self.torch_native_forward(hidden_states, past_key_values, cache_position, attention_mask)
701
+
702
+
703
+ class GearDecoderLayer(GradientCheckpointingLayer):
704
+ def __init__(self, config: GearConfig, layer_idx: int):
705
+ super().__init__()
706
+ self.config = config
707
+ self.hidden_size = config.hidden_size
708
+ self.layer_idx = layer_idx
709
+ self.attention_type = config.layer_types[layer_idx]
710
+ if self.attention_type == "conv_mixer":
711
+ self.local_mixer = GearConvKVGatedMixer(config=config, layer_idx=layer_idx)
712
+ else:
713
+ self.self_attn = GearAttention(config=config, layer_idx=layer_idx)
714
+ self.mlp = GearMLP(config)
715
+ self.input_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
716
+ self.post_attention_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
717
+ self.pre_feedforward_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
718
+ self.post_feedforward_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
719
+
720
+ def forward(
721
+ self,
722
+ hidden_states: torch.Tensor,
723
+ position_embeddings_global: torch.Tensor,
724
+ position_embeddings_local: torch.Tensor,
725
+ attention_mask: Optional[torch.Tensor] = None,
726
+ position_ids: Optional[torch.LongTensor] = None,
727
+ past_key_values: Optional[Cache] = None,
728
+ output_attentions: Optional[bool] = False,
729
+ use_cache: Optional[bool] = False,
730
+ cache_position: Optional[torch.LongTensor] = None,
731
+ **kwargs,
732
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
733
+ residual = hidden_states
734
+
735
+ hidden_states = self.input_layernorm(hidden_states)
736
+
737
+ if self.attention_type == "conv_mixer":
738
+ hidden_states = self.local_mixer(
739
+ hidden_states=hidden_states,
740
+ past_key_values=past_key_values,
741
+ cache_position=cache_position,
742
+ attention_mask=attention_mask,
743
+ )
744
+ else:
745
+ # apply global RoPE to non-sliding layer only
746
+ if self.self_attn.is_sliding:
747
+ position_embeddings = position_embeddings_local
748
+ else:
749
+ position_embeddings = position_embeddings_global
750
+
751
+ hidden_states, self_attn_weights = self.self_attn(
752
+ hidden_states=hidden_states,
753
+ position_embeddings=position_embeddings,
754
+ attention_mask=attention_mask,
755
+ position_ids=position_ids,
756
+ past_key_values=past_key_values,
757
+ output_attentions=output_attentions,
758
+ use_cache=use_cache,
759
+ cache_position=cache_position,
760
+ **kwargs,
761
+ )
762
+ hidden_states = self.post_attention_layernorm(hidden_states)
763
+ hidden_states = residual + hidden_states
764
+
765
+ residual = hidden_states
766
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
767
+ hidden_states = self.mlp(hidden_states)
768
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
769
+ hidden_states = residual + hidden_states
770
+
771
+ outputs = (hidden_states,)
772
+
773
+ if output_attentions:
774
+ outputs += (self_attn_weights,)
775
+
776
+ return outputs
777
+
778
+
779
+ @auto_docstring
780
+ class GearPreTrainedModel(PreTrainedModel):
781
+ config: GearConfig
782
+ base_model_prefix = "model"
783
+ supports_gradient_checkpointing = True
784
+ _no_split_modules = ["GearDecoderLayer"]
785
+ _skip_keys_device_placement = ["past_key_values"]
786
+ _supports_flash_attn = True
787
+ _supports_sdpa = True
788
+ _supports_flex_attn = True
789
+
790
+ _can_compile_fullgraph = True
791
+ _supports_attention_backend = True
792
+ _can_record_outputs = {
793
+ "hidden_states": GearDecoderLayer,
794
+ "attentions": GearAttention,
795
+ "conv_mixer": GearConvKVGatedMixer,
796
+ }
797
+
798
+
799
+ @auto_docstring
800
+ class GearModel(GearPreTrainedModel):
801
+ config: GearConfig
802
+
803
+ def __init__(self, config: GearConfig):
804
+ super().__init__(config)
805
+ self.padding_idx = config.pad_token_id
806
+ self.vocab_size = config.vocab_size
807
+
808
+ self.embed_tokens = GearTextScaledWordEmbedding(
809
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
810
+ )
811
+ self.layers = nn.ModuleList(
812
+ [GearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
813
+ )
814
+ self.norm = GearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
815
+ self.rotary_emb = GearRotaryEmbedding(config=config)
816
+ self.gradient_checkpointing = False
817
+
818
+ config = copy.deepcopy(config)
819
+ config.rope_theta = config.rope_local_base_freq
820
+ config.rope_scaling = {"rope_type": "default"}
821
+ self.rotary_emb_local = GearRotaryEmbedding(config=config)
822
+
823
+ # Initialize weights and apply final processing
824
+ self.post_init()
825
+
826
+ # @check_model_inputs()
827
+ @auto_docstring
828
+ def forward(
829
+ self,
830
+ input_ids: Optional[torch.LongTensor] = None,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_values: Optional[Cache] = None,
834
+ inputs_embeds: Optional[torch.FloatTensor] = None,
835
+ use_cache: Optional[bool] = None,
836
+ output_attentions: Optional[bool] = None,
837
+ output_hidden_states: Optional[bool] = None,
838
+ cache_position: Optional[torch.LongTensor] = None,
839
+ **kwargs: Unpack[TransformersKwargs],
840
+ ) -> BaseModelOutputWithPast:
841
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
842
+ output_hidden_states = (
843
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
844
+ )
845
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
846
+
847
+ if (input_ids is None) ^ (inputs_embeds is not None):
848
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
849
+
850
+ if self.gradient_checkpointing and self.training and use_cache:
851
+ logger.warning_once(
852
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
853
+ )
854
+ use_cache = False
855
+
856
+ if inputs_embeds is None:
857
+ inputs_embeds = self.embed_tokens(input_ids)
858
+
859
+ # if use_cache and past_key_values is None and not self.training:
860
+ # batch_size = inputs_embeds.shape[0]
861
+ # past_key_values = GearHybridKVConvCache(config=self.config, max_batch_size=batch_size, dtype=self.dtype, device=self.device)
862
+
863
+ if use_cache and not self.training:
864
+ if past_key_values is None or type(past_key_values).__name__ == "DynamicCache":
865
+ batch_size = inputs_embeds.shape[0]
866
+ past_key_values = GearHybridKVConvCache(
867
+ config=self.config,
868
+ max_batch_size=batch_size,
869
+ dtype=self.dtype,
870
+ device=self.device
871
+ )
872
+
873
+ if cache_position is None:
874
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
875
+ cache_position = torch.arange(
876
+ past_seen_tokens,
877
+ past_seen_tokens + inputs_embeds.shape[1],
878
+ device=inputs_embeds.device,
879
+ )
880
+
881
+ if position_ids is None:
882
+ position_ids = cache_position.unsqueeze(0)
883
+
884
+ # It may already have been prepared by e.g. `generate`
885
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
886
+ # Prepare mask arguments
887
+ mask_kwargs = {
888
+ "config": self.config,
889
+ "input_embeds": inputs_embeds,
890
+ "attention_mask": attention_mask,
891
+ "cache_position": cache_position,
892
+ "past_key_values": past_key_values,
893
+ "position_ids": position_ids,
894
+ }
895
+ sliding_mask_kwargs = mask_kwargs.copy()
896
+
897
+ if self.config.use_bidirectional_attention:
898
+ mask_kwargs["or_mask_function"] = lambda *args: torch.tensor(True, dtype=torch.bool)
899
+ sliding_mask_kwargs["or_mask_function"] = _bidirectional_window_overlay(self.config.sliding_window)
900
+
901
+ # Create the masks
902
+ causal_mask_mapping = {
903
+ "full_attention": create_causal_mask(**mask_kwargs),
904
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
905
+ "conv_mixer": attention_mask if inputs_embeds.shape[-1] != 1 else None,
906
+ }
907
+
908
+ # embed positions
909
+ hidden_states = inputs_embeds
910
+
911
+ # create position embeddings to be shared across the decoder layers
912
+ position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
913
+ position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
914
+
915
+ # decoder layers
916
+ all_hidden_states = () if output_hidden_states else None
917
+ all_self_attns = () if output_attentions else None
918
+
919
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
920
+ if output_hidden_states:
921
+ all_hidden_states += (hidden_states,)
922
+
923
+ layer_outputs = decoder_layer(
924
+ hidden_states,
925
+ position_embeddings_global=position_embeddings_global,
926
+ position_embeddings_local=position_embeddings_local,
927
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
928
+ position_ids=position_ids,
929
+ past_key_values=past_key_values,
930
+ output_attentions=output_attentions,
931
+ use_cache=use_cache,
932
+ cache_position=cache_position,
933
+ **kwargs,
934
+ )
935
+
936
+ hidden_states = layer_outputs[0]
937
+
938
+ if output_attentions:
939
+ all_self_attns += (layer_outputs[1],)
940
+
941
+ hidden_states = self.norm(hidden_states)
942
+
943
+ if output_hidden_states:
944
+ all_hidden_states += (hidden_states,)
945
+
946
+ return BaseModelOutputWithPast(
947
+ last_hidden_state=hidden_states,
948
+ past_key_values=past_key_values,
949
+ hidden_states=all_hidden_states,
950
+ attentions=all_self_attns,
951
+ )
952
+
953
+
954
+ @auto_docstring
955
+ class GearForCausalLM(GearPreTrainedModel, GenerationMixin):
956
+ _tied_weights_keys = ["lm_head.weight"]
957
+ _tp_plan = {"lm_head": "colwise_rep"}
958
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
959
+ config: GearConfig
960
+
961
+ def __init__(self, config: GearConfig):
962
+ super().__init__(config)
963
+ self.model = GearModel(config)
964
+ self.vocab_size = config.vocab_size
965
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
966
+
967
+ # Initialize weights and apply final processing
968
+ self.post_init()
969
+
970
+ @can_return_tuple
971
+ @auto_docstring
972
+ def forward(
973
+ self,
974
+ input_ids: Optional[torch.LongTensor] = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ position_ids: Optional[torch.LongTensor] = None,
977
+ past_key_values: Optional[Cache] = None,
978
+ inputs_embeds: Optional[torch.FloatTensor] = None,
979
+ labels: Optional[torch.LongTensor] = None,
980
+ use_cache: Optional[bool] = None,
981
+ output_attentions: Optional[bool] = None,
982
+ output_hidden_states: Optional[bool] = None,
983
+ cache_position: Optional[torch.LongTensor] = None,
984
+ logits_to_keep: Union[int, torch.Tensor] = 0,
985
+ **kwargs,
986
+ ) -> CausalLMOutputWithPast:
987
+ r"""
988
+ Example:
989
+
990
+ ```python
991
+ >>> from transformers import AutoTokenizer, Gemma3ForCausalLM
992
+
993
+ >>> model = Gemma3ForCausalLM.from_pretrained("google/gemma-2-9b")
994
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
995
+
996
+ >>> prompt = "What is your favorite condiment?"
997
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
998
+
999
+ >>> # Generate
1000
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1001
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1002
+ "What is your favorite condiment?"
1003
+ ```"""
1004
+
1005
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1006
+ output_hidden_states = (
1007
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1008
+ )
1009
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1010
+ outputs: BaseModelOutputWithPast = self.model(
1011
+ input_ids=input_ids,
1012
+ attention_mask=attention_mask,
1013
+ position_ids=position_ids,
1014
+ past_key_values=past_key_values,
1015
+ inputs_embeds=inputs_embeds,
1016
+ use_cache=use_cache,
1017
+ output_attentions=output_attentions,
1018
+ output_hidden_states=output_hidden_states,
1019
+ cache_position=cache_position,
1020
+ **kwargs,
1021
+ )
1022
+
1023
+ hidden_states = outputs.last_hidden_state
1024
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1025
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1026
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1027
+ # if self.config.final_logit_softcapping is not None:
1028
+ # logits = logits / self.config.final_logit_softcapping
1029
+ # logits = torch.tanh(logits)
1030
+ # logits = logits * self.config.final_logit_softcapping
1031
+
1032
+ loss = None
1033
+ if labels is not None:
1034
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1035
+
1036
+ return CausalLMOutputWithPast(
1037
+ loss=loss,
1038
+ logits=logits,
1039
+ past_key_values=outputs.past_key_values,
1040
+ hidden_states=outputs.hidden_states,
1041
+ attentions=outputs.attentions,
1042
+ )
1043
+
1044
+
1045
+ class GearForSequenceClassification(GenericForSequenceClassification, GearPreTrainedModel):
1046
+ pass
1047
+
1048
+
1049
+ class GearForTokenClassification(GenericForTokenClassification, GearPreTrainedModel):
1050
+ pass
1051
+
1052
+
1053
+ class GearForQuestionAnswering(GenericForQuestionAnswering, GearPreTrainedModel):
1054
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
1055
+
1056
+
1057
+ __all__ = [
1058
+ "GearForCausalLM",
1059
+ "GearForQuestionAnswering",
1060
+ "GearPreTrainedModel",
1061
+ "GearModel",
1062
+ "GearForSequenceClassification",
1063
+ "GearForTokenClassification",
1064
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<bos>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<eos>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<pad>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<pad>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<bos>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<eos>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "bos_token": "<bos>",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "<eos>",
39
+ "extra_special_tokens": {},
40
+ "fix_mistral_regex": true,
41
+ "model_max_length": 512,
42
+ "pad_token": "<pad>",
43
+ "tokenizer_class": "PreTrainedTokenizerFast",
44
+ "unk_token": "<unk>"
45
+ }