Sailesh Panda commited on
Commit
906041e
·
1 Parent(s): 3fb92ec

Added Hinvec modeling files.

Browse files
Files changed (5) hide show
  1. __init__.py +10 -0
  2. config.json +28 -0
  3. configuration_hinvec.py +217 -0
  4. model.safetensors +3 -0
  5. modeling_hinvec.py +493 -0
__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .configuration_hinvec import HinvecConfig
2
+ from .modeling_hinvec import HinvecModel, HinvecForCausalLM
3
+ from .tokenization_hinvec import HinvecTokenizer
4
+
5
+ __all__ = [
6
+ "HinvecConfig",
7
+ "HinvecModel",
8
+ "HinvecForCausalLM",
9
+ "HinvecTokenizer",
10
+ ]
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Ganga-2-1B-PreAlpha_v0.1",
3
+ "architectures": [
4
+ "MistralForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.2,
7
+ "bos_token_id": 6,
8
+ "eos_token_id": 3,
9
+ "head_dim": 64,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2048,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 7168,
14
+ "max_position_embeddings": 2048,
15
+ "model_type": "mistral",
16
+ "num_attention_heads": 32,
17
+ "num_hidden_layers": 16,
18
+ "num_key_value_heads": 8,
19
+ "pad_token_id": 0,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_theta": 10000.0,
22
+ "sliding_window": 1024,
23
+ "tie_word_embeddings": false,
24
+ "torch_dtype": "bfloat16",
25
+ "transformers_version": "4.48.2",
26
+ "use_cache": true,
27
+ "vocab_size": 160002
28
+ }
configuration_hinvec.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Lingo Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """hinvec model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class HinvecConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`hinvecModel`]. It is used to instantiate a
28
+ hinvec model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the hinvec.
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 151936):
36
+ Vocabulary size of the hinvec model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`hinvecModel`]
38
+ hidden_size (`int`, *optional*, defaults to 4096):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 22016):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ num_key_value_heads (`int`, *optional*, defaults to 32):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details, check out [this
52
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54
+ The non-linear activation function (function or string) in the decoder.
55
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
56
+ The maximum sequence length that this model might ever be used with.
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
60
+ The epsilon used by the rms normalization layers.
61
+ use_cache (`bool`, *optional*, defaults to `True`):
62
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
63
+ relevant if `config.is_decoder=True`.
64
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
65
+ Whether the model's input and output word embeddings should be tied.
66
+ rope_theta (`float`, *optional*, defaults to 10000.0):
67
+ The base period of the RoPE embeddings.
68
+ rope_scaling (`Dict`, *optional*):
69
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
70
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
71
+ accordingly.
72
+ Expected contents:
73
+ `rope_type` (`str`):
74
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
75
+ 'llama3'], with 'default' being the original RoPE implementation.
76
+ `factor` (`float`, *optional*):
77
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
78
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
79
+ original maximum pre-trained length.
80
+ `original_max_position_embeddings` (`int`, *optional*):
81
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
82
+ pretraining.
83
+ `attention_factor` (`float`, *optional*):
84
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
85
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
86
+ `factor` field to infer the suggested value.
87
+ `beta_fast` (`float`, *optional*):
88
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
89
+ ramp function. If unspecified, it defaults to 32.
90
+ `beta_slow` (`float`, *optional*):
91
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
92
+ ramp function. If unspecified, it defaults to 1.
93
+ `short_factor` (`list[float]`, *optional*):
94
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
95
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
96
+ size divided by the number of attention heads divided by 2
97
+ `long_factor` (`list[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `low_freq_factor` (`float`, *optional*):
102
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
103
+ `high_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
105
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
106
+ Whether to use sliding window attention.
107
+ sliding_window (`int`, *optional*, defaults to 4096):
108
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
109
+ max_window_layers (`int`, *optional*, defaults to 28):
110
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
111
+ additional layer afterwards will use SWA (Sliding Window Attention).
112
+ layer_types (`list`, *optional*):
113
+ Attention pattern for each layer.
114
+ attention_dropout (`float`, *optional*, defaults to 0.0):
115
+ The dropout ratio for the attention probabilities."""
116
+
117
+ model_type = "hinvec"
118
+ keys_to_ignore_at_inference = ["past_key_values"]
119
+
120
+ # Default tensor parallel plan for base model `hinvec`
121
+ base_model_tp_plan = {
122
+ "layers.*.self_attn.q_proj": "colwise",
123
+ "layers.*.self_attn.k_proj": "colwise",
124
+ "layers.*.self_attn.v_proj": "colwise",
125
+ "layers.*.self_attn.o_proj": "rowwise",
126
+ "layers.*.mlp.gate_proj": "colwise",
127
+ "layers.*.mlp.up_proj": "colwise",
128
+ "layers.*.mlp.down_proj": "rowwise",
129
+ }
130
+ base_model_pp_plan = {
131
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
132
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
133
+ "norm": (["hidden_states"], ["hidden_states"]),
134
+ }
135
+
136
+ def __init__(
137
+ self,
138
+ vocab_size=256002,
139
+ hidden_size=1024,
140
+ intermediate_size=4096,
141
+ num_hidden_layers=12,
142
+ num_attention_heads=16,
143
+ num_key_value_heads=8,
144
+ hidden_act="silu",
145
+ max_position_embeddings=16384,
146
+ initializer_range=0.02,
147
+ rms_norm_eps=1e-6,
148
+ use_cache=True,
149
+ tie_word_embeddings=False,
150
+ rope_theta=10000.0,
151
+ rope_scaling=None,
152
+ use_sliding_window=False,
153
+ sliding_window=4096,
154
+ attention_bias=False,
155
+ max_window_layers=28,
156
+ attention_dropout=0.0,
157
+ layer_types=[
158
+ "sliding_attention",
159
+ "sliding_attention",
160
+ "full_attention",
161
+ "sliding_attention",
162
+ "sliding_attention",
163
+ "full_attention",
164
+ "sliding_attention",
165
+ "sliding_attention",
166
+ "full_attention",
167
+ "sliding_attention",
168
+ "sliding_attention",
169
+ "full_attention"
170
+ ],
171
+ **kwargs,
172
+ ):
173
+ self.vocab_size = vocab_size
174
+ self.max_position_embeddings = max_position_embeddings
175
+ self.hidden_size = hidden_size
176
+ self.intermediate_size = intermediate_size
177
+ self.num_hidden_layers = num_hidden_layers
178
+ self.num_attention_heads = num_attention_heads
179
+ self.use_sliding_window = use_sliding_window
180
+ self.sliding_window = sliding_window if self.use_sliding_window else None
181
+ self.max_window_layers = max_window_layers
182
+
183
+ # for backward compatibility
184
+ if num_key_value_heads is None:
185
+ num_key_value_heads = num_attention_heads
186
+
187
+ self.num_key_value_heads = num_key_value_heads
188
+ self.hidden_act = hidden_act
189
+ self.initializer_range = initializer_range
190
+ self.rms_norm_eps = rms_norm_eps
191
+ self.use_cache = use_cache
192
+ self.rope_theta = rope_theta
193
+ self.rope_scaling = rope_scaling
194
+ self.attention_dropout = attention_dropout
195
+ # Validate the correctness of rotary position embeddings parameters
196
+ # BC: if there is a 'type' field, move it to 'rope_type'.
197
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
198
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
199
+ rope_config_validation(self)
200
+
201
+ self.layer_types = layer_types
202
+ if self.layer_types is None:
203
+ self.layer_types = [
204
+ "sliding_attention"
205
+ if self.sliding_window is not None and i >= self.max_window_layers
206
+ else "full_attention"
207
+ for i in range(self.num_hidden_layers)
208
+ ]
209
+ layer_type_validation(self.layer_types)
210
+
211
+ super().__init__(
212
+ tie_word_embeddings=tie_word_embeddings,
213
+ **kwargs,
214
+ )
215
+
216
+
217
+ __all__ = ["HinvecConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2293285c50ae1d9556fc68a25c5ee85a2e35ae9954a67ac9a14ee7713395d52d
3
+ size 1803775200
modeling_hinvec.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from transformers.activations import ACT2FN
7
+ from transformers.cache_utils import Cache, DynamicCache
8
+ from transformers.integrations import use_kernel_forward_from_hub
9
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
10
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
11
+ from transformers.modeling_layers import (
12
+ GenericForSequenceClassification,
13
+ GenericForTokenClassification,
14
+ GradientCheckpointingLayer,
15
+ )
16
+ from transformers.modeling_outputs import BaseModelOutputWithPast, SequenceClassifierOutputWithPast
17
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
18
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
19
+ from transformers.processing_utils import Unpack
20
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
21
+ from transformers.utils.deprecation import deprecate_kwarg
22
+ from transformers.utils.generic import check_model_inputs
23
+ from configuration_hinvec import HinvecConfig
24
+
25
+
26
+ class HinvecMLP(nn.Module):
27
+ def __init__(self, config):
28
+ super().__init__()
29
+ self.config = config
30
+ self.hidden_size = config.hidden_size
31
+ self.intermediate_size = config.intermediate_size
32
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
33
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
34
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
35
+ self.act_fn = ACT2FN[config.hidden_act]
36
+
37
+ def forward(self, x):
38
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
39
+ return down_proj
40
+
41
+
42
+ def rotate_half(x):
43
+ """Rotates half the hidden dims of the input."""
44
+ x1 = x[..., : x.shape[-1] // 2]
45
+ x2 = x[..., x.shape[-1] // 2 :]
46
+ return torch.cat((-x2, x1), dim=-1)
47
+
48
+
49
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
50
+ """Applies Rotary Position Embedding to the query and key tensors.
51
+
52
+ Args:
53
+ q (`torch.Tensor`): The query tensor.
54
+ k (`torch.Tensor`): The key tensor.
55
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
56
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
57
+ position_ids (`torch.Tensor`, *optional*):
58
+ Deprecated and unused.
59
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
60
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
61
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
62
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
63
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
64
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
65
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
66
+ Returns:
67
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
68
+ """
69
+ cos = cos.unsqueeze(unsqueeze_dim)
70
+ sin = sin.unsqueeze(unsqueeze_dim)
71
+ q_embed = (q * cos) + (rotate_half(q) * sin)
72
+ k_embed = (k * cos) + (rotate_half(k) * sin)
73
+ return q_embed, k_embed
74
+
75
+
76
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
77
+ """
78
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
79
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
80
+ """
81
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
82
+ if n_rep == 1:
83
+ return hidden_states
84
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
85
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
86
+
87
+
88
+ def eager_attention_forward(
89
+ module: nn.Module,
90
+ query: torch.Tensor,
91
+ key: torch.Tensor,
92
+ value: torch.Tensor,
93
+ attention_mask: Optional[torch.Tensor],
94
+ scaling: float,
95
+ dropout: float = 0.0,
96
+ **kwargs: Unpack[TransformersKwargs],
97
+ ):
98
+ key_states = repeat_kv(key, module.num_key_value_groups)
99
+ value_states = repeat_kv(value, module.num_key_value_groups)
100
+
101
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
102
+ if attention_mask is not None:
103
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
104
+ attn_weights = attn_weights + causal_mask
105
+
106
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
107
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
108
+ attn_output = torch.matmul(attn_weights, value_states)
109
+ attn_output = attn_output.transpose(1, 2).contiguous()
110
+
111
+ return attn_output, attn_weights
112
+
113
+
114
+ class HinvecAttention(nn.Module):
115
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
116
+
117
+ def __init__(self, config: HinvecConfig, layer_idx: int):
118
+ super().__init__()
119
+ self.config = config
120
+ self.layer_idx = layer_idx
121
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
122
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
123
+ self.scaling = self.head_dim**-0.5
124
+ self.attention_dropout = config.attention_dropout
125
+ self.is_causal = True
126
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
127
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
128
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
129
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
130
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
131
+
132
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
133
+ def forward(
134
+ self,
135
+ hidden_states: torch.Tensor,
136
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
137
+ attention_mask: Optional[torch.Tensor],
138
+ past_key_values: Optional[Cache] = None,
139
+ cache_position: Optional[torch.LongTensor] = None,
140
+ **kwargs: Unpack[FlashAttentionKwargs],
141
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
142
+ input_shape = hidden_states.shape[:-1]
143
+ hidden_shape = (*input_shape, -1, self.head_dim)
144
+
145
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
146
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
147
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
148
+
149
+ cos, sin = position_embeddings
150
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
151
+
152
+ if past_key_values is not None:
153
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
154
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
155
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
156
+
157
+ attention_interface: Callable = eager_attention_forward
158
+ if self.config._attn_implementation != "eager":
159
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
160
+
161
+ attn_output, attn_weights = attention_interface(
162
+ self,
163
+ query_states,
164
+ key_states,
165
+ value_states,
166
+ attention_mask,
167
+ dropout=0.0 if not self.training else self.attention_dropout,
168
+ scaling=self.scaling,
169
+ sliding_window=self.sliding_window, # main diff with Llama
170
+ **kwargs,
171
+ )
172
+
173
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
174
+ attn_output = self.o_proj(attn_output)
175
+ return attn_output, attn_weights
176
+
177
+
178
+ @use_kernel_forward_from_hub("RMSNorm")
179
+ class HinvecRMSNorm(nn.Module):
180
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
181
+ """
182
+ HinvecRMSNorm is equivalent to T5LayerNorm
183
+ """
184
+ super().__init__()
185
+ self.weight = nn.Parameter(torch.ones(hidden_size))
186
+ self.variance_epsilon = eps
187
+
188
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
189
+ input_dtype = hidden_states.dtype
190
+ hidden_states = hidden_states.to(torch.float32)
191
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
192
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
193
+ return self.weight * hidden_states.to(input_dtype)
194
+
195
+ def extra_repr(self):
196
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
197
+
198
+
199
+ class HinvecDecoderLayer(GradientCheckpointingLayer):
200
+ def __init__(self, config: HinvecConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.hidden_size = config.hidden_size
203
+
204
+ self.self_attn = HinvecAttention(config=config, layer_idx=layer_idx)
205
+
206
+ self.mlp = HinvecMLP(config)
207
+ self.input_layernorm = HinvecRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
208
+ self.post_attention_layernorm = HinvecRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
209
+ self.attention_type = config.layer_types[layer_idx]
210
+
211
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
212
+ def forward(
213
+ self,
214
+ hidden_states: torch.Tensor,
215
+ attention_mask: Optional[torch.Tensor] = None,
216
+ position_ids: Optional[torch.LongTensor] = None,
217
+ past_key_values: Optional[Cache] = None,
218
+ use_cache: Optional[bool] = False,
219
+ cache_position: Optional[torch.LongTensor] = None,
220
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
221
+ **kwargs: Unpack[TransformersKwargs],
222
+ ) -> torch.Tensor:
223
+ residual = hidden_states
224
+ hidden_states = self.input_layernorm(hidden_states)
225
+ # Self Attention
226
+ hidden_states, _ = self.self_attn(
227
+ hidden_states=hidden_states,
228
+ attention_mask=attention_mask,
229
+ position_ids=position_ids,
230
+ past_key_values=past_key_values,
231
+ use_cache=use_cache,
232
+ cache_position=cache_position,
233
+ position_embeddings=position_embeddings,
234
+ **kwargs,
235
+ )
236
+ hidden_states = residual + hidden_states
237
+
238
+ # Fully Connected
239
+ residual = hidden_states
240
+ hidden_states = self.post_attention_layernorm(hidden_states)
241
+ hidden_states = self.mlp(hidden_states)
242
+ hidden_states = residual + hidden_states
243
+ return hidden_states
244
+
245
+
246
+ @auto_docstring
247
+ class HinvecPreTrainedModel(PreTrainedModel):
248
+ config: HinvecConfig
249
+ base_model_prefix = "model"
250
+ supports_gradient_checkpointing = True
251
+ _no_split_modules = ["HinvecDecoderLayer"]
252
+ _skip_keys_device_placement = ["past_key_values"]
253
+ _supports_flash_attn = True
254
+ _supports_sdpa = True
255
+ _supports_flex_attn = True
256
+
257
+ _can_compile_fullgraph = True
258
+ _supports_attention_backend = True
259
+ _can_record_outputs = {
260
+ "hidden_states": HinvecDecoderLayer,
261
+ "attentions": HinvecAttention,
262
+ }
263
+
264
+
265
+ class HinvecRotaryEmbedding(nn.Module):
266
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
267
+
268
+ def __init__(self, config: HinvecConfig, device=None):
269
+ super().__init__()
270
+ # BC: "rope_type" was originally "type"
271
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
272
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
273
+ else:
274
+ self.rope_type = "default"
275
+ self.max_seq_len_cached = config.max_position_embeddings
276
+ self.original_max_seq_len = config.max_position_embeddings
277
+
278
+ self.config = config
279
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
280
+
281
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
282
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
283
+ self.original_inv_freq = self.inv_freq
284
+
285
+ @torch.no_grad()
286
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
287
+ def forward(self, x, position_ids):
288
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
289
+ position_ids_expanded = position_ids[:, None, :].float()
290
+
291
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
292
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
293
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
294
+ emb = torch.cat((freqs, freqs), dim=-1)
295
+ cos = emb.cos() * self.attention_scaling
296
+ sin = emb.sin() * self.attention_scaling
297
+
298
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
299
+
300
+
301
+ @auto_docstring
302
+ class HinvecModel(HinvecPreTrainedModel):
303
+ def __init__(self, config: HinvecConfig):
304
+ super().__init__(config)
305
+ self.padding_idx = config.pad_token_id
306
+ self.vocab_size = config.vocab_size
307
+
308
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
309
+ self.layers = nn.ModuleList(
310
+ [HinvecDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
311
+ )
312
+ self.norm = HinvecRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
313
+ self.rotary_emb = HinvecRotaryEmbedding(config=config)
314
+ self.gradient_checkpointing = False
315
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
316
+
317
+ # Initialize weights and apply final processing
318
+ self.post_init()
319
+
320
+ @check_model_inputs
321
+ @auto_docstring
322
+ def forward(
323
+ self,
324
+ input_ids: Optional[torch.LongTensor] = None,
325
+ attention_mask: Optional[torch.Tensor] = None,
326
+ position_ids: Optional[torch.LongTensor] = None,
327
+ past_key_values: Optional[Cache] = None,
328
+ inputs_embeds: Optional[torch.FloatTensor] = None,
329
+ use_cache: Optional[bool] = None,
330
+ cache_position: Optional[torch.LongTensor] = None,
331
+ **kwargs: Unpack[TransformersKwargs],
332
+ ) -> BaseModelOutputWithPast:
333
+ if (input_ids is None) ^ (inputs_embeds is not None):
334
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
335
+
336
+ if inputs_embeds is None:
337
+ inputs_embeds = self.embed_tokens(input_ids)
338
+
339
+ if use_cache and past_key_values is None:
340
+ past_key_values = DynamicCache(config=self.config)
341
+
342
+ if cache_position is None:
343
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
344
+ cache_position = torch.arange(
345
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
346
+ )
347
+
348
+ if position_ids is None:
349
+ position_ids = cache_position.unsqueeze(0)
350
+
351
+ # It may already have been prepared by e.g. `generate`
352
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
353
+ # Prepare mask arguments
354
+ mask_kwargs = {
355
+ "config": self.config,
356
+ "input_embeds": inputs_embeds,
357
+ "attention_mask": attention_mask,
358
+ "cache_position": cache_position,
359
+ "past_key_values": past_key_values,
360
+ "position_ids": position_ids,
361
+ }
362
+ # Create the masks
363
+ causal_mask_mapping = {
364
+ "full_attention": create_causal_mask(**mask_kwargs),
365
+ }
366
+ # The sliding window alternating layers are not always activated depending on the config
367
+ if self.has_sliding_layers:
368
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
369
+
370
+ hidden_states = inputs_embeds
371
+
372
+ # create position embeddings to be shared across the decoder layers
373
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
374
+
375
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
376
+ hidden_states = decoder_layer(
377
+ hidden_states,
378
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
379
+ position_ids=position_ids,
380
+ past_key_values=past_key_values,
381
+ use_cache=use_cache,
382
+ cache_position=cache_position,
383
+ position_embeddings=position_embeddings,
384
+ **kwargs,
385
+ )
386
+
387
+ hidden_states = self.norm(hidden_states)
388
+ return BaseModelOutputWithPast(
389
+ last_hidden_state=hidden_states,
390
+ past_key_values=past_key_values if use_cache else None,
391
+ )
392
+
393
+ class HinvecForSequenceClassification(GenericForSequenceClassification, HinvecPreTrainedModel):
394
+ _checkpoint_conversion_mapping = {
395
+ "^language_model.model": "model.language_model",
396
+ "^vision_tower": "model.vision_tower",
397
+ "^multi_modal_projector": "model.multi_modal_projector",
398
+ }
399
+
400
+ def __init__(self, config):
401
+ super().__init__(config)
402
+ self.num_labels = config.num_labels
403
+ self.model = HinvecModel(config)
404
+ self.score = nn.Linear(config.text_config.hidden_size, self.num_labels, bias=False)
405
+
406
+ # Initialize weights and apply final processing
407
+ self.post_init()
408
+
409
+ def get_input_embeddings(self):
410
+ return self.model.get_input_embeddings()
411
+
412
+ def set_input_embeddings(self, value):
413
+ self.model.set_input_embeddings(value)
414
+
415
+ @can_return_tuple
416
+ @auto_docstring
417
+ def forward(
418
+ self,
419
+ input_ids: torch.LongTensor = None,
420
+ pixel_values: Optional[torch.FloatTensor] = None,
421
+ attention_mask: Optional[torch.Tensor] = None,
422
+ position_ids: Optional[torch.LongTensor] = None,
423
+ past_key_values: Optional[Cache] = None,
424
+ inputs_embeds: Optional[torch.FloatTensor] = None,
425
+ token_type_ids: Optional[torch.LongTensor] = None,
426
+ labels: Optional[torch.LongTensor] = None,
427
+ use_cache: Optional[bool] = None,
428
+ **kwargs: Unpack[TransformersKwargs],
429
+ ) -> SequenceClassifierOutputWithPast:
430
+ r"""
431
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
432
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
433
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
434
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
435
+ """
436
+
437
+ transformer_outputs = self.model(
438
+ input_ids,
439
+ attention_mask=attention_mask,
440
+ pixel_values=pixel_values,
441
+ position_ids=position_ids,
442
+ past_key_values=past_key_values,
443
+ inputs_embeds=inputs_embeds,
444
+ token_type_ids=token_type_ids,
445
+ use_cache=use_cache,
446
+ **kwargs,
447
+ )
448
+ hidden_states = transformer_outputs.last_hidden_state
449
+ logits = self.score(hidden_states)
450
+
451
+ if input_ids is not None:
452
+ batch_size = input_ids.shape[0]
453
+ else:
454
+ batch_size = inputs_embeds.shape[0]
455
+
456
+ if self.config.text_config.pad_token_id is None and batch_size != 1:
457
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
458
+ if self.config.text_config.pad_token_id is None:
459
+ last_non_pad_token = -1
460
+ elif input_ids is not None:
461
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
462
+ non_pad_mask = (input_ids != self.config.text_config.pad_token_id).to(logits.device, torch.int32)
463
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
464
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
465
+ else:
466
+ last_non_pad_token = -1
467
+
468
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
469
+
470
+ loss = None
471
+ if labels is not None:
472
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
473
+
474
+ return SequenceClassifierOutputWithPast(
475
+ loss=loss,
476
+ logits=pooled_logits,
477
+ past_key_values=transformer_outputs.past_key_values,
478
+ hidden_states=transformer_outputs.hidden_states,
479
+ attentions=transformer_outputs.attentions,
480
+ )
481
+
482
+
483
+ class HinvecForTokenClassification(GenericForTokenClassification, HinvecPreTrainedModel):
484
+ pass
485
+
486
+
487
+ __all__ = [
488
+ "HinvecPreTrainedModel",
489
+ "HinvecModel",
490
+ "HinvecRMSNorm",
491
+ "HinvecForSequenceClassification",
492
+ "HinvecForTokenClassification",
493
+ ]