wilstrup commited on
Commit
9f6466e
1 Parent(s): 12ce5dd

Upload LightpostForCausalLM

Browse files
config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Qwen/Qwen2.5-1.5B-Instruct",
3
+ "architectures": [
4
+ "LightpostForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_lightpost.LightpostConfig",
9
+ "AutoModelForCausalLM": "modeling_lightpost.LightpostForCausalLM"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "eos_token_id": 151645,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 1536,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 8960,
17
+ "max_position_embeddings": 32768,
18
+ "max_window_layers": 21,
19
+ "mem_layers": [
20
+ 2,
21
+ 3,
22
+ 4,
23
+ 5,
24
+ 6,
25
+ 7,
26
+ 8,
27
+ 9,
28
+ 10,
29
+ 11,
30
+ 12,
31
+ 13,
32
+ 14,
33
+ 15,
34
+ 16,
35
+ 17,
36
+ 18,
37
+ 19,
38
+ 20,
39
+ 21,
40
+ 22,
41
+ 23,
42
+ 24,
43
+ 25,
44
+ 26,
45
+ 27
46
+ ],
47
+ "mem_size": 4096,
48
+ "model_type": "lightpost",
49
+ "num_attention_heads": 12,
50
+ "num_hidden_layers": 28,
51
+ "num_key_value_heads": 2,
52
+ "rms_norm_eps": 1e-06,
53
+ "rope_scaling": null,
54
+ "rope_theta": 1000000.0,
55
+ "sliding_window": null,
56
+ "tie_word_embeddings": true,
57
+ "torch_dtype": "float32",
58
+ "transformers_version": "4.46.1",
59
+ "use_cache": true,
60
+ "use_sliding_window": false,
61
+ "vocab_size": 151936
62
+ }
configuration_lightpost.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Lightpost ApS. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5
+ # compliance with the License. You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software distributed under the License is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and limitations under the License.
12
+ """Lightpost model configuration"""
13
+
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.modeling_rope_utils import rope_config_validation
16
+ from transformers.utils import logging
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class LightpostConfig(PretrainedConfig):
23
+ r"""
24
+ Configuration class for the Lightpost model. This class stores all parameters needed to define the model architecture.
25
+
26
+ Inherits from PretrainedConfig to provide standard configuration functionality. See PretrainedConfig docs for details.
27
+
28
+ Args:
29
+ vocab_size (int, optional, defaults to 151936):
30
+ Size of model vocabulary. Determines number of unique tokens model can process.
31
+
32
+ hidden_size (int, optional, defaults to 4096):
33
+ Dimension of model's hidden states.
34
+
35
+ intermediate_size (int, optional, defaults to 22016):
36
+ Dimension of feed-forward network layers.
37
+
38
+ num_hidden_layers (int, optional, defaults to 32):
39
+ Number of transformer layers in model.
40
+
41
+ num_attention_heads (int, optional, defaults to 32):
42
+ Number of attention heads per layer.
43
+
44
+ num_key_value_heads (int, optional, defaults to 32):
45
+ Number of key/value heads for Grouped Query Attention (GQA).
46
+ - If equal to num_attention_heads: Uses Multi-Head Attention (MHA)
47
+ - If equal to 1: Uses Multi-Query Attention (MQA)
48
+ - Otherwise: Uses GQA with specified number of groups
49
+
50
+ hidden_act (str or callable, optional, defaults to "silu"):
51
+ Activation function used in feed-forward layers.
52
+
53
+ max_position_embeddings (int, optional, defaults to 32768):
54
+ Maximum sequence length model can handle.
55
+
56
+ initializer_range (float, optional, defaults to 0.02):
57
+ Standard deviation for weight initialization.
58
+
59
+ rms_norm_eps (float, optional, defaults to 1e-06):
60
+ Epsilon for RMSNorm layers.
61
+
62
+ use_cache (bool, optional, defaults to True):
63
+ Whether to use key/value cache for faster inference.
64
+
65
+ tie_word_embeddings (bool, optional, defaults to False):
66
+ Whether to tie input and output embeddings.
67
+
68
+ rope_theta (float, optional, defaults to 10000.0):
69
+ Base frequency for rotary position embeddings.
70
+
71
+ rope_scaling (dict, optional):
72
+ Configuration for RoPE scaling. Supported types:
73
+ - default: Original RoPE
74
+ - linear: Linear scaling
75
+ - dynamic: Dynamic scaling
76
+ - yarn: YaRN scaling
77
+ - longrope: LongRoPE scaling
78
+ - llama3: Llama 3 style scaling
79
+
80
+ See implementation docs for type-specific parameters.
81
+
82
+ use_sliding_window (bool, optional, defaults to False):
83
+ Whether to use sliding window attention.
84
+
85
+ sliding_window (int, optional, defaults to 4096):
86
+ Size of sliding attention window.
87
+
88
+ max_window_layers (int, optional, defaults to 28):
89
+ Number of bottom layers using sliding window attention.
90
+
91
+ attention_dropout (float, optional, defaults to 0.0):
92
+ Dropout probability for attention weights.
93
+
94
+ mem_size (int, optional, defaults to 32):
95
+ Size of the learnable memory.
96
+
97
+ mem_layers (int or list[int], optional, defaults to None):
98
+ Layers to apply memory attention to.
99
+
100
+ Example:
101
+ >>> from transformers import LightpostModel, LightpostConfig
102
+ >>> config = LightpostConfig() # Initialize with defaults
103
+ >>> model = LightpostModel(config) # Create model
104
+ >>> model.config # Access configuration
105
+ """
106
+
107
+ model_type = "lightpost"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+
110
+ def __init__(
111
+ self,
112
+ vocab_size=151936,
113
+ hidden_size=4096,
114
+ intermediate_size=22016,
115
+ num_hidden_layers=32,
116
+ num_attention_heads=32,
117
+ num_key_value_heads=32,
118
+ hidden_act="silu",
119
+ max_position_embeddings=32768,
120
+ initializer_range=0.02,
121
+ rms_norm_eps=1e-6,
122
+ use_cache=True,
123
+ tie_word_embeddings=False,
124
+ rope_theta=10000.0,
125
+ rope_scaling=None,
126
+ use_sliding_window=False,
127
+ sliding_window=4096,
128
+ max_window_layers=28,
129
+ attention_dropout=0.0,
130
+ mem_size=32,
131
+ mem_layers=None,
132
+ **kwargs,
133
+ ):
134
+ self.vocab_size = vocab_size
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.hidden_size = hidden_size
137
+ self.intermediate_size = intermediate_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+ self.use_sliding_window = use_sliding_window
141
+ self.sliding_window = sliding_window if use_sliding_window else None
142
+ self.max_window_layers = max_window_layers
143
+ self.num_key_value_heads = num_key_value_heads
144
+ self.hidden_act = hidden_act
145
+ self.initializer_range = initializer_range
146
+ self.rms_norm_eps = rms_norm_eps
147
+ self.use_cache = use_cache
148
+ self.rope_theta = rope_theta
149
+ self.rope_scaling = rope_scaling
150
+ self.attention_dropout = attention_dropout
151
+ self.mem_size = mem_size
152
+ self.mem_layers = mem_layers
153
+ # Validate the correctness of rotary position embeddings parameters
154
+ rope_config_validation(self)
155
+
156
+ super().__init__(
157
+ tie_word_embeddings=tie_word_embeddings,
158
+ **kwargs,
159
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.1,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.46.1"
14
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04be499f4bbc4270c3cd6e0f3d85f349db0f600a044b24a5fabdd236d85da23d
3
+ size 4957245200
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c31bf8b80f94a75b9ee6e6c83855491d82525d2e556dd693731b78d4197fe95
3
+ size 2771649528
model.safetensors.index.json ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7728846848
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.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.k_proj.bias": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
30
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
37
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.10.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
39
+ "model.layers.10.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
40
+ "model.layers.10.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
43
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
45
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
52
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.11.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
54
+ "model.layers.11.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
55
+ "model.layers.11.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
58
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
60
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
67
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.12.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
69
+ "model.layers.12.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
70
+ "model.layers.12.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
73
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
75
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
82
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.13.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
84
+ "model.layers.13.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
85
+ "model.layers.13.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
88
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
90
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
97
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.14.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
99
+ "model.layers.14.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
100
+ "model.layers.14.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
103
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
105
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
112
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.15.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
114
+ "model.layers.15.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
115
+ "model.layers.15.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
118
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
120
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
127
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.16.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
129
+ "model.layers.16.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
130
+ "model.layers.16.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
133
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
135
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
142
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.17.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
144
+ "model.layers.17.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
145
+ "model.layers.17.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
147
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
148
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
149
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
150
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
151
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors",
152
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
157
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.18.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
159
+ "model.layers.18.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
160
+ "model.layers.18.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
163
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
165
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
166
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
170
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.19.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
172
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
173
+ "model.layers.19.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
174
+ "model.layers.19.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
175
+ "model.layers.19.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.19.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
178
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.19.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
180
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
187
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.2.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
189
+ "model.layers.2.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
190
+ "model.layers.2.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
193
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
195
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
197
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
198
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
199
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
200
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
201
+ "model.layers.20.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
202
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
203
+ "model.layers.20.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
204
+ "model.layers.20.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
205
+ "model.layers.20.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
206
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
207
+ "model.layers.20.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
208
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
209
+ "model.layers.20.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
210
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
211
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
212
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
213
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
214
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
215
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
216
+ "model.layers.21.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
217
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
218
+ "model.layers.21.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
219
+ "model.layers.21.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
220
+ "model.layers.21.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
221
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
222
+ "model.layers.21.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
223
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
224
+ "model.layers.21.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
225
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
226
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
227
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
228
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
229
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
230
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
231
+ "model.layers.22.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
232
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
233
+ "model.layers.22.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
234
+ "model.layers.22.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
235
+ "model.layers.22.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
236
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
237
+ "model.layers.22.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
238
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
239
+ "model.layers.22.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
240
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
241
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
242
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
243
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
244
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
245
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
246
+ "model.layers.23.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
247
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
248
+ "model.layers.23.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
249
+ "model.layers.23.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
250
+ "model.layers.23.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
251
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
252
+ "model.layers.23.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
253
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
254
+ "model.layers.23.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
255
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
256
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
257
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
258
+ "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
259
+ "model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
260
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
261
+ "model.layers.24.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
262
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
263
+ "model.layers.24.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
264
+ "model.layers.24.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
265
+ "model.layers.24.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
266
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
267
+ "model.layers.24.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
268
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
269
+ "model.layers.24.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
270
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
271
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
272
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
273
+ "model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
274
+ "model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
275
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
276
+ "model.layers.25.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
277
+ "model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
278
+ "model.layers.25.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
279
+ "model.layers.25.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
280
+ "model.layers.25.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
281
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
282
+ "model.layers.25.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
283
+ "model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
284
+ "model.layers.25.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
285
+ "model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
286
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
287
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
288
+ "model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
289
+ "model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
290
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
291
+ "model.layers.26.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
292
+ "model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
293
+ "model.layers.26.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
294
+ "model.layers.26.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
295
+ "model.layers.26.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
296
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
297
+ "model.layers.26.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
298
+ "model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
299
+ "model.layers.26.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
300
+ "model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
301
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
302
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
303
+ "model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
304
+ "model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
305
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
306
+ "model.layers.27.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
307
+ "model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
308
+ "model.layers.27.self_attn.mem_attn.keys": "model-00002-of-00002.safetensors",
309
+ "model.layers.27.self_attn.mem_attn.learnable_memory": "model-00002-of-00002.safetensors",
310
+ "model.layers.27.self_attn.mem_attn.q_proj.weight": "model-00002-of-00002.safetensors",
311
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
312
+ "model.layers.27.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
313
+ "model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
314
+ "model.layers.27.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
315
+ "model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
316
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
317
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
318
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
319
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
320
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
321
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
322
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
323
+ "model.layers.3.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
324
+ "model.layers.3.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
325
+ "model.layers.3.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
326
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
327
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
328
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
329
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
330
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
331
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
332
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
333
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
334
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
335
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
336
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
337
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
338
+ "model.layers.4.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
339
+ "model.layers.4.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
340
+ "model.layers.4.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
341
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
342
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
343
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
344
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
345
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
346
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
347
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
348
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
349
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
350
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
351
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
352
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
353
+ "model.layers.5.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
354
+ "model.layers.5.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
355
+ "model.layers.5.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
356
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
357
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
358
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
359
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
360
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
361
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
362
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
363
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
364
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
365
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
366
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
367
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
368
+ "model.layers.6.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
369
+ "model.layers.6.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
370
+ "model.layers.6.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
371
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
372
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
373
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
374
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
375
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
376
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
377
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
378
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
379
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
380
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
381
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
382
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
383
+ "model.layers.7.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
384
+ "model.layers.7.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
385
+ "model.layers.7.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
386
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
387
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
388
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
389
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
390
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
391
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
392
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
393
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
394
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
395
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
396
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
397
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
398
+ "model.layers.8.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
399
+ "model.layers.8.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
400
+ "model.layers.8.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
401
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
402
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
403
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
404
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
405
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
406
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
407
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
408
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
409
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
410
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
411
+ "model.layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
412
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
413
+ "model.layers.9.self_attn.mem_attn.keys": "model-00001-of-00002.safetensors",
414
+ "model.layers.9.self_attn.mem_attn.learnable_memory": "model-00001-of-00002.safetensors",
415
+ "model.layers.9.self_attn.mem_attn.q_proj.weight": "model-00001-of-00002.safetensors",
416
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
417
+ "model.layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
418
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
419
+ "model.layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
420
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
421
+ "model.norm.weight": "model-00002-of-00002.safetensors"
422
+ }
423
+ }
modeling_lightpost.py ADDED
@@ -0,0 +1,1584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Lightpost ApS. All rights reserved.
3
+ #
4
+ # This code is based on Qwen2, which itself is based on EleutherAI's GPT-NeoX library and the GPT-NeoX and
5
+ # OPT implementations in the Transformers library. The code has been modified to support Lightpost's
6
+ # architectural differences, including memory attention and other adaptations that distinguish it from the
7
+ # original GPT-NeoX and OPT architectures.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
10
+ # compliance with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software distributed under the License is
15
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and limitations under the License.
17
+
18
+ """PyTorch Lightpost model."""
19
+
20
+ import math
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_lightpost import LightpostConfig
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+
60
+ _CHECKPOINT_FOR_DOC = "Lightpost/Lightpost2-7B-beta"
61
+ _CONFIG_FOR_DOC = "LightpostConfig"
62
+
63
+ class MemoryAttention(nn.Module):
64
+ def __init__(
65
+ self,
66
+ config: LightpostConfig,
67
+ ):
68
+ super(MemoryAttention, self).__init__()
69
+ self.embed_dim = config.hidden_size
70
+ self.memory_size = config.mem_size
71
+ self.dropout = config.attention_dropout
72
+ self.scaling = self.embed_dim ** -0.5
73
+
74
+ self.num_heads = config.num_attention_heads
75
+
76
+ self.attn_dropout = nn.Dropout(self.dropout)
77
+
78
+ # Define a learnable memory for the value vectors
79
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
80
+ self.keys = nn.Parameter(0.01 * torch.randn(self.memory_size, self.embed_dim))
81
+ self.learnable_memory = nn.Parameter(0.01 * torch.randn(self.memory_size, self.embed_dim))
82
+
83
+ @staticmethod
84
+ def from_state_dict(state_dict, config):
85
+ """
86
+ Instantiate a MemoryAttention object from a state dictionary.
87
+
88
+ Args:
89
+ state_dict (dict): The state dictionary containing the model parameters.
90
+ config (object): Configuration object with attributes like hidden_size and num_attention_heads.
91
+
92
+ Returns:
93
+ MemoryAttention: An instance of the MemoryAttention class.
94
+ """
95
+ learnable_memory_size = state_dict["learnable_memory"].shape[0]
96
+ config.mem_size = learnable_memory_size
97
+ mem_attn = MemoryAttention(
98
+ config=config,
99
+ )
100
+ mem_attn.load_state_dict(state_dict)
101
+ return mem_attn
102
+
103
+ def forward(
104
+ self,
105
+ inputs,
106
+ ):
107
+ # Assume queries are in (batch, seq, embed) format
108
+ queries = self.q_proj(inputs)
109
+
110
+ # Calculate attention to each key in memory
111
+ attn_weights = torch.matmul(queries, self.keys.transpose(0,1)) * self.scaling # (batch, seq, memory_size)
112
+
113
+ # Apply softmax
114
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(queries.dtype) # (batch, seq, memory_size)
115
+ attn_weights = self.attn_dropout(attn_weights) # (batch, seq, memory_size)
116
+
117
+ # Compute attention output
118
+ attn_output = torch.matmul(attn_weights, self.learnable_memory) # (batch, seq, embed_dim)
119
+
120
+ return attn_output
121
+
122
+
123
+
124
+
125
+ def forward_mh(self, queries):
126
+ """
127
+ Args:
128
+ queries: Tensor of shape (batch_size, seq_length, embed_dim)
129
+
130
+ Returns:
131
+ attn_output: Tensor of shape (batch_size, seq_length, embed_dim)
132
+ """
133
+ bsz, q_len, _ = queries.shape
134
+
135
+ # Reshape queries for multi-head attention
136
+ # From (bsz, q_len, embed_dim) to (bsz, num_heads, q_len, head_dim)
137
+ queries = queries.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) # (bsz, num_heads, q_len, head_dim)
138
+
139
+ # Project keys
140
+ # From (memory_size, embed_dim) to (num_heads, memory_size, head_dim)
141
+ keys = self.k_proj(self.learnable_memory) # (memory_size, embed_dim)
142
+ keys = keys.view(self.memory_size, self.num_heads, self.head_dim).transpose(0, 1) # (num_heads, memory_size, head_dim)
143
+
144
+ # Compute attention weights
145
+ # queries: (bsz, num_heads, q_len, head_dim)
146
+ # keys: (num_heads, memory_size, head_dim)
147
+ # We need to perform matrix multiplication for each head separately
148
+ # Resulting attn_weights shape: (bsz, num_heads, q_len, memory_size)
149
+
150
+ # Expand keys to (1, num_heads, head_dim, memory_size) for broadcasting
151
+ keys = keys.unsqueeze(0).transpose(-2, -1) # (1, num_heads, head_dim, memory_size)
152
+
153
+ # Perform batched matrix multiplication
154
+ attn_weights = torch.matmul(queries, keys) # (bsz, num_heads, q_len, memory_size)
155
+
156
+ # Apply scaling factor
157
+ attn_weights = attn_weights * self.scaling
158
+
159
+ # Apply softmax
160
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1) # (bsz, num_heads, q_len, memory_size)
161
+ attn_weights = self.attn_dropout(attn_weights)
162
+
163
+ # Compute attention output
164
+ # learnable_memory: (memory_size, embed_dim) -> (num_heads, memory_size, head_dim)
165
+ memory = self.learnable_memory.view(self.memory_size, self.num_heads, self.head_dim).transpose(0, 1) # (num_heads, memory_size, head_dim)
166
+
167
+ # Expand memory for batched matrix multiplication
168
+ # memory: (num_heads, memory_size, head_dim) -> (1, num_heads, memory_size, head_dim)
169
+ memory = memory.unsqueeze(0) # (1, num_heads, memory_size, head_dim)
170
+
171
+ # Compute attention output
172
+ # attn_weights: (bsz, num_heads, q_len, memory_size)
173
+ # memory: (1, num_heads, memory_size, head_dim)
174
+ # Resulting attn_output: (bsz, num_heads, q_len, head_dim)
175
+ attn_output = torch.matmul(attn_weights, memory) # (bsz, num_heads, q_len, head_dim)
176
+
177
+ # Concatenate heads and reshape to (bsz, q_len, embed_dim)
178
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, self.embed_dim) # (bsz, q_len, embed_dim)
179
+
180
+ return attn_output
181
+
182
+
183
+
184
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Lightpost
185
+ class LightpostRMSNorm(nn.Module):
186
+ def __init__(self, hidden_size, eps=1e-6):
187
+ """
188
+ LightpostRMSNorm is equivalent to T5LayerNorm
189
+ """
190
+ super().__init__()
191
+ self.weight = nn.Parameter(torch.ones(hidden_size))
192
+ self.variance_epsilon = eps
193
+
194
+ def forward(self, hidden_states):
195
+ input_dtype = hidden_states.dtype
196
+ hidden_states = hidden_states.to(torch.float32)
197
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
198
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
199
+ return self.weight * hidden_states.to(input_dtype)
200
+
201
+ def extra_repr(self):
202
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
203
+
204
+
205
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Lightpost
206
+ class LightpostRotaryEmbedding(nn.Module):
207
+ def __init__(
208
+ self,
209
+ config: LightpostConfig,
210
+ device=None,
211
+ ):
212
+ super().__init__()
213
+
214
+ # Use the config object directly
215
+ if config.rope_scaling is not None:
216
+ self.rope_type = config.rope_scaling.get("rope_type", "default")
217
+ else:
218
+ self.rope_type = "default"
219
+
220
+ self.max_seq_len_cached = config.max_position_embeddings
221
+ self.original_max_seq_len = config.max_position_embeddings
222
+
223
+ self.config = config
224
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
225
+
226
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
227
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
228
+ self.original_inv_freq = self.inv_freq
229
+
230
+ def _dynamic_frequency_update(self, position_ids, device):
231
+ """
232
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
233
+ 1 - growing beyond the cached sequence length (allow scaling)
234
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
235
+ """
236
+ seq_len = torch.max(position_ids) + 1
237
+ if seq_len > self.max_seq_len_cached: # growth
238
+ inv_freq, self.attention_scaling = self.rope_init_fn(
239
+ self.config, device, seq_len=seq_len
240
+ )
241
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
242
+ self.max_seq_len_cached = seq_len
243
+
244
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
245
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
246
+ self.max_seq_len_cached = self.original_max_seq_len
247
+
248
+ @torch.no_grad()
249
+ def forward(self, x, position_ids):
250
+ if "dynamic" in self.rope_type:
251
+ self._dynamic_frequency_update(position_ids, device=x.device)
252
+
253
+ # Core RoPE block
254
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
255
+ position_ids_expanded = position_ids[:, None, :].float()
256
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
257
+ device_type = x.device.type
258
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
259
+ with torch.autocast(device_type=device_type, enabled=False):
260
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
261
+ emb = torch.cat((freqs, freqs), dim=-1)
262
+ cos = emb.cos()
263
+ sin = emb.sin()
264
+
265
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
266
+ cos = cos * self.attention_scaling
267
+ sin = sin * self.attention_scaling
268
+
269
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
270
+
271
+
272
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
273
+ def rotate_half(x):
274
+ """Rotates half the hidden dims of the input."""
275
+ x1 = x[..., : x.shape[-1] // 2]
276
+ x2 = x[..., x.shape[-1] // 2 :]
277
+ return torch.cat((-x2, x1), dim=-1)
278
+
279
+
280
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
281
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
282
+ """Applies Rotary Position Embedding to the query and key tensors.
283
+
284
+ Args:
285
+ q (`torch.Tensor`): The query tensor.
286
+ k (`torch.Tensor`): The key tensor.
287
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
288
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
289
+ position_ids (`torch.Tensor`, *optional*):
290
+ Deprecated and unused.
291
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
292
+ The dimension along which to unsqueeze the rotary position embeddings (cos and sin) for proper broadcasting.
293
+ If q and k have shape [batch_size, heads, seq_len, head_dim], use unsqueeze_dim=1 to insert a dimension
294
+ after batch_size. If q and k have shape [batch_size, seq_len, heads, head_dim], use unsqueeze_dim=2 to
295
+ insert a dimension after seq_len. This ensures the rotary embeddings can be properly broadcast to match
296
+ the query and key tensor shapes.
297
+ Returns:
298
+ `tuple(torch.Tensor)` with the query and key tensors rotated using the Rotary Position Embedding.
299
+ """
300
+ cos = cos.unsqueeze(unsqueeze_dim)
301
+ sin = sin.unsqueeze(unsqueeze_dim)
302
+ q_embed = (q * cos) + (rotate_half(q) * sin)
303
+ k_embed = (k * cos) + (rotate_half(k) * sin)
304
+ return q_embed, k_embed
305
+
306
+
307
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Lightpost
308
+ class LightpostMLP(nn.Module):
309
+ def __init__(self, config):
310
+ super().__init__()
311
+ self.hidden_size = config.hidden_size
312
+ self.intermediate_size = config.intermediate_size
313
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
314
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
315
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
316
+ self.act_fn = ACT2FN[config.hidden_act]
317
+
318
+ def forward(self, hidden_state):
319
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
320
+
321
+
322
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
323
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
324
+ """
325
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
326
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
327
+ """
328
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
329
+ if n_rep == 1:
330
+ return hidden_states
331
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
332
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
333
+
334
+
335
+ class LightpostAttention(nn.Module):
336
+ """
337
+ Multi-headed attention from 'Attention Is All You Need' paper. For long sequences, this implementation uses
338
+ sliding window attention similar to Longformer and Sparse Transformers, where each token attends to a local window of
339
+ surrounding tokens rather than the full sequence. This allows for efficient processing of very long sequences while
340
+ maintaining the key benefits of self-attention within each window.
341
+ """
342
+
343
+ def __init__(self, config: LightpostConfig, layer_idx: int):
344
+ super().__init__()
345
+ self.config = config
346
+ self.layer_idx = layer_idx
347
+
348
+ self.hidden_size = config.hidden_size
349
+ self.num_heads = config.num_attention_heads
350
+ self.head_dim = self.hidden_size // self.num_heads
351
+ self.num_key_value_heads = config.num_key_value_heads
352
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
353
+ self.max_position_embeddings = config.max_position_embeddings
354
+ self.rope_theta = config.rope_theta
355
+ self.is_causal = True
356
+ self.attention_dropout = config.attention_dropout
357
+
358
+ if (self.head_dim * self.num_heads) != self.hidden_size:
359
+ raise ValueError(
360
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
361
+ f" and `num_heads`: {self.num_heads})."
362
+ )
363
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
364
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
365
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
366
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
367
+
368
+
369
+ if self.config.mem_layers is not None and self.layer_idx in self.config.mem_layers:
370
+ self.mem_attn = MemoryAttention(config=self.config)
371
+ else:
372
+ self.mem_attn = None
373
+
374
+ self.rotary_emb = LightpostRotaryEmbedding(config=self.config)
375
+
376
+ def forward(
377
+ self,
378
+ hidden_states: torch.Tensor,
379
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]],
380
+ attention_mask: Optional[torch.Tensor] = None,
381
+ position_ids: Optional[torch.LongTensor] = None,
382
+ past_key_value: Optional[Cache] = None,
383
+ output_attentions: bool = False,
384
+ use_cache: bool = False,
385
+ cache_position: Optional[torch.LongTensor] = None,
386
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
387
+ bsz, q_len, _ = hidden_states.size()
388
+
389
+ query_states = self.q_proj(hidden_states)
390
+ key_states = self.k_proj(hidden_states)
391
+ value_states = self.v_proj(hidden_states)
392
+
393
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
394
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
395
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
396
+
397
+ cos, sin = position_embeddings
398
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
399
+
400
+ if past_key_value is not None:
401
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
402
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
403
+
404
+ # repeat k/v heads if n_kv_heads < n_heads
405
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
406
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
407
+
408
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
409
+ if attention_mask is not None: # no matter the length, we just slice it
410
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
411
+ attn_weights = attn_weights + causal_mask
412
+
413
+ # upcast attention to fp32
414
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
415
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
416
+ attn_output = torch.matmul(attn_weights, value_states)
417
+
418
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
419
+ raise ValueError(
420
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
421
+ f" {attn_output.size()}"
422
+ )
423
+
424
+ attn_output = attn_output.transpose(1, 2).contiguous()
425
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
426
+
427
+ attn_output = self.o_proj(attn_output)
428
+
429
+ if not output_attentions:
430
+ attn_weights = None
431
+
432
+ return attn_output, attn_weights, past_key_value
433
+
434
+
435
+ class LightpostFlashAttention2(LightpostAttention):
436
+ """
437
+ Lightpost flash attention module that inherits from `LightpostAttention`. The weights remain identical to the base class,
438
+ with modifications only to the forward pass to properly integrate with flash attention's API and handle padding tokens.
439
+ For sliding window attention (SWA), it is applied only to the bottom config.max_window_layers layers of the model.
440
+ """
441
+
442
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
443
+ def __init__(self, *args, **kwargs):
444
+ super().__init__(*args, **kwargs)
445
+
446
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
447
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
448
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
449
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
450
+
451
+ def forward(
452
+ self,
453
+ hidden_states: torch.Tensor,
454
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]],
455
+ attention_mask: Optional[torch.Tensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_value: Optional[Cache] = None,
458
+ output_attentions: bool = False,
459
+ use_cache: bool = False,
460
+ cache_position: Optional[torch.LongTensor] = None,
461
+ ):
462
+ bsz, q_len, _ = hidden_states.size()
463
+
464
+ query_states = self.q_proj(hidden_states)
465
+ key_states = self.k_proj(hidden_states)
466
+ value_states = self.v_proj(hidden_states)
467
+
468
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
469
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
470
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
471
+
472
+ cos, sin = position_embeddings
473
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
474
+
475
+ if past_key_value is not None:
476
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
477
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
478
+
479
+ # repeat k/v heads if n_kv_heads < n_heads
480
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
481
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
482
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
483
+
484
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
485
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
486
+ # cast them back in float16 just to be sure everything works as expected.
487
+ input_dtype = query_states.dtype
488
+ if input_dtype == torch.float32:
489
+ if torch.is_autocast_enabled():
490
+ target_dtype = torch.get_autocast_gpu_dtype()
491
+ # Handle the case where the model is quantized
492
+ elif hasattr(self.config, "_pre_quantization_dtype"):
493
+ target_dtype = self.config._pre_quantization_dtype
494
+ else:
495
+ target_dtype = self.q_proj.weight.dtype
496
+
497
+ logger.warning_once(
498
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
499
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
500
+ f" {target_dtype}."
501
+ )
502
+
503
+ query_states = query_states.to(target_dtype)
504
+ key_states = key_states.to(target_dtype)
505
+ value_states = value_states.to(target_dtype)
506
+
507
+ # Reashape to the expected shape for Flash Attention
508
+ query_states = query_states.transpose(1, 2)
509
+ key_states = key_states.transpose(1, 2)
510
+ value_states = value_states.transpose(1, 2)
511
+
512
+ if (
513
+ self.config.use_sliding_window
514
+ and getattr(self.config, "sliding_window", None) is not None
515
+ and self.layer_idx >= self.config.max_window_layers
516
+ ):
517
+ sliding_window = self.config.sliding_window
518
+ else:
519
+ sliding_window = None
520
+
521
+ attn_output = _flash_attention_forward(
522
+ query_states,
523
+ key_states,
524
+ value_states,
525
+ attention_mask,
526
+ q_len,
527
+ position_ids=position_ids,
528
+ dropout=dropout_rate,
529
+ sliding_window=sliding_window,
530
+ is_causal=self.is_causal,
531
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
532
+ )
533
+
534
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
535
+ attn_output = self.o_proj(attn_output)
536
+
537
+ if not output_attentions:
538
+ attn_weights = None
539
+
540
+ return attn_output, attn_weights, past_key_value
541
+
542
+
543
+ class LightpostSdpaAttention(LightpostAttention):
544
+ """
545
+ This module implements Lightpost attention using PyTorch's scaled dot-product attention (SDPA) functionality. It extends
546
+ the base `LightpostAttention` class, preserving all weights and parameters. The only modification is in the forward
547
+ pass implementation to leverage the optimized SDPA interface.
548
+ """
549
+
550
+ # Adapted from LightpostAttention.forward
551
+ def forward(
552
+ self,
553
+ hidden_states: torch.Tensor,
554
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]],
555
+ attention_mask: Optional[torch.Tensor] = None,
556
+ position_ids: Optional[torch.LongTensor] = None,
557
+ past_key_value: Optional[Cache] = None,
558
+ output_attentions: bool = False,
559
+ use_cache: bool = False,
560
+ cache_position: Optional[torch.LongTensor] = None,
561
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
562
+ if output_attentions:
563
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
564
+ logger.warning_once(
565
+ "LightpostModel is using LightpostSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
566
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
567
+ )
568
+ return super().forward(
569
+ hidden_states=hidden_states,
570
+ attention_mask=attention_mask,
571
+ position_ids=position_ids,
572
+ past_key_value=past_key_value,
573
+ output_attentions=output_attentions,
574
+ use_cache=use_cache,
575
+ )
576
+
577
+ bsz, q_len, _ = hidden_states.size()
578
+
579
+ query_states = self.q_proj(hidden_states)
580
+ key_states = self.k_proj(hidden_states)
581
+ value_states = self.v_proj(hidden_states)
582
+
583
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
584
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
585
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
586
+
587
+ cos, sin = position_embeddings
588
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
589
+
590
+ if past_key_value is not None:
591
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
592
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
593
+
594
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
595
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
596
+
597
+ causal_mask = attention_mask
598
+ if attention_mask is not None: # no matter the length, we just slice it
599
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
600
+
601
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
602
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
603
+ if query_states.device.type == "cuda" and attention_mask is not None:
604
+ query_states = query_states.contiguous()
605
+ key_states = key_states.contiguous()
606
+ value_states = value_states.contiguous()
607
+
608
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
609
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
610
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
611
+ is_causal = True if causal_mask is None and q_len > 1 else False
612
+
613
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ attn_mask=causal_mask,
618
+ dropout_p=self.attention_dropout if self.training else 0.0,
619
+ is_causal=is_causal,
620
+ )
621
+
622
+ attn_output = attn_output.transpose(1, 2).contiguous()
623
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
624
+
625
+ if self.mem_attn:
626
+ attn_output = attn_output +self.mem_attn(hidden_states)
627
+
628
+ attn_output = self.o_proj(attn_output)
629
+
630
+
631
+ return attn_output, None, past_key_value
632
+
633
+
634
+ LIGHTPOST_ATTENTION_CLASSES = {
635
+ "eager": LightpostAttention,
636
+ "flash_attention_2": LightpostFlashAttention2,
637
+ "sdpa": LightpostSdpaAttention,
638
+ }
639
+
640
+ # Adapted from QWEN2DecoderLayer
641
+ class LightpostDecoderLayer(nn.Module):
642
+ def __init__(self, config: LightpostConfig, layer_idx: int):
643
+ super().__init__()
644
+ self.hidden_size = config.hidden_size
645
+
646
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
647
+ logger.warning_once(
648
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
649
+ "unexpected results may be encountered."
650
+ )
651
+ self.self_attn = LIGHTPOST_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
652
+
653
+
654
+ self.mlp = LightpostMLP(config)
655
+ self.input_layernorm = LightpostRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
656
+ self.post_attention_layernorm = LightpostRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
657
+
658
+ def forward(
659
+ self,
660
+ hidden_states: torch.Tensor,
661
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]],
662
+ attention_mask: Optional[torch.Tensor] = None,
663
+ position_ids: Optional[torch.LongTensor] = None,
664
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
665
+ output_attentions: Optional[bool] = False,
666
+ use_cache: Optional[bool] = False,
667
+ cache_position: Optional[torch.LongTensor] = None,
668
+ **kwargs,
669
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
670
+ """
671
+ Args:
672
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
673
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`):
674
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
675
+ with `head_dim` being the embedding dimension of each attention head.
676
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
677
+ `(batch, sequence_length)` where padding elements are indicated by 0.
678
+ output_attentions (`bool`, *optional*):
679
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
680
+ returned tensors for more detail.
681
+ use_cache (`bool`, *optional*):
682
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
683
+ (see `past_key_values`).
684
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
685
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
686
+ Indices depicting the position of the input sequence tokens in the sequence.
687
+ kwargs (`dict`, *optional*):
688
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
689
+ into the model
690
+ """
691
+
692
+ residual = hidden_states
693
+
694
+ hidden_states = self.input_layernorm(hidden_states)
695
+
696
+ # Self Attention
697
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
698
+ hidden_states=hidden_states,
699
+ position_embeddings=position_embeddings,
700
+ attention_mask=attention_mask,
701
+ position_ids=position_ids,
702
+ past_key_value=past_key_value,
703
+ output_attentions=output_attentions,
704
+ use_cache=use_cache,
705
+ cache_position=cache_position,
706
+ )
707
+
708
+ hidden_states = residual + hidden_states
709
+
710
+ # Fully Connected
711
+ residual = hidden_states
712
+ hidden_states = self.post_attention_layernorm(hidden_states)
713
+ hidden_states = self.mlp(hidden_states)
714
+ hidden_states = residual + hidden_states
715
+
716
+ outputs = (hidden_states,)
717
+
718
+ if output_attentions:
719
+ outputs += (self_attn_weights,)
720
+
721
+ if use_cache:
722
+ outputs += (present_key_value,)
723
+
724
+ return outputs
725
+
726
+
727
+ LIGHTPOST_START_DOCSTRING = r"""
728
+ This model extends [`PreTrainedModel`] and provides access to common functionality like model downloading, saving,
729
+ input embedding resizing, and head pruning. See the parent class documentation for details on these methods.
730
+
731
+ As a standard PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module), this model can be
732
+ used like any other PyTorch module. Refer to PyTorch's documentation for general usage patterns and behaviors.
733
+
734
+ Parameters:
735
+ config ([`LightpostConfig`]):
736
+ Configuration object containing model parameters. Note that initializing with a config only sets up the model
737
+ architecture - to load pretrained weights, use [`~PreTrainedModel.from_pretrained`].
738
+ """
739
+
740
+
741
+ @add_start_docstrings(
742
+ """
743
+ The base Lightpost Model that outputs raw hidden states from the transformer layers,
744
+ without any task-specific head (like language modeling or classification) on top.
745
+ This provides the core transformer functionality that task-specific models can build upon.
746
+ """,
747
+ LIGHTPOST_START_DOCSTRING,
748
+ )
749
+ class LightpostPreTrainedModel(PreTrainedModel):
750
+ config_class = LightpostConfig
751
+ base_model_prefix = "model"
752
+ supports_gradient_checkpointing = True
753
+ _no_split_modules = ["LightpostDecoderLayer"]
754
+ _skip_keys_device_placement = "past_key_values"
755
+ _supports_flash_attn_2 = True
756
+ _supports_sdpa = True
757
+ _supports_cache_class = True
758
+ _supports_quantized_cache = True
759
+ _supports_static_cache = True
760
+
761
+ def _init_weights(self, module):
762
+ std = self.config.initializer_range
763
+ if isinstance(module, nn.Linear):
764
+ module.weight.data.normal_(mean=0.0, std=std)
765
+ if module.bias is not None:
766
+ module.bias.data.zero_()
767
+ elif isinstance(module, nn.Embedding):
768
+ module.weight.data.normal_(mean=0.0, std=std)
769
+ if module.padding_idx is not None:
770
+ module.weight.data[module.padding_idx].zero_()
771
+
772
+
773
+ LIGHTPOST_INPUTS_DOCSTRING = r"""
774
+ Args:
775
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
776
+ Input token IDs. These are indices into the model's vocabulary. Padding tokens will be ignored.
777
+ Can be obtained using a tokenizer from the `AutoTokenizer` class.
778
+
779
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
780
+ Attention mask to avoid attending to padding tokens:
781
+ - 1 for tokens to attend to
782
+ - 0 for tokens to ignore
783
+ See the model's `_prepare_decoder_attention_mask` method for implementation details.
784
+
785
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
786
+ Position indices for input tokens, ranging from 0 to config.n_positions - 1.
787
+ Used for positional embeddings.
788
+
789
+ past_key_values (`Cache`, *optional*):
790
+ Cached key/value states from previous forward passes to speed up sequential decoding.
791
+ Must be a `Cache` instance (see [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)).
792
+ When using cached states, only the new tokens need to be provided in input_ids.
793
+
794
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
795
+ Pre-computed input embeddings. Alternative to passing input_ids.
796
+ Useful for more control over token embedding process.
797
+
798
+ use_cache (`bool`, *optional*):
799
+ Whether to return key/value states for use in subsequent forward passes.
800
+
801
+ output_attentions (`bool`, *optional*):
802
+ Whether to return attention weights from all layers.
803
+
804
+ output_hidden_states (`bool`, *optional*):
805
+ Whether to return hidden states from all layers.
806
+
807
+ return_dict (`bool`, *optional*):
808
+ Whether to return a ModelOutput object instead of a tuple.
809
+
810
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
811
+ Indices showing true sequence position of input tokens, ignoring padding.
812
+ Used for cache position tracking and inference.
813
+ """
814
+
815
+
816
+ @add_start_docstrings(
817
+ "The bare Lightpost Model outputting raw hidden-states without any specific head on top.",
818
+ LIGHTPOST_START_DOCSTRING,
819
+ )
820
+ class LightpostModel(LightpostPreTrainedModel):
821
+ """
822
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LightpostDecoderLayer`]
823
+
824
+ Args:
825
+ config: LightpostConfig
826
+ """
827
+
828
+ def __init__(self, config: LightpostConfig):
829
+ super().__init__(config)
830
+ self.padding_idx = config.pad_token_id
831
+ self.vocab_size = config.vocab_size
832
+
833
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
834
+ self.layers = nn.ModuleList(
835
+ [LightpostDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
836
+ )
837
+ self._attn_implementation = config._attn_implementation
838
+ self.norm = LightpostRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
839
+ self.rotary_emb = LightpostRotaryEmbedding(config=config)
840
+
841
+ self.gradient_checkpointing = False
842
+ # Initialize weights and apply final processing
843
+ self.post_init()
844
+
845
+
846
+ def set_mem(self, memory_size: int, mem_layers: None | int | list[int] = None):
847
+ if mem_layers is None:
848
+ mem_layers = list(range(len(self.layers)))
849
+ elif isinstance(mem_layers, int):
850
+ mem_layers = [mem_layers]
851
+
852
+ mem_layers = list(mem_layers)
853
+
854
+ print(f"Setting memory size to {memory_size} for layers {mem_layers}")
855
+ self.config.mem_size = memory_size
856
+ self.config.mem_layers = mem_layers
857
+
858
+ for ix, layer in enumerate(self.layers):
859
+ if ix in mem_layers:
860
+ if memory_size == 0 or memory_size is None:
861
+ layer.self_attn.mem_attn = None
862
+ elif hasattr(layer.self_attn, 'mem_attn'):
863
+ device = next(layer.parameters()).device
864
+ dtype = next(layer.parameters()).dtype
865
+ layer.self_attn.mem_attn = MemoryAttention(config=self.config).to(device, dtype=dtype)
866
+ else:
867
+ if hasattr(layer.self_attn, 'mem_attn'):
868
+ delattr(layer.self_attn, 'mem_attn')
869
+
870
+ def save_mem(self, path: str):
871
+ data = {"version": 1, "layers": {}}
872
+ for ix, layer in enumerate(self.layers):
873
+ if hasattr(layer.self_attn, 'mem_attn') and layer.self_attn.mem_attn is not None:
874
+ data["layers"][ix] = layer.self_attn.mem_attn.state_dict()
875
+
876
+ torch.save(data, path)
877
+
878
+ def load_mem(self, path: str):
879
+ data = torch.load(path, weights_only=True)
880
+
881
+ if data['version'] != 1:
882
+ raise ValueError(f"Unsupported version: {data['version']}")
883
+
884
+ for ix, state_dict in data["layers"].items():
885
+
886
+ if not hasattr(self.layers[ix], 'self_attn'):
887
+ raise ValueError(f"MemoryAttention module not found in layer {ix}")
888
+
889
+ device = next(self.layers[ix].parameters()).device
890
+ self.layers[ix].self_attn.mem_attn = MemoryAttention.from_state_dict(state_dict, self.config).to(device)
891
+
892
+ # Ensure that the config is updated with the correct memory size
893
+ self.config.mem_layers = list(data["layers"].keys())
894
+ self.config.mem_size = self.layers[self.config.mem_layers[0]].self_attn.mem_attn.memory_size
895
+
896
+
897
+ def get_input_embeddings(self):
898
+ return self.embed_tokens
899
+
900
+ def set_input_embeddings(self, value):
901
+ self.embed_tokens = value
902
+
903
+ @add_start_docstrings_to_model_forward(LIGHTPOST_INPUTS_DOCSTRING)
904
+ def forward(
905
+ self,
906
+ input_ids: torch.LongTensor = None,
907
+ attention_mask: Optional[torch.Tensor] = None,
908
+ position_ids: Optional[torch.LongTensor] = None,
909
+ past_key_values: Optional[Cache] = None,
910
+ inputs_embeds: Optional[torch.FloatTensor] = None,
911
+ use_cache: Optional[bool] = None,
912
+ output_attentions: Optional[bool] = None,
913
+ output_hidden_states: Optional[bool] = None,
914
+ return_dict: Optional[bool] = None,
915
+ cache_position: Optional[torch.LongTensor] = None,
916
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
917
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
918
+ output_hidden_states = (
919
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
920
+ )
921
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
922
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
923
+
924
+ if (input_ids is None) ^ (inputs_embeds is not None):
925
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
926
+
927
+ if self.gradient_checkpointing and self.training:
928
+ if use_cache:
929
+ logger.warning_once(
930
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
931
+ )
932
+ use_cache = False
933
+
934
+ # Ensure `past_key_values` is a `Cache` instance
935
+ if use_cache and past_key_values is None:
936
+ past_key_values = DynamicCache()
937
+
938
+ if inputs_embeds is None:
939
+ inputs_embeds = self.embed_tokens(input_ids)
940
+
941
+ if cache_position is None:
942
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
943
+ cache_position = torch.arange(
944
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
945
+ )
946
+ if position_ids is None:
947
+ position_ids = cache_position.unsqueeze(0)
948
+
949
+ causal_mask = self._update_causal_mask(
950
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
951
+ )
952
+
953
+ hidden_states = inputs_embeds
954
+
955
+ # create position embeddings to be shared across the decoder layers
956
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
957
+
958
+ # decoder layers
959
+ all_hidden_states = () if output_hidden_states else None
960
+ all_self_attns = () if output_attentions else None
961
+ next_decoder_cache = None
962
+
963
+ for decoder_layer in self.layers:
964
+ if output_hidden_states:
965
+ all_hidden_states += (hidden_states,)
966
+
967
+ if self.gradient_checkpointing and self.training:
968
+ layer_outputs = self._gradient_checkpointing_func(
969
+ decoder_layer.__call__,
970
+ hidden_states,
971
+ causal_mask,
972
+ position_ids,
973
+ past_key_values,
974
+ output_attentions,
975
+ use_cache,
976
+ cache_position,
977
+ position_embeddings,
978
+ )
979
+ else:
980
+ layer_outputs = decoder_layer(
981
+ hidden_states,
982
+ position_embeddings=position_embeddings,
983
+ attention_mask=causal_mask,
984
+ position_ids=position_ids,
985
+ past_key_value=past_key_values,
986
+ output_attentions=output_attentions,
987
+ use_cache=use_cache,
988
+ cache_position=cache_position
989
+ )
990
+
991
+ hidden_states = layer_outputs[0]
992
+
993
+ if use_cache:
994
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
995
+
996
+ if output_attentions:
997
+ all_self_attns += (layer_outputs[1],)
998
+
999
+ hidden_states = self.norm(hidden_states)
1000
+
1001
+ # add hidden states from the last decoder layer
1002
+ if output_hidden_states:
1003
+ all_hidden_states += (hidden_states,)
1004
+
1005
+ next_cache = next_decoder_cache if use_cache else None
1006
+
1007
+ if not return_dict:
1008
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1009
+ return BaseModelOutputWithPast(
1010
+ last_hidden_state=hidden_states,
1011
+ past_key_values=next_cache,
1012
+ hidden_states=all_hidden_states,
1013
+ attentions=all_self_attns,
1014
+ )
1015
+
1016
+ # Copied from transformers.models.phi3.modeling_phi3.Phi3Model._update_causal_mask
1017
+ def _update_causal_mask(
1018
+ self,
1019
+ attention_mask: torch.Tensor,
1020
+ input_tensor: torch.Tensor,
1021
+ cache_position: torch.Tensor,
1022
+ past_key_values: Cache,
1023
+ output_attentions: bool,
1024
+ ):
1025
+ if self.config._attn_implementation == "flash_attention_2":
1026
+ if attention_mask is not None and 0.0 in attention_mask:
1027
+ return attention_mask
1028
+ return None
1029
+
1030
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1031
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1032
+ # to infer the attention mask.
1033
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1034
+ using_static_cache = isinstance(past_key_values, StaticCache)
1035
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1036
+
1037
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1038
+ if (
1039
+ self.config._attn_implementation == "sdpa"
1040
+ and not (using_static_cache or using_sliding_window_cache)
1041
+ and not output_attentions
1042
+ ):
1043
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1044
+ attention_mask,
1045
+ inputs_embeds=input_tensor,
1046
+ past_key_values_length=past_seen_tokens,
1047
+ sliding_window=self.config.sliding_window,
1048
+ is_training=self.training,
1049
+ ):
1050
+ return None
1051
+
1052
+ dtype, device = input_tensor.dtype, input_tensor.device
1053
+ min_dtype = torch.finfo(dtype).min
1054
+ sequence_length = input_tensor.shape[1]
1055
+ # SlidingWindowCache or StaticCache
1056
+ if using_sliding_window_cache or using_static_cache:
1057
+ target_length = past_key_values.get_max_cache_shape()
1058
+ # DynamicCache or no cache
1059
+ else:
1060
+ target_length = (
1061
+ attention_mask.shape[-1]
1062
+ if isinstance(attention_mask, torch.Tensor)
1063
+ else past_seen_tokens + sequence_length + 1
1064
+ )
1065
+
1066
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1067
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1068
+ attention_mask,
1069
+ sequence_length=sequence_length,
1070
+ target_length=target_length,
1071
+ dtype=dtype,
1072
+ device=device,
1073
+ cache_position=cache_position,
1074
+ batch_size=input_tensor.shape[0],
1075
+ config=self.config,
1076
+ past_key_values=past_key_values,
1077
+ )
1078
+
1079
+ if (
1080
+ self.config._attn_implementation == "sdpa"
1081
+ and attention_mask is not None
1082
+ and attention_mask.device.type == "cuda"
1083
+ and not output_attentions
1084
+ ):
1085
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1086
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1087
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1088
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1089
+
1090
+ return causal_mask
1091
+
1092
+ @staticmethod
1093
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel._prepare_4d_causal_attention_mask_with_cache_position with Mistral->Lightpost
1094
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1095
+ attention_mask: torch.Tensor,
1096
+ sequence_length: int,
1097
+ target_length: int,
1098
+ dtype: torch.dtype,
1099
+ device: torch.device,
1100
+ cache_position: torch.Tensor,
1101
+ batch_size: int,
1102
+ config: LightpostConfig,
1103
+ past_key_values: Cache,
1104
+ ):
1105
+ """
1106
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1107
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1108
+
1109
+ Args:
1110
+ attention_mask (`torch.Tensor`):
1111
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1112
+ sequence_length (`int`):
1113
+ The sequence length being processed.
1114
+ target_length (`int`):
1115
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1116
+ dtype (`torch.dtype`):
1117
+ The dtype to use for the 4D attention mask.
1118
+ device (`torch.device`):
1119
+ The device to plcae the 4D attention mask on.
1120
+ cache_position (`torch.Tensor`):
1121
+ Indices depicting the position of the input sequence tokens in the sequence.
1122
+ batch_size (`torch.Tensor`):
1123
+ Batch size.
1124
+ config (`LightpostConfig`):
1125
+ The model's configuration class
1126
+ past_key_values (`Cache`):
1127
+ The cache class that is being used currently to generate
1128
+ """
1129
+ if attention_mask is not None and attention_mask.dim() == 4:
1130
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1131
+ causal_mask = attention_mask
1132
+ else:
1133
+ min_dtype = torch.finfo(dtype).min
1134
+ causal_mask = torch.full(
1135
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1136
+ )
1137
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1138
+ if config.sliding_window is not None:
1139
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1140
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1141
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1142
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1143
+ cache_position.reshape(-1, 1) - config.sliding_window
1144
+ )
1145
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1146
+ causal_mask *= diagonal_attend_mask
1147
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1148
+ if attention_mask is not None:
1149
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1150
+ if attention_mask.shape[-1] > target_length:
1151
+ attention_mask = attention_mask[:, :target_length]
1152
+ mask_length = attention_mask.shape[-1]
1153
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1154
+ padding_mask = padding_mask == 0
1155
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1156
+ padding_mask, min_dtype
1157
+ )
1158
+ return causal_mask
1159
+
1160
+
1161
+ class LightpostForCausalLM(LightpostPreTrainedModel, GenerationMixin):
1162
+ _tied_weights_keys = ["lm_head.weight"]
1163
+
1164
+ def __init__(self, config):
1165
+ super().__init__(config)
1166
+ self.model = LightpostModel(config)
1167
+ self.vocab_size = config.vocab_size
1168
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1169
+
1170
+ # Initialize weights and apply final processing
1171
+ self.post_init()
1172
+
1173
+ def get_input_embeddings(self):
1174
+ return self.model.embed_tokens
1175
+
1176
+ def set_input_embeddings(self, value):
1177
+ self.model.embed_tokens = value
1178
+
1179
+ def get_output_embeddings(self):
1180
+ return self.lm_head
1181
+
1182
+ def set_output_embeddings(self, new_embeddings):
1183
+ self.lm_head = new_embeddings
1184
+
1185
+ def set_decoder(self, decoder):
1186
+ self.model = decoder
1187
+
1188
+ def get_decoder(self):
1189
+ return self.model
1190
+
1191
+ @add_start_docstrings_to_model_forward(LIGHTPOST_INPUTS_DOCSTRING)
1192
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1193
+ def forward(
1194
+ self,
1195
+ input_ids: torch.LongTensor = None,
1196
+ attention_mask: Optional[torch.Tensor] = None,
1197
+ position_ids: Optional[torch.LongTensor] = None,
1198
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1199
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1200
+ labels: Optional[torch.LongTensor] = None,
1201
+ use_cache: Optional[bool] = None,
1202
+ output_attentions: Optional[bool] = None,
1203
+ output_hidden_states: Optional[bool] = None,
1204
+ return_dict: Optional[bool] = None,
1205
+ cache_position: Optional[torch.LongTensor] = None,
1206
+ num_logits_to_keep: int = 0,
1207
+ **loss_kwargs,
1208
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1209
+ r"""
1210
+ Args:
1211
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1212
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1213
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1214
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1215
+
1216
+ num_logits_to_keep (`int`, *optional*):
1217
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1218
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1219
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1220
+
1221
+ Returns:
1222
+
1223
+ Example:
1224
+
1225
+ ```python
1226
+ >>> from transformers import AutoTokenizer, LightpostForCausalLM
1227
+
1228
+ >>> model = LightpostForCausalLM.from_pretrained(PATH_TO_WEIGHTS)
1229
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_TOKENIZER)
1230
+
1231
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1232
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1233
+
1234
+ >>> # Generate
1235
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1236
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1237
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1238
+ ```"""
1239
+
1240
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1241
+ output_hidden_states = (
1242
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1243
+ )
1244
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1245
+
1246
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1247
+ outputs = self.model(
1248
+ input_ids=input_ids,
1249
+ attention_mask=attention_mask,
1250
+ position_ids=position_ids,
1251
+ past_key_values=past_key_values,
1252
+ inputs_embeds=inputs_embeds,
1253
+ use_cache=use_cache,
1254
+ output_attentions=output_attentions,
1255
+ output_hidden_states=output_hidden_states,
1256
+ return_dict=return_dict,
1257
+ cache_position=cache_position,
1258
+ )
1259
+
1260
+ hidden_states = outputs[0]
1261
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1262
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1263
+
1264
+ loss = None
1265
+ if labels is not None:
1266
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1267
+ self._input_ids = input_ids
1268
+ self._logits = logits
1269
+ self._labels = labels
1270
+ self._attention_mask = attention_mask
1271
+ self._loss_kwargs = loss_kwargs
1272
+ self._num_logits_to_keep = num_logits_to_keep
1273
+
1274
+
1275
+ if not return_dict:
1276
+ output = (logits,) + outputs[1:]
1277
+ return (loss,) + output if loss is not None else output
1278
+
1279
+ return CausalLMOutputWithPast(
1280
+ loss=loss,
1281
+ logits=logits,
1282
+ past_key_values=outputs.past_key_values,
1283
+ hidden_states=outputs.hidden_states,
1284
+ attentions=outputs.attentions,
1285
+ )
1286
+
1287
+
1288
+ @add_start_docstrings(
1289
+ """
1290
+ The Lightpost Model transformer with a sequence classification head on top (linear layer).
1291
+
1292
+ [`LightpostForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1293
+ (e.g. GPT-2) do.
1294
+
1295
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1296
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1297
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1298
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1299
+ each row of the batch).
1300
+ """,
1301
+ LIGHTPOST_START_DOCSTRING,
1302
+ )
1303
+ class LightpostForSequenceClassification(LightpostPreTrainedModel):
1304
+ def __init__(self, config):
1305
+ super().__init__(config)
1306
+ self.num_labels = config.num_labels
1307
+ self.model = LightpostModel(config)
1308
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1309
+
1310
+ # Initialize weights and apply final processing
1311
+ self.post_init()
1312
+
1313
+ def get_input_embeddings(self):
1314
+ return self.model.embed_tokens
1315
+
1316
+ def set_input_embeddings(self, value):
1317
+ self.model.embed_tokens = value
1318
+
1319
+ @add_start_docstrings_to_model_forward(LIGHTPOST_INPUTS_DOCSTRING)
1320
+ def forward(
1321
+ self,
1322
+ input_ids: torch.LongTensor = None,
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ position_ids: Optional[torch.LongTensor] = None,
1325
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1326
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1327
+ labels: Optional[torch.LongTensor] = None,
1328
+ use_cache: Optional[bool] = None,
1329
+ output_attentions: Optional[bool] = None,
1330
+ output_hidden_states: Optional[bool] = None,
1331
+ return_dict: Optional[bool] = None,
1332
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1333
+ r"""
1334
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1335
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1336
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1337
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1338
+ """
1339
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1340
+
1341
+ transformer_outputs = self.model(
1342
+ input_ids,
1343
+ attention_mask=attention_mask,
1344
+ position_ids=position_ids,
1345
+ past_key_values=past_key_values,
1346
+ inputs_embeds=inputs_embeds,
1347
+ use_cache=use_cache,
1348
+ output_attentions=output_attentions,
1349
+ output_hidden_states=output_hidden_states,
1350
+ return_dict=return_dict,
1351
+ )
1352
+ hidden_states = transformer_outputs[0]
1353
+ logits = self.score(hidden_states)
1354
+
1355
+ if input_ids is not None:
1356
+ batch_size = input_ids.shape[0]
1357
+ else:
1358
+ batch_size = inputs_embeds.shape[0]
1359
+
1360
+ if self.config.pad_token_id is None and batch_size != 1:
1361
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1362
+ if self.config.pad_token_id is None:
1363
+ sequence_lengths = -1
1364
+ else:
1365
+ if input_ids is not None:
1366
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1367
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1368
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1369
+ sequence_lengths = sequence_lengths.to(logits.device)
1370
+ else:
1371
+ sequence_lengths = -1
1372
+
1373
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1374
+
1375
+ loss = None
1376
+ if labels is not None:
1377
+ labels = labels.to(logits.device)
1378
+ if self.config.problem_type is None:
1379
+ if self.num_labels == 1:
1380
+ self.config.problem_type = "regression"
1381
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1382
+ self.config.problem_type = "single_label_classification"
1383
+ else:
1384
+ self.config.problem_type = "multi_label_classification"
1385
+
1386
+ if self.config.problem_type == "regression":
1387
+ loss_fct = MSELoss()
1388
+ if self.num_labels == 1:
1389
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1390
+ else:
1391
+ loss = loss_fct(pooled_logits, labels)
1392
+ elif self.config.problem_type == "single_label_classification":
1393
+ loss_fct = CrossEntropyLoss()
1394
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1395
+ elif self.config.problem_type == "multi_label_classification":
1396
+ loss_fct = BCEWithLogitsLoss()
1397
+ loss = loss_fct(pooled_logits, labels)
1398
+ if not return_dict:
1399
+ output = (pooled_logits,) + transformer_outputs[1:]
1400
+ return ((loss,) + output) if loss is not None else output
1401
+
1402
+ return SequenceClassifierOutputWithPast(
1403
+ loss=loss,
1404
+ logits=pooled_logits,
1405
+ past_key_values=transformer_outputs.past_key_values,
1406
+ hidden_states=transformer_outputs.hidden_states,
1407
+ attentions=transformer_outputs.attentions,
1408
+ )
1409
+
1410
+
1411
+ @add_start_docstrings(
1412
+ """
1413
+ The Lightpost Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1414
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1415
+ """,
1416
+ LIGHTPOST_START_DOCSTRING,
1417
+ )
1418
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Lightpost, LLAMA->QWEN2
1419
+ class LightpostForTokenClassification(LightpostPreTrainedModel):
1420
+ def __init__(self, config):
1421
+ super().__init__(config)
1422
+ self.num_labels = config.num_labels
1423
+ self.model = LightpostModel(config)
1424
+ if getattr(config, "classifier_dropout", None) is not None:
1425
+ classifier_dropout = config.classifier_dropout
1426
+ elif getattr(config, "hidden_dropout", None) is not None:
1427
+ classifier_dropout = config.hidden_dropout
1428
+ else:
1429
+ classifier_dropout = 0.1
1430
+ self.dropout = nn.Dropout(classifier_dropout)
1431
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1432
+
1433
+ # Initialize weights and apply final processing
1434
+ self.post_init()
1435
+
1436
+ def get_input_embeddings(self):
1437
+ return self.model.embed_tokens
1438
+
1439
+ def set_input_embeddings(self, value):
1440
+ self.model.embed_tokens = value
1441
+
1442
+ @add_start_docstrings_to_model_forward(LIGHTPOST_INPUTS_DOCSTRING)
1443
+ @add_code_sample_docstrings(
1444
+ checkpoint=_CHECKPOINT_FOR_DOC,
1445
+ output_type=TokenClassifierOutput,
1446
+ config_class=_CONFIG_FOR_DOC,
1447
+ )
1448
+ def forward(
1449
+ self,
1450
+ input_ids: Optional[torch.LongTensor] = None,
1451
+ attention_mask: Optional[torch.Tensor] = None,
1452
+ position_ids: Optional[torch.LongTensor] = None,
1453
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1454
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1455
+ labels: Optional[torch.LongTensor] = None,
1456
+ use_cache: Optional[bool] = None,
1457
+ output_attentions: Optional[bool] = None,
1458
+ output_hidden_states: Optional[bool] = None,
1459
+ return_dict: Optional[bool] = None,
1460
+ ) -> Union[Tuple, TokenClassifierOutput]:
1461
+ r"""
1462
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1463
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1464
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1465
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1466
+ """
1467
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1468
+
1469
+ outputs = self.model(
1470
+ input_ids,
1471
+ attention_mask=attention_mask,
1472
+ position_ids=position_ids,
1473
+ past_key_values=past_key_values,
1474
+ inputs_embeds=inputs_embeds,
1475
+ use_cache=use_cache,
1476
+ output_attentions=output_attentions,
1477
+ output_hidden_states=output_hidden_states,
1478
+ return_dict=return_dict,
1479
+ )
1480
+ sequence_output = outputs[0]
1481
+ sequence_output = self.dropout(sequence_output)
1482
+ logits = self.score(sequence_output)
1483
+
1484
+ loss = None
1485
+ if labels is not None:
1486
+ loss = self.loss_function(logits, labels, self.config)
1487
+
1488
+ if not return_dict:
1489
+ output = (logits,) + outputs[2:]
1490
+ return ((loss,) + output) if loss is not None else output
1491
+
1492
+ return TokenClassifierOutput(
1493
+ loss=loss,
1494
+ logits=logits,
1495
+ hidden_states=outputs.hidden_states,
1496
+ attentions=outputs.attentions,
1497
+ )
1498
+
1499
+
1500
+ @add_start_docstrings(
1501
+ """
1502
+ The Lightpost Model transformer with a span classification head on top for extractive question-answering tasks like
1503
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1504
+ """,
1505
+ LIGHTPOST_START_DOCSTRING,
1506
+ )
1507
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->Lightpost
1508
+ class LightpostForQuestionAnswering(LightpostPreTrainedModel):
1509
+ base_model_prefix = "model"
1510
+
1511
+ def __init__(self, config):
1512
+ super().__init__(config)
1513
+ self.model = LightpostModel(config)
1514
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1515
+
1516
+ # Initialize weights and apply final processing
1517
+ self.post_init()
1518
+
1519
+ def get_input_embeddings(self):
1520
+ return self.model.embed_tokens
1521
+
1522
+ def set_input_embeddings(self, value):
1523
+ self.model.embed_tokens = value
1524
+
1525
+ @add_start_docstrings_to_model_forward(LIGHTPOST_INPUTS_DOCSTRING)
1526
+ def forward(
1527
+ self,
1528
+ input_ids: Optional[torch.LongTensor] = None,
1529
+ attention_mask: Optional[torch.FloatTensor] = None,
1530
+ position_ids: Optional[torch.LongTensor] = None,
1531
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1532
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1533
+ start_positions: Optional[torch.LongTensor] = None,
1534
+ end_positions: Optional[torch.LongTensor] = None,
1535
+ output_attentions: Optional[bool] = None,
1536
+ output_hidden_states: Optional[bool] = None,
1537
+ return_dict: Optional[bool] = None,
1538
+ **kwargs,
1539
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1540
+ r"""
1541
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1542
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1543
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1544
+ are not taken into account for computing the loss.
1545
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1546
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1547
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1548
+ are not taken into account for computing the loss.
1549
+ """
1550
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1551
+
1552
+ outputs = self.model(
1553
+ input_ids,
1554
+ attention_mask=attention_mask,
1555
+ position_ids=position_ids,
1556
+ past_key_values=past_key_values,
1557
+ inputs_embeds=inputs_embeds,
1558
+ output_attentions=output_attentions,
1559
+ output_hidden_states=output_hidden_states,
1560
+ return_dict=return_dict,
1561
+ )
1562
+
1563
+ sequence_output = outputs[0]
1564
+
1565
+ logits = self.qa_outputs(sequence_output)
1566
+ start_logits, end_logits = logits.split(1, dim=-1)
1567
+ start_logits = start_logits.squeeze(-1).contiguous()
1568
+ end_logits = end_logits.squeeze(-1).contiguous()
1569
+
1570
+ loss = None
1571
+ if start_positions is not None and end_positions is not None:
1572
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1573
+
1574
+ if not return_dict:
1575
+ output = (start_logits, end_logits) + outputs[2:]
1576
+ return ((loss,) + output) if loss is not None else output
1577
+
1578
+ return QuestionAnsweringModelOutput(
1579
+ loss=loss,
1580
+ start_logits=start_logits,
1581
+ end_logits=end_logits,
1582
+ hidden_states=outputs.hidden_states,
1583
+ attentions=outputs.attentions,
1584
+ )