minlik commited on
Commit
24e7c49
1 Parent(s): 258f447

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/shared_language_model/models/docllm-Yi-6B-fp16",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
8
+ },
9
+ "attention_bias": false,
10
+ "attention_dropout": 0.0,
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 11008,
17
+ "lambda_ss": 1,
18
+ "lambda_st": 1,
19
+ "lambda_ts": 1,
20
+ "max_position_embeddings": 4096,
21
+ "model_type": "llama",
22
+ "num_attention_heads": 32,
23
+ "num_hidden_layers": 32,
24
+ "num_key_value_heads": 4,
25
+ "pad_token_id": 0,
26
+ "pretraining_tp": 1,
27
+ "rms_norm_eps": 1e-05,
28
+ "rope_scaling": null,
29
+ "rope_theta": 5000000.0,
30
+ "tie_word_embeddings": false,
31
+ "torch_dtype": "float16",
32
+ "transformers_version": "4.36.1",
33
+ "use_cache": true,
34
+ "vocab_size": 64000
35
+ }
configuration_llama.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class LlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
65
+ Llama 2 up to 4096, CodeLlama up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+
101
+ ```python
102
+ >>> from transformers import LlamaModel, LlamaConfig
103
+
104
+ >>> # Initializing a LLaMA llama-7b style configuration
105
+ >>> configuration = LlamaConfig()
106
+
107
+ >>> # Initializing a model from the llama-7b style configuration
108
+ >>> model = LlamaModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "llama"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32000,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ hidden_act="silu",
126
+ max_position_embeddings=2048,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-6,
129
+ use_cache=True,
130
+ pad_token_id=None,
131
+ bos_token_id=1,
132
+ eos_token_id=2,
133
+ pretraining_tp=1,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ attention_bias=False,
138
+ attention_dropout=0.0,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ # for backward compatibility
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.hidden_act = hidden_act
154
+ self.initializer_range = initializer_range
155
+ self.rms_norm_eps = rms_norm_eps
156
+ self.pretraining_tp = pretraining_tp
157
+ self.use_cache = use_cache
158
+ self.rope_theta = rope_theta
159
+ self.rope_scaling = rope_scaling
160
+ self._rope_scaling_validation()
161
+ self.attention_bias = attention_bias
162
+ self.attention_dropout = attention_dropout
163
+
164
+ super().__init__(
165
+ pad_token_id=pad_token_id,
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ def _rope_scaling_validation(self):
173
+ """
174
+ Validate the `rope_scaling` configuration.
175
+ """
176
+ if self.rope_scaling is None:
177
+ return
178
+
179
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
180
+ raise ValueError(
181
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
182
+ f"got {self.rope_scaling}"
183
+ )
184
+ rope_scaling_type = self.rope_scaling.get("type", None)
185
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
186
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
187
+ raise ValueError(
188
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
189
+ )
190
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
191
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.36.1"
7
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c115737895ba4df49628a48b4aa080ee04489ad51069c2bc64f5552627158d25
3
+ size 4999839936
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c881958cde938d238a3fbf63df510713ce394204b2a665d74e599279914480d3
3
+ size 4953704232
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fbd3ef9c280913803c6ad2491faebc93b0c205d7b0c45212031eb708562888d
3
+ size 3510782376
model.safetensors.index.json ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13464281088
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00003-of-00003.safetensors",
7
+ "model.embed_spatial.weight": "model-00001-of-00003.safetensors",
8
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.0.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
18
+ "model.layers.0.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.0.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
20
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
29
+ "model.layers.1.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
30
+ "model.layers.1.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
31
+ "model.layers.1.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
32
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
33
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00003.safetensors",
34
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
35
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
36
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
37
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
40
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
41
+ "model.layers.10.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
42
+ "model.layers.10.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
43
+ "model.layers.10.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
44
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
45
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
46
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
47
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
48
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
52
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
53
+ "model.layers.11.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
54
+ "model.layers.11.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
55
+ "model.layers.11.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
56
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
57
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
59
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.12.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
66
+ "model.layers.12.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.12.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
68
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
70
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
72
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.13.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
78
+ "model.layers.13.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
79
+ "model.layers.13.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
81
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
83
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
85
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.14.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
90
+ "model.layers.14.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.14.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
92
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
94
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
96
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.15.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
102
+ "model.layers.15.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.15.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
105
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
107
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
109
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.16.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
114
+ "model.layers.16.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.16.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
117
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
118
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
119
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
120
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
121
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
124
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
125
+ "model.layers.17.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
126
+ "model.layers.17.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.17.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
131
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
133
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
137
+ "model.layers.18.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
138
+ "model.layers.18.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.18.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
140
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
141
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
142
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
143
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
144
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
145
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
148
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
149
+ "model.layers.19.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
150
+ "model.layers.19.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
151
+ "model.layers.19.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
152
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
153
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
154
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
155
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
156
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
157
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
160
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
161
+ "model.layers.2.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
162
+ "model.layers.2.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
163
+ "model.layers.2.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
164
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
165
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
166
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
167
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
168
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
169
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
172
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
173
+ "model.layers.20.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
174
+ "model.layers.20.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
175
+ "model.layers.20.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
176
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
177
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
178
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
179
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
180
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
181
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
184
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
185
+ "model.layers.21.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
186
+ "model.layers.21.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
187
+ "model.layers.21.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
188
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
189
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00003.safetensors",
190
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
191
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
192
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
193
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
196
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
197
+ "model.layers.22.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
198
+ "model.layers.22.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
199
+ "model.layers.22.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
200
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
201
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00003.safetensors",
202
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
203
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
204
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
205
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
208
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
209
+ "model.layers.23.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
210
+ "model.layers.23.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
211
+ "model.layers.23.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
212
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
213
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
214
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
215
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
216
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
217
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
220
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
221
+ "model.layers.24.self_attn.spatial_k_proj.weight": "model-00002-of-00003.safetensors",
222
+ "model.layers.24.self_attn.spatial_q_proj.weight": "model-00002-of-00003.safetensors",
223
+ "model.layers.24.self_attn.spatial_v_proj.weight": "model-00002-of-00003.safetensors",
224
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
225
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
226
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
227
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
228
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
229
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
232
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
233
+ "model.layers.25.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
234
+ "model.layers.25.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
235
+ "model.layers.25.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
236
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
237
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
238
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
239
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
240
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
241
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
242
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
244
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
245
+ "model.layers.26.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
246
+ "model.layers.26.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
247
+ "model.layers.26.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
248
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
249
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
250
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
251
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
252
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
253
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
254
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
255
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
256
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
257
+ "model.layers.27.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
258
+ "model.layers.27.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
259
+ "model.layers.27.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
260
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
261
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00003.safetensors",
262
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
263
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
264
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
265
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
266
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
267
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
268
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
269
+ "model.layers.28.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
270
+ "model.layers.28.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
271
+ "model.layers.28.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
272
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
273
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00003.safetensors",
274
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
275
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
276
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
277
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
278
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
279
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
280
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
281
+ "model.layers.29.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
282
+ "model.layers.29.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
283
+ "model.layers.29.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
284
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
285
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
286
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
287
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
288
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
289
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
290
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
291
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
292
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
293
+ "model.layers.3.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
294
+ "model.layers.3.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
295
+ "model.layers.3.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
296
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
297
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00003.safetensors",
298
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
299
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
300
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
301
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
302
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
303
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
304
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
305
+ "model.layers.30.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
306
+ "model.layers.30.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
307
+ "model.layers.30.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
308
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
309
+ "model.layers.31.input_layernorm.weight": "model-00003-of-00003.safetensors",
310
+ "model.layers.31.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
311
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
312
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
313
+ "model.layers.31.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
314
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
315
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
316
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
317
+ "model.layers.31.self_attn.spatial_k_proj.weight": "model-00003-of-00003.safetensors",
318
+ "model.layers.31.self_attn.spatial_q_proj.weight": "model-00003-of-00003.safetensors",
319
+ "model.layers.31.self_attn.spatial_v_proj.weight": "model-00003-of-00003.safetensors",
320
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
321
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
322
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
323
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
324
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
325
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
326
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
327
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
328
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
329
+ "model.layers.4.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
330
+ "model.layers.4.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
331
+ "model.layers.4.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
332
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
333
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
334
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
335
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
336
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
337
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
338
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
339
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
340
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
341
+ "model.layers.5.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
342
+ "model.layers.5.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
343
+ "model.layers.5.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
344
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
345
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
346
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
347
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
348
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
349
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
350
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
351
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
352
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
353
+ "model.layers.6.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
354
+ "model.layers.6.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
355
+ "model.layers.6.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
356
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
357
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
358
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
359
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
360
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
361
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
362
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
363
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
364
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
365
+ "model.layers.7.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
366
+ "model.layers.7.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
367
+ "model.layers.7.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
368
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
369
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
370
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
371
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
372
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
373
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
374
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
375
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
376
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
377
+ "model.layers.8.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
378
+ "model.layers.8.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
379
+ "model.layers.8.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
380
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
381
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00003.safetensors",
382
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
383
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
384
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
385
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
386
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
387
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
388
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
389
+ "model.layers.9.self_attn.spatial_k_proj.weight": "model-00001-of-00003.safetensors",
390
+ "model.layers.9.self_attn.spatial_q_proj.weight": "model-00001-of-00003.safetensors",
391
+ "model.layers.9.self_attn.spatial_v_proj.weight": "model-00001-of-00003.safetensors",
392
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
393
+ "model.norm.weight": "model-00003-of-00003.safetensors"
394
+ }
395
+ }
modeling_llama.py ADDED
@@ -0,0 +1,1074 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
40
+ SequenceClassifierOutputWithPast
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from transformers.utils.import_utils import is_torch_fx_available
50
+ from .configuration_llama import LlamaConfig
51
+
52
+
53
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
54
+ # It means that the function will not be traced through and simply appear as a node in the graph.
55
+ if is_torch_fx_available():
56
+ if not is_torch_greater_or_equal_than_1_13:
57
+ import torch.fx
58
+
59
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "LlamaConfig"
64
+
65
+
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
79
+ warnings.warn(
80
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
81
+ )
82
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
83
+
84
+
85
+ def _make_causal_mask(
86
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
87
+ ):
88
+ warnings.warn(
89
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
90
+ )
91
+ return AttentionMaskConverter._make_causal_mask(
92
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
93
+ )
94
+
95
+
96
+ class LlamaRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ LlamaRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ input_dtype = hidden_states.dtype
107
+ hidden_states = hidden_states.to(torch.float32)
108
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
109
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
114
+
115
+
116
+ class LlamaRotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
129
+ )
130
+
131
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
132
+ self.max_seq_len_cached = seq_len
133
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
134
+
135
+ freqs = torch.outer(t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
139
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
140
+
141
+ def forward(self, x, seq_len=None):
142
+ # x: [bs, num_attention_heads, seq_len, head_size]
143
+ if seq_len > self.max_seq_len_cached:
144
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
145
+
146
+ return (
147
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
148
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
149
+ )
150
+
151
+
152
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
153
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
154
+
155
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
156
+ self.scaling_factor = scaling_factor
157
+ super().__init__(dim, max_position_embeddings, base, device)
158
+
159
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
160
+ self.max_seq_len_cached = seq_len
161
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
162
+ t = t / self.scaling_factor
163
+
164
+ freqs = torch.outer(t, self.inv_freq)
165
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
166
+ emb = torch.cat((freqs, freqs), dim=-1)
167
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
168
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
169
+
170
+
171
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
172
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
173
+
174
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
175
+ self.scaling_factor = scaling_factor
176
+ super().__init__(dim, max_position_embeddings, base, device)
177
+
178
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
179
+ self.max_seq_len_cached = seq_len
180
+
181
+ if seq_len > self.max_position_embeddings:
182
+ base = self.base * (
183
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
184
+ ) ** (self.dim / (self.dim - 2))
185
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
186
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
187
+
188
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
189
+
190
+ freqs = torch.outer(t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ def rotate_half(x):
198
+ """Rotates half the hidden dims of the input."""
199
+ x1 = x[..., : x.shape[-1] // 2]
200
+ x2 = x[..., x.shape[-1] // 2:]
201
+ return torch.cat((-x2, x1), dim=-1)
202
+
203
+
204
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
205
+ """Applies Rotary Position Embedding to the query and key tensors.
206
+
207
+ Args:
208
+ q (`torch.Tensor`): The query tensor.
209
+ k (`torch.Tensor`): The key tensor.
210
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
211
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
212
+ position_ids (`torch.Tensor`):
213
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
214
+ used to pass offsetted position ids when working with a KV-cache.
215
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
216
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
217
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
218
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
219
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
220
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
221
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
222
+ Returns:
223
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
224
+ """
225
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
226
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
227
+ q_embed = (q * cos) + (rotate_half(q) * sin)
228
+ k_embed = (k * cos) + (rotate_half(k) * sin)
229
+ return q_embed, k_embed
230
+
231
+
232
+ class LlamaMLP(nn.Module):
233
+ def __init__(self, config):
234
+ super().__init__()
235
+ self.config = config
236
+ self.hidden_size = config.hidden_size
237
+ self.intermediate_size = config.intermediate_size
238
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
239
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
240
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
241
+ self.act_fn = ACT2FN[config.hidden_act]
242
+
243
+ def forward(self, x):
244
+ if self.config.pretraining_tp > 1:
245
+ slice = self.intermediate_size // self.config.pretraining_tp
246
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
247
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
248
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
249
+
250
+ gate_proj = torch.cat(
251
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
252
+ )
253
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
254
+
255
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
256
+ down_proj = [
257
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
258
+ ]
259
+ down_proj = sum(down_proj)
260
+ else:
261
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
262
+
263
+ return down_proj
264
+
265
+
266
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
267
+ """
268
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
269
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
270
+ """
271
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
272
+ if n_rep == 1:
273
+ return hidden_states
274
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
275
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
276
+
277
+
278
+ class LlamaAttention(nn.Module):
279
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
280
+
281
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
282
+ super().__init__()
283
+ self.config = config
284
+ self.layer_idx = layer_idx
285
+ if layer_idx is None:
286
+ logger.warning_once(
287
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
288
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
289
+ "when creating this class."
290
+ )
291
+
292
+ self.attention_dropout = config.attention_dropout
293
+ self.hidden_size = config.hidden_size
294
+ self.num_heads = config.num_attention_heads
295
+ self.head_dim = self.hidden_size // self.num_heads
296
+ self.num_key_value_heads = config.num_key_value_heads
297
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
298
+ self.max_position_embeddings = config.max_position_embeddings
299
+ self.rope_theta = config.rope_theta
300
+ self.is_causal = True
301
+
302
+ # fixme: config needs to be updated to include these parameters
303
+ self._lambda_ts = 1
304
+ self._lambda_st = 1
305
+ self._lambda_ss = 1
306
+
307
+ if (self.head_dim * self.num_heads) != self.hidden_size:
308
+ raise ValueError(
309
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
310
+ f" and `num_heads`: {self.num_heads})."
311
+ )
312
+
313
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
314
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
315
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
316
+ self.spatial_q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
317
+ self.spatial_k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
318
+ self.spatial_v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
319
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
320
+ self._init_rope()
321
+
322
+ def _init_rope(self):
323
+ if self.config.rope_scaling is None:
324
+ self.rotary_emb = LlamaRotaryEmbedding(
325
+ self.head_dim,
326
+ max_position_embeddings=self.max_position_embeddings,
327
+ base=self.rope_theta,
328
+ )
329
+ else:
330
+ scaling_type = self.config.rope_scaling["type"]
331
+ scaling_factor = self.config.rope_scaling["factor"]
332
+ if scaling_type == "linear":
333
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
334
+ self.head_dim,
335
+ max_position_embeddings=self.max_position_embeddings,
336
+ scaling_factor=scaling_factor,
337
+ base=self.rope_theta,
338
+ )
339
+ elif scaling_type == "dynamic":
340
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
341
+ self.head_dim,
342
+ max_position_embeddings=self.max_position_embeddings,
343
+ scaling_factor=scaling_factor,
344
+ base=self.rope_theta,
345
+ )
346
+ else:
347
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
348
+
349
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
350
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
351
+
352
+ def forward(
353
+ self,
354
+ hidden_states: torch.Tensor,
355
+ bounding_box_embeddings: torch.Tensor,
356
+ attention_mask: Optional[torch.Tensor] = None,
357
+ position_ids: Optional[torch.LongTensor] = None,
358
+ past_key_value: Optional[Cache] = None,
359
+ spatial_past_key_value: Optional[Cache] = None,
360
+ output_attentions: bool = False,
361
+ use_cache: bool = False,
362
+ **kwargs,
363
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
364
+ if "padding_mask" in kwargs:
365
+ warnings.warn(
366
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
367
+ )
368
+
369
+ bsz, q_len, _ = hidden_states.size()
370
+
371
+ if self.config.pretraining_tp > 1:
372
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
373
+ query_slices = self.q_proj.weight.split(
374
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
375
+ )
376
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
377
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
378
+
379
+ spatial_query_slices = self.spatial_q_proj.weight.split(
380
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
381
+ )
382
+ spatial_key_slices = self.spatial_k_proj.weight.split(key_value_slicing, dim=0)
383
+ spatial_value_slices = self.spatial_v_proj.weight.split(key_value_slicing, dim=0)
384
+
385
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
386
+ query_states = torch.cat(query_states, dim=-1)
387
+ spatial_query_states = [F.linear(bounding_box_embeddings, spatial_query_slices[i]) for i in range(self.config.pretraining_tp)]
388
+ spatial_query_states = torch.cat(spatial_query_states, dim=-1)
389
+
390
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
391
+ key_states = torch.cat(key_states, dim=-1)
392
+ spatial_key_states = [F.linear(bounding_box_embeddings, spatial_key_slices[i]) for i in range(self.config.pretraining_tp)]
393
+ spatial_key_states = torch.cat(spatial_key_states, dim=-1)
394
+
395
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
396
+ value_states = torch.cat(value_states, dim=-1)
397
+ spatial_value_states = [F.linear(bounding_box_embeddings, spatial_value_slices[i]) for i in range(self.config.pretraining_tp)]
398
+ spatial_value_states = torch.cat(spatial_value_states, dim=-1)
399
+ else:
400
+ query_states = self.q_proj(hidden_states)
401
+ key_states = self.k_proj(hidden_states)
402
+ value_states = self.v_proj(hidden_states)
403
+
404
+ spatial_query_states = self.spatial_q_proj(bounding_box_embeddings)
405
+ spatial_key_states = self.spatial_k_proj(bounding_box_embeddings)
406
+ spatial_value_states = self.spatial_v_proj(bounding_box_embeddings)
407
+
408
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
409
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
410
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
411
+ spatial_query_states = spatial_query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+ spatial_key_states = spatial_key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
413
+ spatial_value_states = spatial_value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
414
+
415
+ kv_seq_len = key_states.shape[-2]
416
+ if past_key_value is not None:
417
+ if self.layer_idx is None:
418
+ raise ValueError(
419
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
420
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
421
+ "with a layer index."
422
+ )
423
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
424
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
425
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
426
+
427
+ # fixme: do we need to apply rotary pos emb to spatial query and key states?
428
+ spatial_query_states, spatial_key_states = apply_rotary_pos_emb(spatial_query_states, spatial_key_states, cos, sin, position_ids)
429
+
430
+ if past_key_value is not None:
431
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
432
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
433
+ if spatial_past_key_value is not None:
434
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
435
+ spatial_key_states, spatial_value_states = spatial_past_key_value.update(spatial_key_states, spatial_value_states, self.layer_idx, cache_kwargs)
436
+
437
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
438
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
439
+ spatial_key_states = repeat_kv(spatial_key_states, self.num_key_value_groups)
440
+
441
+ attn_weight_tt = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
442
+ attn_weight_ts = torch.matmul(query_states, spatial_key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
443
+ attn_weight_st = torch.matmul(spatial_query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
444
+ attn_weight_ss = torch.matmul(spatial_query_states, spatial_key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
445
+
446
+ attn_weights = attn_weight_tt + self._lambda_ts * attn_weight_ts + self._lambda_st * attn_weight_st + self._lambda_ss * attn_weight_ss
447
+
448
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
449
+ raise ValueError(
450
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
451
+ f" {attn_weights.size()}"
452
+ )
453
+
454
+ if attention_mask is not None:
455
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
456
+ raise ValueError(
457
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
458
+ )
459
+ attn_weights = attn_weights + attention_mask
460
+
461
+ # upcast attention to fp32
462
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
463
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
464
+ attn_output = torch.matmul(attn_weights, value_states)
465
+
466
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
467
+ raise ValueError(
468
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
469
+ f" {attn_output.size()}"
470
+ )
471
+
472
+ attn_output = attn_output.transpose(1, 2).contiguous()
473
+
474
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
475
+
476
+ if self.config.pretraining_tp > 1:
477
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
478
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
479
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
480
+ else:
481
+ attn_output = self.o_proj(attn_output)
482
+
483
+ if not output_attentions:
484
+ attn_weights = None
485
+
486
+ return attn_output, attn_weights, past_key_value, spatial_past_key_value
487
+
488
+
489
+ class LlamaDecoderLayer(nn.Module):
490
+ def __init__(self, config: LlamaConfig, layer_idx: int):
491
+ super().__init__()
492
+ self.hidden_size = config.hidden_size
493
+
494
+ # flash attention is not supported for Docllm model yet
495
+ # self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
496
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
497
+ self.mlp = LlamaMLP(config)
498
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
499
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
500
+
501
+ def forward(
502
+ self,
503
+ hidden_states: torch.Tensor,
504
+ bounding_box_embeddings: Optional[torch.Tensor] = None,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
508
+ spatial_past_key_value: Optional[Tuple[torch.Tensor]] = None,
509
+ output_attentions: Optional[bool] = False,
510
+ use_cache: Optional[bool] = False,
511
+ **kwargs,
512
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
513
+ """
514
+ Args:
515
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
516
+ attention_mask (`torch.FloatTensor`, *optional*):
517
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
518
+ query_sequence_length, key_sequence_length)` if default attention is used.
519
+ output_attentions (`bool`, *optional*):
520
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
521
+ returned tensors for more detail.
522
+ use_cache (`bool`, *optional*):
523
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
524
+ (see `past_key_values`).
525
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
526
+ """
527
+ if "padding_mask" in kwargs:
528
+ warnings.warn(
529
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
530
+ )
531
+
532
+ residual = hidden_states
533
+
534
+ hidden_states = self.input_layernorm(hidden_states)
535
+
536
+ # Self Attention
537
+ hidden_states, self_attn_weights, present_key_value, spatial_present_key_value = self.self_attn(
538
+ hidden_states=hidden_states,
539
+ bounding_box_embeddings=bounding_box_embeddings,
540
+ attention_mask=attention_mask,
541
+ position_ids=position_ids,
542
+ past_key_value=past_key_value,
543
+ spatial_past_key_value=spatial_past_key_value,
544
+ output_attentions=output_attentions,
545
+ use_cache=use_cache,
546
+ **kwargs,
547
+ )
548
+ hidden_states = residual + hidden_states
549
+
550
+ # Fully Connected
551
+ residual = hidden_states
552
+ hidden_states = self.post_attention_layernorm(hidden_states)
553
+ hidden_states = self.mlp(hidden_states)
554
+ hidden_states = residual + hidden_states
555
+
556
+ outputs = (hidden_states,)
557
+
558
+ if output_attentions:
559
+ outputs += (self_attn_weights,)
560
+
561
+ if use_cache:
562
+ outputs += (present_key_value,)
563
+ outputs += (spatial_present_key_value,)
564
+
565
+ return outputs
566
+
567
+
568
+ LLAMA_START_DOCSTRING = r"""
569
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
570
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
571
+ etc.)
572
+
573
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
574
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
575
+ and behavior.
576
+
577
+ Parameters:
578
+ config ([`LlamaConfig`]):
579
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
580
+ load the weights associated with the model, only the configuration. Check out the
581
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
582
+ """
583
+
584
+
585
+ @add_start_docstrings(
586
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
587
+ LLAMA_START_DOCSTRING,
588
+ )
589
+ class LlamaPreTrainedModel(PreTrainedModel):
590
+ config_class = LlamaConfig
591
+ base_model_prefix = "model"
592
+ supports_gradient_checkpointing = True
593
+ _no_split_modules = ["LlamaDecoderLayer"]
594
+ _skip_keys_device_placement = "past_key_values"
595
+ _supports_cache_class = True
596
+
597
+ def _init_weights(self, module):
598
+ std = self.config.initializer_range
599
+ if isinstance(module, nn.Linear):
600
+ module.weight.data.normal_(mean=0.0, std=std)
601
+ if module.bias is not None:
602
+ module.bias.data.zero_()
603
+ elif isinstance(module, nn.Embedding):
604
+ module.weight.data.normal_(mean=0.0, std=std)
605
+ if module.padding_idx is not None:
606
+ module.weight.data[module.padding_idx].zero_()
607
+
608
+
609
+ LLAMA_INPUTS_DOCSTRING = r"""
610
+ Args:
611
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
612
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
613
+ it.
614
+
615
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
616
+ [`PreTrainedTokenizer.__call__`] for details.
617
+
618
+ [What are input IDs?](../glossary#input-ids)
619
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
620
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
621
+
622
+ - 1 for tokens that are **not masked**,
623
+ - 0 for tokens that are **masked**.
624
+
625
+ [What are attention masks?](../glossary#attention-mask)
626
+
627
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
628
+ [`PreTrainedTokenizer.__call__`] for details.
629
+
630
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
631
+ `past_key_values`).
632
+
633
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
634
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
635
+ information on the default strategy.
636
+
637
+ - 1 indicates the head is **not masked**,
638
+ - 0 indicates the head is **masked**.
639
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
640
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
641
+ config.n_positions - 1]`.
642
+
643
+ [What are position IDs?](../glossary#position-ids)
644
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
645
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
646
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
647
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
648
+
649
+ Two formats are allowed:
650
+ - a [`~cache_utils.Cache`] instance;
651
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
652
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
653
+ cache format.
654
+
655
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
656
+ legacy cache format will be returned.
657
+
658
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
659
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
660
+ of shape `(batch_size, sequence_length)`.
661
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
662
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
663
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
664
+ model's internal embedding lookup matrix.
665
+ use_cache (`bool`, *optional*):
666
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
667
+ `past_key_values`).
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
670
+ tensors for more detail.
671
+ output_hidden_states (`bool`, *optional*):
672
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
673
+ more detail.
674
+ return_dict (`bool`, *optional*):
675
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
676
+ """
677
+
678
+
679
+ @add_start_docstrings(
680
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
681
+ LLAMA_START_DOCSTRING,
682
+ )
683
+ class DocLLMBaseModelOutputWithPast(BaseModelOutputWithPast):
684
+ def __init__(self, *args, spatial_past_key_values=None, **kwargs):
685
+ super().__init__(*args, **kwargs)
686
+ self.spatial_past_key_values = spatial_past_key_values
687
+
688
+
689
+ class DocLLMCausalLMOutputWithPast(CausalLMOutputWithPast):
690
+ def __init__(self, *args, spatial_past_key_values=None, **kwargs):
691
+ super().__init__(*args, **kwargs)
692
+ self.spatial_past_key_values = spatial_past_key_values
693
+
694
+
695
+ class LlamaModel(LlamaPreTrainedModel):
696
+ """
697
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
698
+
699
+ Args:
700
+ config: LlamaConfig
701
+ """
702
+
703
+ def __init__(self, config: LlamaConfig):
704
+ super().__init__(config)
705
+ self.padding_idx = config.pad_token_id
706
+ self.vocab_size = config.vocab_size
707
+
708
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
709
+ self.embed_spatial = nn.Linear(4, config.hidden_size, bias=False)
710
+ self.layers = nn.ModuleList(
711
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
712
+ )
713
+ self._use_sdpa = config._attn_implementation == "sdpa"
714
+ # self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
715
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
716
+
717
+ self.gradient_checkpointing = False
718
+ # Initialize weights and apply final processing
719
+ self.post_init()
720
+
721
+ def get_input_embeddings(self):
722
+ return self.embed_tokens
723
+
724
+ def set_input_embeddings(self, value):
725
+ self.embed_tokens = value
726
+
727
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
728
+ def forward(
729
+ self,
730
+ input_ids: torch.LongTensor = None,
731
+ input_coordinates: torch.FloatTensor = None,
732
+ attention_mask: Optional[torch.Tensor] = None,
733
+ position_ids: Optional[torch.LongTensor] = None,
734
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
735
+ spatial_past_key_values: Optional[torch.FloatTensor] = None,
736
+ inputs_embeds: Optional[torch.FloatTensor] = None,
737
+ use_cache: Optional[bool] = None,
738
+ output_attentions: Optional[bool] = None,
739
+ output_hidden_states: Optional[bool] = None,
740
+ return_dict: Optional[bool] = None,
741
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
742
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
743
+ output_hidden_states = (
744
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
745
+ )
746
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
747
+
748
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
749
+
750
+ # retrieve input_ids and inputs_embeds
751
+ if input_ids is not None and inputs_embeds is not None:
752
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
753
+ elif input_ids is not None:
754
+ batch_size, seq_length = input_ids.shape[:2]
755
+ elif inputs_embeds is not None:
756
+ batch_size, seq_length = inputs_embeds.shape[:2]
757
+ else:
758
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
759
+ assert input_ids.device == input_coordinates.device
760
+
761
+ if self.gradient_checkpointing and self.training:
762
+ if use_cache:
763
+ logger.warning_once(
764
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
765
+ )
766
+ use_cache = False
767
+
768
+ past_key_values_length = 0
769
+ if use_cache:
770
+ use_legacy_cache = not isinstance(past_key_values, Cache)
771
+ if use_legacy_cache:
772
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
773
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
774
+
775
+ spatial_use_legacy_cache = not isinstance(spatial_past_key_values, Cache)
776
+ if spatial_use_legacy_cache:
777
+ spatial_past_key_values = DynamicCache.from_legacy_cache(spatial_past_key_values)
778
+
779
+ if position_ids is None:
780
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
781
+ position_ids = torch.arange(
782
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
783
+ )
784
+ position_ids = position_ids.unsqueeze(0)
785
+
786
+ if inputs_embeds is None:
787
+ inputs_embeds = self.embed_tokens(input_ids)
788
+
789
+ coordinate_embeds = self.embed_spatial(input_coordinates)
790
+
791
+ # if self._use_flash_attention_2:
792
+ # # 2d mask is passed through the layers
793
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
794
+ if self._use_sdpa and not output_attentions:
795
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
796
+ # the manual implementation that requires a 4D causal mask in all cases.
797
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
798
+ attention_mask,
799
+ (batch_size, seq_length),
800
+ inputs_embeds,
801
+ past_key_values_length,
802
+ )
803
+ else:
804
+ # 4d mask is passed through the layers
805
+ attention_mask = _prepare_4d_causal_attention_mask(
806
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
807
+ )
808
+
809
+ # embed positions
810
+ hidden_states = inputs_embeds
811
+
812
+ # decoder layers
813
+ all_hidden_states = () if output_hidden_states else None
814
+ all_self_attns = () if output_attentions else None
815
+ next_decoder_cache = None
816
+ spatial_next_decoder_cache = None
817
+
818
+ for decoder_layer in self.layers:
819
+ if output_hidden_states:
820
+ all_hidden_states += (hidden_states,)
821
+
822
+ if self.gradient_checkpointing and self.training:
823
+ layer_outputs = self._gradient_checkpointing_func(
824
+ decoder_layer.__call__,
825
+ hidden_states,
826
+ coordinate_embeds,
827
+ attention_mask,
828
+ position_ids,
829
+ past_key_values,
830
+ output_attentions,
831
+ use_cache,
832
+ )
833
+ else:
834
+ layer_outputs = decoder_layer(
835
+ hidden_states,
836
+ coordinate_embeds,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ past_key_value=past_key_values,
840
+ spatial_past_key_value=spatial_past_key_values,
841
+ output_attentions=output_attentions,
842
+ use_cache=use_cache,
843
+ )
844
+
845
+ hidden_states = layer_outputs[0]
846
+
847
+ if use_cache:
848
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
849
+ spatial_next_decoder_cache = layer_outputs[3 if output_attentions else 2]
850
+
851
+ if output_attentions:
852
+ all_self_attns += (layer_outputs[1],)
853
+
854
+ hidden_states = self.norm(hidden_states)
855
+
856
+ # add hidden states from the last decoder layer
857
+ if output_hidden_states:
858
+ all_hidden_states += (hidden_states,)
859
+
860
+ next_cache = None
861
+ spatial_next_cache = None
862
+ if use_cache:
863
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
864
+ spatial_next_cache = spatial_next_decoder_cache.to_legacy_cache() if spatial_use_legacy_cache \
865
+ else spatial_next_decoder_cache
866
+ if not return_dict:
867
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
868
+ return DocLLMBaseModelOutputWithPast(
869
+ last_hidden_state=hidden_states,
870
+ past_key_values=next_cache,
871
+ spatial_past_key_values=spatial_next_cache,
872
+ hidden_states=all_hidden_states,
873
+ attentions=all_self_attns,
874
+ )
875
+
876
+
877
+ class LlamaForCausalLM(LlamaPreTrainedModel):
878
+ _tied_weights_keys = ["lm_head.weight"]
879
+
880
+ def __init__(self, config):
881
+ super().__init__(config)
882
+ self.model = LlamaModel(config)
883
+ self.vocab_size = config.vocab_size
884
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
885
+
886
+ # Initialize weights and apply final processing
887
+ self.post_init()
888
+
889
+ def get_input_embeddings(self):
890
+ return self.model.embed_tokens
891
+
892
+ def set_input_embeddings(self, value):
893
+ self.model.embed_tokens = value
894
+
895
+ def get_output_embeddings(self):
896
+ return self.lm_head
897
+
898
+ def set_output_embeddings(self, new_embeddings):
899
+ self.lm_head = new_embeddings
900
+
901
+ def set_decoder(self, decoder):
902
+ self.model = decoder
903
+
904
+ def get_decoder(self):
905
+ return self.model
906
+
907
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
908
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
909
+ def forward(
910
+ self,
911
+ input_ids: torch.LongTensor = None,
912
+ input_coordinates: torch.FloatTensor = None,
913
+ attention_mask: Optional[torch.Tensor] = None,
914
+ position_ids: Optional[torch.LongTensor] = None,
915
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
916
+ spatial_past_key_values: Optional[List[torch.FloatTensor]] = None,
917
+ inputs_embeds: Optional[torch.FloatTensor] = None,
918
+ labels: Optional[torch.LongTensor] = None,
919
+ use_cache: Optional[bool] = None,
920
+ output_attentions: Optional[bool] = None,
921
+ output_hidden_states: Optional[bool] = None,
922
+ return_dict: Optional[bool] = None,
923
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
924
+ r"""
925
+ Args:
926
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
928
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
929
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
930
+
931
+ Returns:
932
+
933
+ Example:
934
+
935
+ ```python
936
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
937
+
938
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
939
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
940
+
941
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
942
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
943
+
944
+ >>> # Generate
945
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
946
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
947
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
948
+ ```"""
949
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
950
+ output_hidden_states = (
951
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
952
+ )
953
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
954
+
955
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
956
+ outputs = self.model(
957
+ input_ids=input_ids,
958
+ input_coordinates=input_coordinates,
959
+ attention_mask=attention_mask,
960
+ position_ids=position_ids,
961
+ past_key_values=past_key_values,
962
+ spatial_past_key_values=spatial_past_key_values,
963
+ inputs_embeds=inputs_embeds,
964
+ use_cache=use_cache,
965
+ output_attentions=output_attentions,
966
+ output_hidden_states=output_hidden_states,
967
+ return_dict=return_dict,
968
+ )
969
+
970
+ hidden_states = outputs[0]
971
+ if self.config.pretraining_tp > 1:
972
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
973
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
974
+ logits = torch.cat(logits, dim=-1)
975
+ else:
976
+ logits = self.lm_head(hidden_states)
977
+ logits = logits.float()
978
+
979
+ loss = None
980
+ if labels is not None:
981
+ # Shift so that tokens < n predict n
982
+ shift_logits = logits[..., :-1, :].contiguous()
983
+ shift_labels = labels[..., 1:].contiguous()
984
+ # Flatten the tokens
985
+ loss_fct = CrossEntropyLoss()
986
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
987
+ shift_labels = shift_labels.view(-1)
988
+ # Enable model parallelism
989
+ shift_labels = shift_labels.to(shift_logits.device)
990
+ loss = loss_fct(shift_logits, shift_labels)
991
+
992
+ if not return_dict:
993
+ output = (logits,) + outputs[1:]
994
+ return (loss,) + output if loss is not None else output
995
+
996
+ return DocLLMCausalLMOutputWithPast(
997
+ loss=loss,
998
+ logits=logits,
999
+ past_key_values=outputs.past_key_values,
1000
+ spatial_past_key_values=outputs.spatial_past_key_values,
1001
+ hidden_states=outputs.hidden_states,
1002
+ attentions=outputs.attentions,
1003
+ )
1004
+
1005
+ def prepare_inputs_for_generation(
1006
+ self, input_ids, input_coordinates, past_key_values=None, spatial_pst_key_values=None,
1007
+ attention_mask=None, inputs_embeds=None, coordinates_embeds=None, **kwargs
1008
+ ):
1009
+ if past_key_values is not None:
1010
+ if isinstance(past_key_values, Cache):
1011
+ cache_length = past_key_values.get_seq_length()
1012
+ past_length = past_key_values.seen_tokens
1013
+ max_cache_length = past_key_values.get_max_length()
1014
+ else:
1015
+ cache_length = past_length = past_key_values[0][0].shape[2]
1016
+ max_cache_length = None
1017
+
1018
+ # Keep only the unprocessed tokens:
1019
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1020
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1021
+ # input)
1022
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1023
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1024
+ input_coordinates = input_coordinates[:, -(attention_mask.shape[1] - past_length):]
1025
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1026
+ # input_ids based on the past_length.
1027
+ elif past_length < input_ids.shape[1]:
1028
+ input_ids = input_ids[:, past_length:]
1029
+ input_coordinates = input_coordinates[:, past_length:]
1030
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1031
+
1032
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1033
+ if (
1034
+ max_cache_length is not None
1035
+ and attention_mask is not None
1036
+ and cache_length + input_ids.shape[1] > max_cache_length
1037
+ ):
1038
+ attention_mask = attention_mask[:, -max_cache_length:]
1039
+
1040
+ position_ids = kwargs.get("position_ids", None)
1041
+ if attention_mask is not None and position_ids is None:
1042
+ # create position_ids on the fly for batch generation
1043
+ position_ids = attention_mask.long().cumsum(-1) - 1
1044
+ position_ids.masked_fill_(attention_mask == 0, 1)
1045
+ if past_key_values:
1046
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1047
+
1048
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1049
+ if inputs_embeds is not None and past_key_values is None:
1050
+ model_inputs = {"inputs_embeds": inputs_embeds,
1051
+ "coordinates_embeds": coordinates_embeds}
1052
+ else:
1053
+ model_inputs = {"input_ids": input_ids,
1054
+ "input_coordinates": input_coordinates}
1055
+
1056
+ model_inputs.update(
1057
+ {
1058
+ "position_ids": position_ids,
1059
+ "past_key_values": past_key_values,
1060
+ "spatial_past_key_values": spatial_pst_key_values,
1061
+ "use_cache": kwargs.get("use_cache"),
1062
+ "attention_mask": attention_mask,
1063
+ }
1064
+ )
1065
+ return model_inputs
1066
+
1067
+ @staticmethod
1068
+ def _reorder_cache(past_key_values, beam_idx):
1069
+ reordered_past = ()
1070
+ for layer_past in past_key_values:
1071
+ reordered_past += (
1072
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1073
+ )
1074
+ return reordered_past
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:386c49cf943d71aa110361135338c50e38beeff0a66593480421f37b319e1a39
3
+ size 1033105
tokenizer_config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<|startoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "<|endoftext|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "bos_token": "<|startoftext|>",
31
+ "clean_up_tokenization_spaces": false,
32
+ "eos_token": "<|endoftext|>",
33
+ "legacy": true,
34
+ "model_max_length": 4096,
35
+ "pad_token": "<unk>",
36
+ "sp_model_kwargs": {},
37
+ "tokenizer_class": "LlamaTokenizer",
38
+ "unk_token": "<unk>",
39
+ "use_default_system_prompt": false
40
+ }