hasankursun commited on
Commit
92ff3ee
·
verified ·
1 Parent(s): 07b9710

Upload folder using huggingface_hub

Browse files
added_tokens.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</|thought|>": 32003,
3
+ "<|assistant|>": 32001,
4
+ "<|endoftext|>": 32000,
5
+ "<|end|>": 32007,
6
+ "<|placeholder1|>": 32011,
7
+ "<|placeholder2|>": 32012,
8
+ "<|placeholder3|>": 32004,
9
+ "<|placeholder4|>": 32005,
10
+ "<|placeholder5|>": 32008,
11
+ "<|placeholder6|>": 32009,
12
+ "<|system|>": 32006,
13
+ "<|thought|>": 32002,
14
+ "<|user|>": 32010
15
+ }
chat_template.jinja ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% for message in messages %}{% if loop.first and message['role'] != 'system' %}{{'<|system|>
2
+ You are Lumees, an advanced reasoning AI assistant.<|end|>
3
+ '}}{% endif %}{% if message['role'] == 'system' %}{{'<|system|>
4
+ ' + message['content'] + '<|end|>
5
+ '}}{% elif message['role'] == 'user' %}{{'<|user|>
6
+ ' + message['content'] + '<|end|>
7
+ '}}{% elif message['role'] == 'assistant' %}{% if message['thought'] %}{{'<|assistant|>
8
+ <|thought|>
9
+ ' + message['thought'] + '
10
+ </|thought|>
11
+ ' + message['content'] + '<|end|>
12
+ '}}{% else %}{{'<|assistant|>
13
+ ' + message['content'] + '<|end|>
14
+ '}}{% endif %}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>
15
+ ' }}{% else %}{{ eos_token }}{% endif %}
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LumeesForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_lumees.LumeesConfig",
9
+ "AutoModelForCausalLM": "modeling_lumees.LumeesForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "torch_dtype": "bfloat16",
13
+ "embd_pdrop": 0.0,
14
+ "eos_token_id": 32000,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 3072,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 8192,
19
+ "max_position_embeddings": 4096,
20
+ "model_type": "lumees",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 32,
24
+ "original_max_position_embeddings": 4096,
25
+ "pad_token_id": 32000,
26
+ "partial_rotary_factor": 1.0,
27
+ "resid_pdrop": 0.0,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_scaling": null,
30
+ "rope_theta": 10000.0,
31
+ "sliding_window": 2047,
32
+ "tie_word_embeddings": false,
33
+ "transformers_version": "4.57.1",
34
+ "unsloth_version": "2025.11.3",
35
+ "use_cache": true,
36
+ "vocab_size": 32064
37
+ }
configuration_lumees.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft, the HuggingFace Inc. team, and the Lumees AI 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
+
16
+ """ Lumees model configuration (Based on Phi-3) """
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ class LumeesConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`LumeesModel`]. It is used to instantiate a Lumees
26
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
27
+ defaults will yield a configuration similar to the standard Phi-3 Mini.
28
+
29
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
30
+ documentation from [`PretrainedConfig`] for more information.
31
+
32
+ Args:
33
+ vocab_size (`int`, *optional*, defaults to 32064):
34
+ Vocabulary size of the Lumees model. Defines the number of different tokens that can be represented by the
35
+ `inputs_ids` passed when calling [`LumeesModel`].
36
+ hidden_size (`int`, *optional*, defaults to 3072):
37
+ Dimension of the hidden representations.
38
+ intermediate_size (`int`, *optional*, defaults to 8192):
39
+ Dimension of the MLP representations.
40
+ num_hidden_layers (`int`, *optional*, defaults to 32):
41
+ Number of hidden layers in the Transformer decoder.
42
+ num_attention_heads (`int`, *optional*, defaults to 32):
43
+ Number of attention heads for each attention layer in the Transformer decoder.
44
+ num_key_value_heads (`int`, *optional*):
45
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
46
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
47
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
48
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
49
+ Dropout probability for mlp outputs.
50
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
51
+ The dropout ratio for the embeddings.
52
+ attention_dropout (`float`, *optional*, defaults to 0.0):
53
+ The dropout ratio after computing the attention scores.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
57
+ The maximum sequence length that this model might ever be used with.
58
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
59
+ The maximum sequence length that this model was trained with.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
63
+ The epsilon value used for the RMSNorm.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether to tie weight embeddings.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`dict`, *optional*):
71
+ The scaling strategy for the RoPE embeddings. Must contain `type='longrope'`, `short_factor` and `long_factor`.
72
+ bos_token_id (`int`, *optional*, defaults to 1):
73
+ The id of the "beginning-of-sequence" token.
74
+ eos_token_id (`int`, *optional*, defaults to 32000):
75
+ The id of the "end-of-sequence" token.
76
+ pad_token_id (`int`, *optional*, defaults to 32000):
77
+ The id of the padding token.
78
+ sliding_window (`int`, *optional*):
79
+ Sliding window attention window size. If `None`, no sliding window is applied.
80
+
81
+ Example:
82
+
83
+ ```python
84
+ >>> from transformers import AutoModelForCausalLM, AutoConfig
85
+ >>> from configuration_lumees import LumeesConfig
86
+
87
+ >>> # Initializing a Lumees style configuration
88
+ >>> configuration = LumeesConfig()
89
+
90
+ >>> # Initializing a model from the configuration
91
+ >>> model = AutoModelForCausalLM.from_config(configuration)
92
+ ```"""
93
+
94
+ model_type = "lumees"
95
+ keys_to_ignore_at_inference = ["past_key_values"]
96
+
97
+ def __init__(
98
+ self,
99
+ vocab_size=32064,
100
+ hidden_size=3072,
101
+ intermediate_size=8192,
102
+ num_hidden_layers=32,
103
+ num_attention_heads=32,
104
+ num_key_value_heads=None,
105
+ resid_pdrop=0.0,
106
+ embd_pdrop=0.0,
107
+ attention_dropout=0.0,
108
+ hidden_act="silu",
109
+ max_position_embeddings=4096,
110
+ original_max_position_embeddings=4096,
111
+ initializer_range=0.02,
112
+ rms_norm_eps=1e-5,
113
+ use_cache=True,
114
+ tie_word_embeddings=False,
115
+ rope_theta=10000.0,
116
+ rope_scaling=None,
117
+ bos_token_id=1,
118
+ eos_token_id=32000,
119
+ pad_token_id=32000,
120
+ sliding_window=None,
121
+ **kwargs,
122
+ ):
123
+ self.vocab_size = vocab_size
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+
129
+ if num_key_value_heads is None:
130
+ num_key_value_heads = num_attention_heads
131
+
132
+ self.num_key_value_heads = num_key_value_heads
133
+ self.resid_pdrop = resid_pdrop
134
+ self.embd_pdrop = embd_pdrop
135
+ self.attention_dropout = attention_dropout
136
+ self.hidden_act = hidden_act
137
+ self.max_position_embeddings = max_position_embeddings
138
+ self.original_max_position_embeddings = original_max_position_embeddings
139
+ self.initializer_range = initializer_range
140
+ self.rms_norm_eps = rms_norm_eps
141
+ self.use_cache = use_cache
142
+ self.rope_theta = rope_theta
143
+ self.rope_scaling = rope_scaling
144
+ self._rope_scaling_adjustment()
145
+ self._rope_scaling_validation()
146
+ self.sliding_window = sliding_window
147
+
148
+ super().__init__(
149
+ bos_token_id=bos_token_id,
150
+ eos_token_id=eos_token_id,
151
+ pad_token_id=pad_token_id,
152
+ tie_word_embeddings=tie_word_embeddings,
153
+ **kwargs,
154
+ )
155
+
156
+ def _rope_scaling_adjustment(self):
157
+ """
158
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
159
+ """
160
+ if self.rope_scaling is None:
161
+ return
162
+
163
+ rope_scaling_type = self.rope_scaling.get("type", None)
164
+
165
+ # For backward compatibility if previous version used "su" or "yarn"
166
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
167
+ self.rope_scaling["type"] = "longrope"
168
+
169
+ def _rope_scaling_validation(self):
170
+ """
171
+ Validate the `rope_scaling` configuration.
172
+ """
173
+ if self.rope_scaling is None:
174
+ return
175
+
176
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
177
+ raise ValueError(
178
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
179
+ f"got {self.rope_scaling}"
180
+ )
181
+ rope_scaling_type = self.rope_scaling.get("type", None)
182
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
183
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
184
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
185
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
186
+ if not (
187
+ isinstance(rope_scaling_short_factor, list)
188
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
189
+ ):
190
+ raise ValueError(
191
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
192
+ )
193
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
194
+ raise ValueError(
195
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
196
+ )
197
+ if not (
198
+ isinstance(rope_scaling_long_factor, list)
199
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
200
+ ):
201
+ raise ValueError(
202
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
203
+ )
204
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
205
+ raise ValueError(
206
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
207
+ )
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b0429e0e6f9ba16ce12ea90d9ba445575c34935e04e7e2401b187bb33b751ba
3
+ size 4972489328
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10b3c4399714dcb3582cbdb88a53ee9c88b1921b70af2279c2969051d09b6eaf
3
+ size 2669692552
model.safetensors.index.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7642159104
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.norm.weight": "model-00002-of-00002.safetensors"
201
+ }
202
+ }
modeling_lumees.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft, the HuggingFace Inc. team, and the Lumees AI 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
+
16
+ """ PyTorch Lumees model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ # IMPORTANT: Make sure this file exists in the same directory
49
+ from .configuration_lumees import LumeesConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading.
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attention` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "your-org/Lumees-mini-instruct"
71
+ _CONFIG_FOR_DOC = "LumeesConfig"
72
+
73
+ LUMEES_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "your-org/Lumees-mini-instruct",
75
+ ]
76
+
77
+
78
+ class LumeesRMSNorm(nn.Module):
79
+ def __init__(self, hidden_size, eps=1e-6):
80
+ """
81
+ LumeesRMSNorm is equivalent to T5LayerNorm
82
+ """
83
+ super().__init__()
84
+ self.weight = nn.Parameter(torch.ones(hidden_size))
85
+ self.variance_epsilon = eps
86
+
87
+ def forward(self, hidden_states):
88
+ input_dtype = hidden_states.dtype
89
+ hidden_states = hidden_states.to(torch.float32)
90
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
91
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
92
+ return self.weight * hidden_states.to(input_dtype)
93
+
94
+
95
+ def _get_unpad_data(attention_mask):
96
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
97
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
98
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
99
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
100
+ return (
101
+ indices,
102
+ cu_seqlens,
103
+ max_seqlen_in_batch,
104
+ )
105
+
106
+
107
+ class LumeesRotaryEmbedding(nn.Module):
108
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
109
+ super().__init__()
110
+
111
+ self.dim = dim
112
+ self.max_position_embeddings = max_position_embeddings
113
+ self.base = base
114
+ self.register_buffer("inv_freq", None, persistent=False)
115
+
116
+ @torch.no_grad()
117
+ def forward(self, x, position_ids, seq_len=None):
118
+ # x: [bs, num_attention_heads, seq_len, head_size]
119
+ if self.inv_freq is None:
120
+ self.inv_freq = 1.0 / (
121
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
122
+ )
123
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
124
+ position_ids_expanded = position_ids[:, None, :].float()
125
+
126
+ device_type = x.device.type
127
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
128
+ with torch.autocast(device_type=device_type, enabled=False):
129
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
130
+ emb = torch.cat((freqs, freqs), dim=-1)
131
+ cos = emb.cos()
132
+ sin = emb.sin()
133
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
134
+
135
+
136
+ class LumeesLongRoPEScaledRotaryEmbedding(LumeesRotaryEmbedding):
137
+ def __init__(self, dim, config, device=None):
138
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
139
+
140
+ self.short_factor = config.rope_scaling["short_factor"]
141
+ self.long_factor = config.rope_scaling["long_factor"]
142
+ self.original_max_position_embeddings = config.original_max_position_embeddings
143
+
144
+ @torch.no_grad()
145
+ def forward(self, x, position_ids, seq_len=None):
146
+ seq_len = torch.max(position_ids) + 1
147
+ if seq_len > self.original_max_position_embeddings:
148
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
149
+ else:
150
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
151
+
152
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
153
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
154
+
155
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
156
+ position_ids_expanded = position_ids[:, None, :].float()
157
+
158
+ device_type = x.device.type
159
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
160
+ with torch.autocast(device_type=device_type, enabled=False):
161
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
162
+ emb = torch.cat((freqs, freqs), dim=-1)
163
+
164
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
165
+ if scale <= 1.0:
166
+ scaling_factor = 1.0
167
+ else:
168
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
169
+
170
+ cos = emb.cos() * scaling_factor
171
+ sin = emb.sin() * scaling_factor
172
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
173
+
174
+
175
+ def rotate_half(x):
176
+ """Rotates half the hidden dims of the input."""
177
+ x1 = x[..., : x.shape[-1] // 2]
178
+ x2 = x[..., x.shape[-1] // 2 :]
179
+ return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
183
+ cos = cos.unsqueeze(unsqueeze_dim)
184
+ sin = sin.unsqueeze(unsqueeze_dim)
185
+ q_embed = (q * cos) + (rotate_half(q) * sin)
186
+ k_embed = (k * cos) + (rotate_half(k) * sin)
187
+ return q_embed, k_embed
188
+
189
+
190
+ class LumeesMLP(nn.Module):
191
+ def __init__(self, config):
192
+ super().__init__()
193
+
194
+ self.config = config
195
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
196
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
197
+
198
+ self.activation_fn = ACT2FN[config.hidden_act]
199
+
200
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
201
+ up_states = self.gate_up_proj(hidden_states)
202
+
203
+ gate, up_states = up_states.chunk(2, dim=-1)
204
+ up_states = up_states * self.activation_fn(gate)
205
+
206
+ return self.down_proj(up_states)
207
+
208
+
209
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
210
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
211
+ if n_rep == 1:
212
+ return hidden_states
213
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
214
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
215
+
216
+
217
+ class LumeesAttention(nn.Module):
218
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
219
+
220
+ def __init__(self, config: LumeesConfig, layer_idx: Optional[int] = None):
221
+ super().__init__()
222
+ self.config = config
223
+ self.layer_idx = layer_idx
224
+ if layer_idx is None:
225
+ logger.warning_once(
226
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
227
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
228
+ "when creating this class."
229
+ )
230
+
231
+ self.attention_dropout = config.attention_dropout
232
+ self.hidden_size = config.hidden_size
233
+ self.num_heads = config.num_attention_heads
234
+ self.head_dim = self.hidden_size // self.num_heads
235
+ self.num_key_value_heads = config.num_key_value_heads
236
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
237
+ self.max_position_embeddings = config.max_position_embeddings
238
+ self.original_max_position_embeddings = config.original_max_position_embeddings
239
+ self.rope_theta = config.rope_theta
240
+ self.rope_scaling = config.rope_scaling
241
+ self.is_causal = True
242
+
243
+ if (self.head_dim * self.num_heads) != self.hidden_size:
244
+ raise ValueError(
245
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
246
+ f" and `num_heads`: {self.num_heads})."
247
+ )
248
+
249
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
250
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
251
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
252
+ self._init_rope()
253
+
254
+ def _init_rope(self):
255
+ if self.rope_scaling is None:
256
+ self.rotary_emb = LumeesRotaryEmbedding(
257
+ self.head_dim,
258
+ max_position_embeddings=self.max_position_embeddings,
259
+ base=self.rope_theta,
260
+ )
261
+ else:
262
+ scaling_type = self.config.rope_scaling["type"]
263
+ if scaling_type == "longrope":
264
+ self.rotary_emb = LumeesLongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
265
+ else:
266
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
267
+
268
+ def forward(
269
+ self,
270
+ hidden_states: torch.Tensor,
271
+ attention_mask: Optional[torch.Tensor] = None,
272
+ position_ids: Optional[torch.LongTensor] = None,
273
+ past_key_value: Optional[Cache] = None,
274
+ output_attentions: bool = False,
275
+ use_cache: bool = False,
276
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
277
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
278
+
279
+ bsz, q_len, _ = hidden_states.size()
280
+
281
+ qkv = self.qkv_proj(hidden_states)
282
+ query_pos = self.num_heads * self.head_dim
283
+ query_states = qkv[..., :query_pos]
284
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
285
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
286
+
287
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
288
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
289
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
290
+
291
+ kv_seq_len = key_states.shape[-2]
292
+ if past_key_value is not None:
293
+ if self.layer_idx is None:
294
+ raise ValueError(
295
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
296
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
297
+ "with a layer index."
298
+ )
299
+ # FIX: Use get_seq_length if get_usable_length is missing (Transformers >= 4.40 compatibility)
300
+ if hasattr(past_key_value, "get_usable_length"):
301
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
302
+ else:
303
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
304
+
305
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
306
+
307
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
308
+
309
+ if past_key_value is not None:
310
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
311
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
312
+
313
+ # repeat k/v heads if n_kv_heads < n_heads
314
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
315
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
316
+
317
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
318
+
319
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
320
+ raise ValueError(
321
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
322
+ f" {attn_weights.size()}"
323
+ )
324
+
325
+ if attention_mask is not None:
326
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
327
+ raise ValueError(
328
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
329
+ )
330
+ attn_weights = attn_weights + attention_mask
331
+
332
+ # upcast attention to fp32
333
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
334
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
335
+
336
+ attn_output = torch.matmul(attn_weights, value_states)
337
+
338
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
339
+ raise ValueError(
340
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
341
+ f" {attn_output.size()}"
342
+ )
343
+
344
+ attn_output = attn_output.transpose(1, 2).contiguous()
345
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
346
+
347
+ attn_output = self.o_proj(attn_output)
348
+
349
+ if not output_attentions:
350
+ attn_weights = None
351
+
352
+ return attn_output, attn_weights, past_key_value
353
+
354
+
355
+ class LumeesFlashAttention2(LumeesAttention):
356
+ """
357
+ Lumees flash attention module. This module inherits from `LumeesAttention` as the weights of the module stays
358
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
359
+ flash attention and deal with padding tokens in case the input contains any of them.
360
+ """
361
+
362
+ def __init__(self, *args, **kwargs):
363
+ super().__init__(*args, **kwargs)
364
+
365
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
366
+
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ attention_mask: Optional[torch.LongTensor] = None,
371
+ position_ids: Optional[torch.LongTensor] = None,
372
+ past_key_value: Optional[Cache] = None,
373
+ output_attentions: bool = False,
374
+ use_cache: bool = False,
375
+ **kwargs,
376
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
377
+ # LumeesFlashAttention2 attention does not support output_attentions
378
+
379
+ if not _flash_supports_window_size:
380
+ logger.warning_once(
381
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
382
+ )
383
+ raise ValueError("The current flash attention version does not support sliding window attention.")
384
+
385
+ output_attentions = False
386
+
387
+ if "padding_mask" in kwargs:
388
+ warnings.warn(
389
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
390
+ )
391
+ attention_mask = kwargs.pop("padding_mask")
392
+
393
+ bsz, q_len, _ = hidden_states.size()
394
+
395
+ qkv = self.qkv_proj(hidden_states)
396
+ query_pos = self.num_heads * self.head_dim
397
+ query_states = qkv[..., :query_pos]
398
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
399
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
400
+
401
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
402
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
403
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
404
+
405
+ kv_seq_len = key_states.shape[-2]
406
+ if past_key_value is not None:
407
+ if self.layer_idx is None:
408
+ raise ValueError(
409
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
410
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
411
+ "with a layer index."
412
+ )
413
+ # FIX: Use get_seq_length if get_usable_length is missing
414
+ if hasattr(past_key_value, "get_usable_length"):
415
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
416
+ else:
417
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
418
+
419
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
420
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
421
+
422
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
423
+
424
+ use_sliding_windows = (
425
+ _flash_supports_window_size
426
+ and getattr(self.config, "sliding_window", None) is not None
427
+ and kv_seq_len > self.config.sliding_window
428
+ )
429
+
430
+ if past_key_value is not None:
431
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
432
+ if (
433
+ getattr(self.config, "sliding_window", None) is not None
434
+ and kv_seq_len > self.config.sliding_window
435
+ and cache_has_contents
436
+ ):
437
+ slicing_tokens = 1 - self.config.sliding_window
438
+
439
+ past_key = past_key_value[self.layer_idx][0]
440
+ past_value = past_key_value[self.layer_idx][1]
441
+
442
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
443
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
444
+
445
+ if past_key.shape[-2] != self.config.sliding_window - 1:
446
+ raise ValueError(
447
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
448
+ f" {past_key.shape}"
449
+ )
450
+
451
+ if attention_mask is not None:
452
+ attention_mask = attention_mask[:, slicing_tokens:]
453
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
454
+
455
+ cache_kwargs = {"sin": sin, "cos": cos}
456
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
457
+
458
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
459
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
460
+
461
+ attn_dropout = self.attention_dropout if self.training else 0.0
462
+
463
+ if query_states.dtype == torch.float32:
464
+ if torch.is_autocast_enabled():
465
+ target_dtype = torch.get_autocast_gpu_dtype()
466
+ elif hasattr(self.config, "_pre_quantization_dtype"):
467
+ target_dtype = self.config._pre_quantization_dtype
468
+ else:
469
+ target_dtype = self.qkv_proj.weight.dtype
470
+
471
+ logger.warning_once(
472
+ f"The input hidden states seems to be silently casted in float32. We will cast back the input in {target_dtype}."
473
+ )
474
+
475
+ query_states = query_states.to(target_dtype)
476
+ key_states = key_states.to(target_dtype)
477
+ value_states = value_states.to(target_dtype)
478
+
479
+ query_states = query_states.transpose(1, 2)
480
+ key_states = key_states.transpose(1, 2)
481
+ value_states = value_states.transpose(1, 2)
482
+
483
+ attn_output = self._flash_attention_forward(
484
+ query_states,
485
+ key_states,
486
+ value_states,
487
+ attention_mask,
488
+ q_len,
489
+ dropout=attn_dropout,
490
+ use_sliding_windows=use_sliding_windows,
491
+ )
492
+
493
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
494
+ attn_output = self.o_proj(attn_output)
495
+
496
+ if not output_attentions:
497
+ attn_weights = None
498
+
499
+ return attn_output, attn_weights, past_key_value
500
+
501
+ def _flash_attention_forward(
502
+ self,
503
+ query_states,
504
+ key_states,
505
+ value_states,
506
+ attention_mask,
507
+ query_length,
508
+ dropout=0.0,
509
+ softmax_scale=None,
510
+ use_sliding_windows=False,
511
+ ):
512
+ if not self._flash_attn_uses_top_left_mask:
513
+ causal = self.is_causal
514
+ else:
515
+ causal = self.is_causal and query_length != 1
516
+
517
+ if attention_mask is not None:
518
+ batch_size = query_states.shape[0]
519
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
520
+ query_states, key_states, value_states, attention_mask, query_length
521
+ )
522
+
523
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
524
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
525
+
526
+ if not use_sliding_windows:
527
+ attn_output_unpad = flash_attn_varlen_func(
528
+ query_states,
529
+ key_states,
530
+ value_states,
531
+ cu_seqlens_q=cu_seqlens_q,
532
+ cu_seqlens_k=cu_seqlens_k,
533
+ max_seqlen_q=max_seqlen_in_batch_q,
534
+ max_seqlen_k=max_seqlen_in_batch_k,
535
+ dropout_p=dropout,
536
+ softmax_scale=softmax_scale,
537
+ causal=causal,
538
+ )
539
+ else:
540
+ attn_output_unpad = flash_attn_varlen_func(
541
+ query_states,
542
+ key_states,
543
+ value_states,
544
+ cu_seqlens_q=cu_seqlens_q,
545
+ cu_seqlens_k=cu_seqlens_k,
546
+ max_seqlen_q=max_seqlen_in_batch_q,
547
+ max_seqlen_k=max_seqlen_in_batch_k,
548
+ dropout_p=dropout,
549
+ softmax_scale=softmax_scale,
550
+ causal=causal,
551
+ window_size=(self.config.sliding_window, self.config.sliding_window),
552
+ )
553
+
554
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
555
+ else:
556
+ if not use_sliding_windows:
557
+ attn_output = flash_attn_func(
558
+ query_states,
559
+ key_states,
560
+ value_states,
561
+ dropout,
562
+ softmax_scale=softmax_scale,
563
+ causal=causal,
564
+ )
565
+ else:
566
+ attn_output = flash_attn_func(
567
+ query_states,
568
+ key_states,
569
+ value_states,
570
+ dropout,
571
+ softmax_scale=softmax_scale,
572
+ causal=causal,
573
+ window_size=(self.config.sliding_window, self.config.sliding_window),
574
+ )
575
+
576
+ return attn_output
577
+
578
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
579
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
580
+
581
+ if kv_seq_len != attention_mask.shape[-1]:
582
+ attention_mask_num_tokens = attention_mask.shape[-1]
583
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
584
+
585
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
586
+
587
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
588
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
589
+
590
+ if query_length == kv_seq_len:
591
+ query_layer = index_first_axis(
592
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
593
+ )
594
+ cu_seqlens_q = cu_seqlens_k
595
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
596
+ indices_q = indices_k
597
+ elif query_length == 1:
598
+ max_seqlen_in_batch_q = 1
599
+ cu_seqlens_q = torch.arange(
600
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
601
+ )
602
+ indices_q = cu_seqlens_q[:-1]
603
+ query_layer = query_layer.squeeze(1)
604
+ else:
605
+ attention_mask = attention_mask[:, -query_length:]
606
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
607
+
608
+ return (
609
+ query_layer,
610
+ key_layer,
611
+ value_layer,
612
+ indices_q,
613
+ (cu_seqlens_q, cu_seqlens_k),
614
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
615
+ )
616
+
617
+
618
+ class LumeesSdpaAttention(LumeesAttention):
619
+ """
620
+ Lumees attention module using torch.nn.functional.scaled_dot_product_attention.
621
+ """
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ attention_mask: Optional[torch.Tensor] = None,
627
+ position_ids: Optional[torch.LongTensor] = None,
628
+ past_key_value: Optional[Cache] = None,
629
+ output_attentions: bool = False,
630
+ use_cache: bool = False,
631
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
632
+ if output_attentions:
633
+ logger.warning_once(
634
+ "LumeesModel is using LumeesSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation."
635
+ )
636
+ return super().forward(
637
+ hidden_states=hidden_states,
638
+ attention_mask=attention_mask,
639
+ position_ids=position_ids,
640
+ past_key_value=past_key_value,
641
+ output_attentions=output_attentions,
642
+ use_cache=use_cache,
643
+ )
644
+
645
+ bsz, q_len, _ = hidden_states.size()
646
+
647
+ qkv = self.qkv_proj(hidden_states)
648
+ query_pos = self.num_heads * self.head_dim
649
+ query_states = qkv[..., :query_pos]
650
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
651
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
652
+
653
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
654
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
655
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
656
+
657
+ kv_seq_len = key_states.shape[-2]
658
+ if past_key_value is not None:
659
+ # FIX: Use get_seq_length if get_usable_length is missing
660
+ if hasattr(past_key_value, "get_usable_length"):
661
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
662
+ else:
663
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
664
+
665
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
666
+
667
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
668
+
669
+ if past_key_value is not None:
670
+ cache_kwargs = {"sin": sin, "cos": cos}
671
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
672
+
673
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
674
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
675
+
676
+ if attention_mask is not None:
677
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
678
+ raise ValueError(
679
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
680
+ )
681
+
682
+ if query_states.device.type == "cuda" and attention_mask is not None:
683
+ query_states = query_states.contiguous()
684
+ key_states = key_states.contiguous()
685
+ value_states = value_states.contiguous()
686
+
687
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
688
+ query_states,
689
+ key_states,
690
+ value_states,
691
+ attn_mask=attention_mask,
692
+ dropout_p=self.attention_dropout if self.training else 0.0,
693
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
694
+ )
695
+
696
+ attn_output = attn_output.transpose(1, 2).contiguous()
697
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
698
+
699
+ attn_output = self.o_proj(attn_output)
700
+
701
+ return attn_output, None, past_key_value
702
+
703
+
704
+ LUMEES_ATTENTION_CLASSES = {
705
+ "eager": LumeesAttention,
706
+ "flash_attention_2": LumeesFlashAttention2,
707
+ "sdpa": LumeesSdpaAttention,
708
+ }
709
+
710
+
711
+ class LumeesDecoderLayer(nn.Module):
712
+ def __init__(self, config: LumeesConfig, layer_idx: int):
713
+ super().__init__()
714
+
715
+ self.config = config
716
+ self.self_attn = LUMEES_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
717
+
718
+ self.mlp = LumeesMLP(config)
719
+ self.input_layernorm = LumeesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
720
+
721
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
722
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
723
+ self.post_attention_layernorm = LumeesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
724
+
725
+ def forward(
726
+ self,
727
+ hidden_states: torch.Tensor,
728
+ attention_mask: Optional[torch.Tensor] = None,
729
+ position_ids: Optional[torch.LongTensor] = None,
730
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
731
+ output_attentions: Optional[bool] = False,
732
+ use_cache: Optional[bool] = False,
733
+ **kwargs,
734
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
735
+ if "padding_mask" in kwargs:
736
+ warnings.warn(
737
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
738
+ )
739
+
740
+ residual = hidden_states
741
+
742
+ hidden_states = self.input_layernorm(hidden_states)
743
+
744
+ # Self Attention
745
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
746
+ hidden_states=hidden_states,
747
+ attention_mask=attention_mask,
748
+ position_ids=position_ids,
749
+ past_key_value=past_key_value,
750
+ output_attentions=output_attentions,
751
+ use_cache=use_cache,
752
+ )
753
+
754
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
755
+
756
+ residual = hidden_states
757
+ hidden_states = self.post_attention_layernorm(hidden_states)
758
+ hidden_states = self.mlp(hidden_states)
759
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
760
+
761
+ outputs = (hidden_states,)
762
+
763
+ if output_attentions:
764
+ outputs += (self_attn_weights,)
765
+
766
+ if use_cache:
767
+ outputs += (present_key_value,)
768
+
769
+ return outputs
770
+
771
+
772
+ LUMEES_START_DOCSTRING = r"""
773
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
774
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
775
+ etc.)
776
+
777
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
778
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
779
+ and behavior.
780
+
781
+ Parameters:
782
+ config ([`LumeesConfig`]):
783
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
784
+ load the weights associated with the model, only the configuration. Check out the
785
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
786
+ """
787
+
788
+
789
+ @add_start_docstrings(
790
+ "The bare Lumees model outputting raw hidden-states without any specific head on top.",
791
+ LUMEES_START_DOCSTRING,
792
+ )
793
+ class LumeesPreTrainedModel(PreTrainedModel):
794
+ config_class = LumeesConfig
795
+ base_model_prefix = "model"
796
+ supports_gradient_checkpointing = True
797
+ _no_split_modules = ["LumeesDecoderLayer"]
798
+ _skip_keys_device_placement = "past_key_values"
799
+ _supports_flash_attn_2 = True
800
+ _supports_sdpa = False
801
+ _supports_cache_class = True
802
+
803
+ _version = "0.0.1"
804
+
805
+ def _init_weights(self, module):
806
+ std = self.config.initializer_range
807
+ if isinstance(module, nn.Linear):
808
+ module.weight.data.normal_(mean=0.0, std=std)
809
+ if module.bias is not None:
810
+ module.bias.data.zero_()
811
+ elif isinstance(module, nn.Embedding):
812
+ module.weight.data.normal_(mean=0.0, std=std)
813
+ if module.padding_idx is not None:
814
+ module.weight.data[module.padding_idx].zero_()
815
+
816
+
817
+ LUMEES_INPUTS_DOCSTRING = r"""
818
+ Args:
819
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
820
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
821
+ it.
822
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
823
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
824
+
825
+ - 1 for tokens that are **not masked**,
826
+ - 0 for tokens that are **masked**.
827
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
828
+ Indices of positions of each input sequence tokens in the position embeddings.
829
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
830
+ Pre-computed hidden-states (key and values in the self-attention blocks).
831
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
832
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
833
+ use_cache (`bool`, *optional*):
834
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding.
835
+ output_attentions (`bool`, *optional*):
836
+ Whether or not to return the attentions tensors of all attention layers.
837
+ output_hidden_states (`bool`, *optional*):
838
+ Whether or not to return the hidden states of all layers.
839
+ return_dict (`bool`, *optional*):
840
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
841
+ """
842
+
843
+
844
+ @add_start_docstrings(
845
+ "The bare Lumees model outputting raw hidden-states without any specific head on top.",
846
+ LUMEES_START_DOCSTRING,
847
+ )
848
+ class LumeesModel(LumeesPreTrainedModel):
849
+ """
850
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LumeesDecoderLayer`]
851
+
852
+ Args:
853
+ config: LumeesConfig
854
+ """
855
+
856
+ def __init__(self, config: LumeesConfig):
857
+ super().__init__(config)
858
+ self.padding_idx = config.pad_token_id
859
+ self.vocab_size = config.vocab_size
860
+
861
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
862
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
863
+ self.layers = nn.ModuleList(
864
+ [LumeesDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
865
+ )
866
+ self._attn_implementation = config._attn_implementation
867
+ self.norm = LumeesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
868
+
869
+ self.gradient_checkpointing = False
870
+ self.post_init()
871
+
872
+ def get_input_embeddings(self):
873
+ return self.embed_tokens
874
+
875
+ def set_input_embeddings(self, value):
876
+ self.embed_tokens = value
877
+
878
+ @add_start_docstrings_to_model_forward(LUMEES_INPUTS_DOCSTRING)
879
+ def forward(
880
+ self,
881
+ input_ids: torch.LongTensor = None,
882
+ attention_mask: Optional[torch.Tensor] = None,
883
+ position_ids: Optional[torch.LongTensor] = None,
884
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
885
+ inputs_embeds: Optional[torch.FloatTensor] = None,
886
+ use_cache: Optional[bool] = None,
887
+ output_attentions: Optional[bool] = None,
888
+ output_hidden_states: Optional[bool] = None,
889
+ return_dict: Optional[bool] = None,
890
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
891
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
892
+ output_hidden_states = (
893
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
894
+ )
895
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
896
+
897
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
898
+
899
+ if input_ids is not None and inputs_embeds is not None:
900
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
901
+ elif input_ids is not None:
902
+ batch_size, seq_length = input_ids.shape[:2]
903
+ elif inputs_embeds is not None:
904
+ batch_size, seq_length = inputs_embeds.shape[:2]
905
+ else:
906
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
907
+
908
+ past_key_values_length = 0
909
+
910
+ if self.gradient_checkpointing and self.training:
911
+ if use_cache:
912
+ logger.warning_once(
913
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
914
+ )
915
+ use_cache = False
916
+
917
+ if use_cache:
918
+ use_legacy_cache = not isinstance(past_key_values, Cache)
919
+ if use_legacy_cache:
920
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
921
+
922
+ # FIX: Robust check for get_usable_length vs get_seq_length
923
+ if hasattr(past_key_values, "get_usable_length"):
924
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
925
+ else:
926
+ past_key_values_length = past_key_values.get_seq_length()
927
+
928
+ if position_ids is None:
929
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
930
+ position_ids = torch.arange(
931
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
932
+ )
933
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
934
+ else:
935
+ position_ids = position_ids.view(-1, seq_length).long()
936
+
937
+ if inputs_embeds is None:
938
+ inputs_embeds = self.embed_tokens(input_ids)
939
+
940
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
941
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
942
+ if is_padding_right:
943
+ raise ValueError(
944
+ "You are attempting to perform batched generation with padding_side='right' "
945
+ "this may lead to unexpected behaviour for Flash Attention."
946
+ )
947
+
948
+ if self._attn_implementation == "flash_attention_2":
949
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
950
+ else:
951
+ attention_mask = _prepare_4d_causal_attention_mask(
952
+ attention_mask,
953
+ (batch_size, seq_length),
954
+ inputs_embeds,
955
+ past_key_values_length,
956
+ sliding_window=self.config.sliding_window,
957
+ )
958
+
959
+ hidden_states = inputs_embeds
960
+
961
+ all_hidden_states = () if output_hidden_states else None
962
+ all_self_attns = () if output_attentions else None
963
+ next_decoder_cache = None
964
+
965
+ for decoder_layer in self.layers:
966
+ if output_hidden_states:
967
+ all_hidden_states += (hidden_states,)
968
+
969
+ if self.gradient_checkpointing and self.training:
970
+ layer_outputs = self._gradient_checkpointing_func(
971
+ decoder_layer.__call__,
972
+ hidden_states,
973
+ attention_mask,
974
+ position_ids,
975
+ past_key_values,
976
+ output_attentions,
977
+ use_cache,
978
+ )
979
+ else:
980
+ layer_outputs = decoder_layer(
981
+ hidden_states,
982
+ attention_mask=attention_mask,
983
+ position_ids=position_ids,
984
+ past_key_value=past_key_values,
985
+ output_attentions=output_attentions,
986
+ use_cache=use_cache,
987
+ )
988
+
989
+ hidden_states = layer_outputs[0]
990
+
991
+ if use_cache:
992
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
993
+
994
+ if output_attentions:
995
+ all_self_attns += (layer_outputs[1],)
996
+
997
+ hidden_states = self.norm(hidden_states)
998
+
999
+ if output_hidden_states:
1000
+ all_hidden_states += (hidden_states,)
1001
+
1002
+ next_cache = None
1003
+ if use_cache:
1004
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1005
+ if not return_dict:
1006
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1007
+ return BaseModelOutputWithPast(
1008
+ last_hidden_state=hidden_states,
1009
+ past_key_values=next_cache,
1010
+ hidden_states=all_hidden_states,
1011
+ attentions=all_self_attns,
1012
+ )
1013
+
1014
+
1015
+ class LumeesForCausalLM(LumeesPreTrainedModel):
1016
+ _tied_weights_keys = ["lm_head.weight"]
1017
+
1018
+ def __init__(self, config):
1019
+ super().__init__(config)
1020
+ self.model = LumeesModel(config)
1021
+ self.vocab_size = config.vocab_size
1022
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1023
+
1024
+ self.post_init()
1025
+
1026
+ def get_input_embeddings(self):
1027
+ return self.model.embed_tokens
1028
+
1029
+ def set_input_embeddings(self, value):
1030
+ self.model.embed_tokens = value
1031
+
1032
+ def get_output_embeddings(self):
1033
+ return self.lm_head
1034
+
1035
+ def set_output_embeddings(self, new_embeddings):
1036
+ self.lm_head = new_embeddings
1037
+
1038
+ def set_decoder(self, decoder):
1039
+ self.model = decoder
1040
+
1041
+ def get_decoder(self):
1042
+ return self.model
1043
+
1044
+ @add_start_docstrings_to_model_forward(LUMEES_INPUTS_DOCSTRING)
1045
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1046
+ def forward(
1047
+ self,
1048
+ input_ids: torch.LongTensor = None,
1049
+ attention_mask: Optional[torch.Tensor] = None,
1050
+ position_ids: Optional[torch.LongTensor] = None,
1051
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1052
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1053
+ labels: Optional[torch.LongTensor] = None,
1054
+ use_cache: Optional[bool] = None,
1055
+ output_attentions: Optional[bool] = None,
1056
+ output_hidden_states: Optional[bool] = None,
1057
+ return_dict: Optional[bool] = None,
1058
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1059
+ r"""
1060
+ Args:
1061
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1062
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1063
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1064
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1065
+
1066
+ Returns:
1067
+ """
1068
+
1069
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1070
+ output_hidden_states = (
1071
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1072
+ )
1073
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1074
+
1075
+ outputs = self.model(
1076
+ input_ids=input_ids,
1077
+ attention_mask=attention_mask,
1078
+ position_ids=position_ids,
1079
+ past_key_values=past_key_values,
1080
+ inputs_embeds=inputs_embeds,
1081
+ use_cache=use_cache,
1082
+ output_attentions=output_attentions,
1083
+ output_hidden_states=output_hidden_states,
1084
+ return_dict=return_dict,
1085
+ )
1086
+
1087
+ hidden_states = outputs[0]
1088
+ logits = self.lm_head(hidden_states)
1089
+ logits = logits.float()
1090
+
1091
+ loss = None
1092
+ if labels is not None:
1093
+ shift_logits = logits[..., :-1, :].contiguous()
1094
+ shift_labels = labels[..., 1:].contiguous()
1095
+ loss_fct = CrossEntropyLoss()
1096
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1097
+ shift_labels = shift_labels.view(-1)
1098
+ shift_labels = shift_labels.to(shift_logits.device)
1099
+ loss = loss_fct(shift_logits, shift_labels)
1100
+
1101
+ if not return_dict:
1102
+ output = (logits,) + outputs[1:]
1103
+ return (loss,) + output if loss is not None else output
1104
+
1105
+ return CausalLMOutputWithPast(
1106
+ loss=loss,
1107
+ logits=logits,
1108
+ past_key_values=outputs.past_key_values,
1109
+ hidden_states=outputs.hidden_states,
1110
+ attentions=outputs.attentions,
1111
+ )
1112
+
1113
+ def prepare_inputs_for_generation(
1114
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1115
+ ):
1116
+ if past_key_values is not None:
1117
+ if isinstance(past_key_values, Cache):
1118
+ cache_length = past_key_values.get_seq_length()
1119
+ past_length = past_key_values.get_seq_length()
1120
+
1121
+ # FIX: Robust check for get_max_length (missing in some DynamicCache versions)
1122
+ if hasattr(past_key_values, "get_max_length"):
1123
+ max_cache_length = past_key_values.get_max_length()
1124
+ else:
1125
+ max_cache_length = None
1126
+ else:
1127
+ # Legacy tuple cache format
1128
+ cache_length = past_length = past_key_values[0][0].shape[2]
1129
+ max_cache_length = None
1130
+
1131
+ # Keep only the unprocessed tokens:
1132
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1133
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1134
+ elif past_length < input_ids.shape[1]:
1135
+ input_ids = input_ids[:, past_length:]
1136
+
1137
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1138
+ if (
1139
+ max_cache_length is not None
1140
+ and attention_mask is not None
1141
+ and cache_length + input_ids.shape[1] > max_cache_length
1142
+ ):
1143
+ attention_mask = attention_mask[:, -max_cache_length:]
1144
+
1145
+ position_ids = kwargs.get("position_ids", None)
1146
+ if attention_mask is not None and position_ids is None:
1147
+ # create position_ids on the fly for batch generation
1148
+ position_ids = attention_mask.long().cumsum(-1) - 1
1149
+ position_ids.masked_fill_(attention_mask == 0, 1)
1150
+ if past_key_values:
1151
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1152
+
1153
+ if inputs_embeds is not None and past_key_values is None:
1154
+ model_inputs = {"inputs_embeds": inputs_embeds}
1155
+ else:
1156
+ model_inputs = {"input_ids": input_ids}
1157
+
1158
+ model_inputs.update(
1159
+ {
1160
+ "position_ids": position_ids,
1161
+ "past_key_values": past_key_values,
1162
+ "use_cache": kwargs.get("use_cache"),
1163
+ "attention_mask": attention_mask,
1164
+ }
1165
+ )
1166
+ return model_inputs
1167
+ @staticmethod
1168
+ def _reorder_cache(past_key_values, beam_idx):
1169
+ reordered_past = ()
1170
+ for layer_past in past_key_values:
1171
+ reordered_past += (
1172
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1173
+ )
1174
+ return reordered_past
1175
+
1176
+
1177
+ @add_start_docstrings(
1178
+ """
1179
+ The [`LumeesModel`] with a sequence classification head on top (linear layer).
1180
+ """,
1181
+ LUMEES_START_DOCSTRING,
1182
+ )
1183
+ class LumeesForSequenceClassification(LumeesPreTrainedModel):
1184
+ def __init__(self, config):
1185
+ super().__init__(config)
1186
+ self.num_labels = config.num_labels
1187
+ self.model = LumeesModel(config)
1188
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1189
+
1190
+ self.post_init()
1191
+
1192
+ def get_input_embeddings(self):
1193
+ return self.model.embed_tokens
1194
+
1195
+ def set_input_embeddings(self, value):
1196
+ self.model.embed_tokens = value
1197
+
1198
+ @add_start_docstrings_to_model_forward(LUMEES_INPUTS_DOCSTRING)
1199
+ def forward(
1200
+ self,
1201
+ input_ids: torch.LongTensor = None,
1202
+ attention_mask: Optional[torch.Tensor] = None,
1203
+ position_ids: Optional[torch.LongTensor] = None,
1204
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1205
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1206
+ labels: Optional[torch.LongTensor] = None,
1207
+ use_cache: Optional[bool] = None,
1208
+ output_attentions: Optional[bool] = None,
1209
+ output_hidden_states: Optional[bool] = None,
1210
+ return_dict: Optional[bool] = None,
1211
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1212
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1213
+
1214
+ model_outputs = self.model(
1215
+ input_ids,
1216
+ attention_mask=attention_mask,
1217
+ position_ids=position_ids,
1218
+ past_key_values=past_key_values,
1219
+ inputs_embeds=inputs_embeds,
1220
+ use_cache=use_cache,
1221
+ output_attentions=output_attentions,
1222
+ output_hidden_states=output_hidden_states,
1223
+ return_dict=return_dict,
1224
+ )
1225
+ hidden_states = model_outputs[0]
1226
+ logits = self.score(hidden_states)
1227
+
1228
+ if input_ids is not None:
1229
+ batch_size = input_ids.shape[0]
1230
+ else:
1231
+ batch_size = inputs_embeds.shape[0]
1232
+
1233
+ if self.config.pad_token_id is None and batch_size != 1:
1234
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1235
+ if self.config.pad_token_id is None:
1236
+ sequence_lengths = -1
1237
+ else:
1238
+ if input_ids is not None:
1239
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1240
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1241
+ sequence_lengths = sequence_lengths.to(logits.device)
1242
+ else:
1243
+ sequence_lengths = -1
1244
+
1245
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1246
+
1247
+ loss = None
1248
+ if labels is not None:
1249
+ labels = labels.to(logits.device)
1250
+ if self.config.problem_type is None:
1251
+ if self.num_labels == 1:
1252
+ self.config.problem_type = "regression"
1253
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1254
+ self.config.problem_type = "single_label_classification"
1255
+ else:
1256
+ self.config.problem_type = "multi_label_classification"
1257
+
1258
+ if self.config.problem_type == "regression":
1259
+ loss_fct = MSELoss()
1260
+ if self.num_labels == 1:
1261
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1262
+ else:
1263
+ loss = loss_fct(pooled_logits, labels)
1264
+ elif self.config.problem_type == "single_label_classification":
1265
+ loss_fct = CrossEntropyLoss()
1266
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1267
+ elif self.config.problem_type == "multi_label_classification":
1268
+ loss_fct = BCEWithLogitsLoss()
1269
+ loss = loss_fct(pooled_logits, labels)
1270
+ if not return_dict:
1271
+ output = (pooled_logits,) + model_outputs[1:]
1272
+ return ((loss,) + output) if loss is not None else output
1273
+
1274
+ return SequenceClassifierOutputWithPast(
1275
+ loss=loss,
1276
+ logits=pooled_logits,
1277
+ past_key_values=model_outputs.past_key_values,
1278
+ hidden_states=model_outputs.hidden_states,
1279
+ attentions=model_outputs.attentions,
1280
+ )
1281
+
1282
+
1283
+ @add_start_docstrings(
1284
+ """
1285
+ [`LumeesModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1286
+ Named-Entity-Recognition (NER) tasks.
1287
+ """,
1288
+ LUMEES_START_DOCSTRING,
1289
+ )
1290
+ class LumeesForTokenClassification(LumeesPreTrainedModel):
1291
+ def __init__(self, config: LumeesConfig):
1292
+ super().__init__(config)
1293
+ self.num_labels = config.num_labels
1294
+
1295
+ self.model = LumeesModel(config)
1296
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1297
+ classifier_dropout = config.classifier_dropout
1298
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1299
+ classifier_dropout = config.hidden_dropout
1300
+ else:
1301
+ classifier_dropout = 0.1
1302
+ self.dropout = nn.Dropout(classifier_dropout)
1303
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1304
+
1305
+ self.post_init()
1306
+
1307
+ @add_start_docstrings_to_model_forward(LUMEES_INPUTS_DOCSTRING)
1308
+ @add_code_sample_docstrings(
1309
+ checkpoint=_CHECKPOINT_FOR_DOC,
1310
+ output_type=TokenClassifierOutput,
1311
+ config_class=_CONFIG_FOR_DOC,
1312
+ )
1313
+ def forward(
1314
+ self,
1315
+ input_ids: Optional[torch.LongTensor] = None,
1316
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1317
+ attention_mask: Optional[torch.Tensor] = None,
1318
+ inputs_embeds: Optional[torch.Tensor] = None,
1319
+ labels: Optional[torch.Tensor] = None,
1320
+ use_cache: Optional[bool] = None,
1321
+ output_attentions: Optional[bool] = None,
1322
+ output_hidden_states: Optional[bool] = None,
1323
+ return_dict: Optional[bool] = None,
1324
+ **deprecated_arguments,
1325
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1326
+ r"""
1327
+ Args:
1328
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1329
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1330
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1331
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1332
+ """
1333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1334
+
1335
+ model_outputs = self.model(
1336
+ input_ids,
1337
+ past_key_values=past_key_values,
1338
+ attention_mask=attention_mask,
1339
+ inputs_embeds=inputs_embeds,
1340
+ use_cache=use_cache,
1341
+ output_attentions=output_attentions,
1342
+ output_hidden_states=output_hidden_states,
1343
+ return_dict=return_dict,
1344
+ )
1345
+
1346
+ hidden_states = model_outputs[0]
1347
+ hidden_states = self.dropout(hidden_states)
1348
+ logits = self.classifier(hidden_states)
1349
+
1350
+ loss = None
1351
+ if labels is not None:
1352
+ labels = labels.to(logits.device)
1353
+ batch_size, seq_length = labels.shape
1354
+ loss_fct = CrossEntropyLoss()
1355
+ loss = loss_fct(
1356
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1357
+ )
1358
+
1359
+ if not return_dict:
1360
+ output = (logits,) + model_outputs[2:]
1361
+ return ((loss,) + output) if loss is not None else output
1362
+
1363
+ return TokenClassifierOutput(
1364
+ loss=loss,
1365
+ logits=logits,
1366
+ hidden_states=model_outputs.hidden_states,
1367
+ attentions=model_outputs.attentions,
1368
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|placeholder2|>",
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.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|thought|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "</|thought|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": true,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "32011": {
119
+ "content": "<|placeholder1|>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": true,
123
+ "single_word": false,
124
+ "special": true
125
+ },
126
+ "32012": {
127
+ "content": "<|placeholder2|>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": true
133
+ }
134
+ },
135
+ "bos_token": "<s>",
136
+ "clean_up_tokenization_spaces": false,
137
+ "eos_token": "<|endoftext|>",
138
+ "extra_special_tokens": {},
139
+ "legacy": false,
140
+ "model_max_length": 4096,
141
+ "pad_token": "<|placeholder2|>",
142
+ "padding_side": "left",
143
+ "sp_model_kwargs": {},
144
+ "tokenizer_class": "LlamaTokenizer",
145
+ "unk_token": "<unk>",
146
+ "use_default_system_prompt": false
147
+ }