Omkar Thawakar commited on
Commit
98cccfc
1 Parent(s): 39556d5

initial commit

Browse files

Uploading MobiLlama Model weights

config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "tinyllama",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2048,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 5632,
14
+ "max_position_embeddings": 2048,
15
+ "model_type": "llama",
16
+ "num_attention_heads": 32,
17
+ "num_hidden_layers": 22,
18
+ "num_key_value_heads": 4,
19
+ "pretraining_tp": 1,
20
+ "rms_norm_eps": 1e-05,
21
+ "rope_scaling": null,
22
+ "rope_theta": 10000.0,
23
+ "tie_word_embeddings": false,
24
+ "torch_dtype": "float32",
25
+ "transformers_version": "4.36.1",
26
+ "use_cache": true,
27
+ "vocab_size": 32000
28
+ }
configuration_mobillama.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ...configuration_utils import PretrainedConfig
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class MobiLlamaConfig(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/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
+
103
+ ```"""
104
+
105
+ model_type = "mobillama"
106
+ keys_to_ignore_at_inference = ["past_key_values"]
107
+
108
+ def __init__(
109
+ self,
110
+ vocab_size=32000,
111
+ hidden_size=4096,
112
+ intermediate_size=11008,
113
+ num_hidden_layers=32,
114
+ num_attention_heads=32,
115
+ num_key_value_heads=None,
116
+ hidden_act="silu",
117
+ max_position_embeddings=2048,
118
+ initializer_range=0.02,
119
+ rms_norm_eps=1e-6,
120
+ use_cache=True,
121
+ pad_token_id=None,
122
+ bos_token_id=1,
123
+ eos_token_id=2,
124
+ pretraining_tp=1,
125
+ tie_word_embeddings=False,
126
+ rope_theta=10000.0,
127
+ rope_scaling=None,
128
+ attention_bias=False,
129
+ attention_dropout=0.0,
130
+ **kwargs,
131
+ ):
132
+ self.vocab_size = vocab_size
133
+ self.max_position_embeddings = max_position_embeddings
134
+ self.hidden_size = hidden_size
135
+ self.intermediate_size = intermediate_size
136
+ self.num_hidden_layers = num_hidden_layers
137
+ self.num_attention_heads = num_attention_heads
138
+
139
+ # for backward compatibility
140
+ if num_key_value_heads is None:
141
+ num_key_value_heads = num_attention_heads
142
+
143
+ self.num_key_value_heads = num_key_value_heads
144
+ self.hidden_act = hidden_act
145
+ self.initializer_range = initializer_range
146
+ self.rms_norm_eps = rms_norm_eps
147
+ self.pretraining_tp = pretraining_tp
148
+ self.use_cache = use_cache
149
+ self.rope_theta = rope_theta
150
+ self.rope_scaling = rope_scaling
151
+ self._rope_scaling_validation()
152
+ self.attention_bias = attention_bias
153
+ self.attention_dropout = attention_dropout
154
+
155
+ super().__init__(
156
+ pad_token_id=pad_token_id,
157
+ bos_token_id=bos_token_id,
158
+ eos_token_id=eos_token_id,
159
+ tie_word_embeddings=tie_word_embeddings,
160
+ **kwargs,
161
+ )
162
+
163
+ def _rope_scaling_validation(self):
164
+ """
165
+ Validate the `rope_scaling` configuration.
166
+ """
167
+ if self.rope_scaling is None:
168
+ return
169
+
170
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
171
+ raise ValueError(
172
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
173
+ f"got {self.rope_scaling}"
174
+ )
175
+ rope_scaling_type = self.rope_scaling.get("type", None)
176
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
177
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
178
+ raise ValueError(
179
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
180
+ )
181
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
182
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.36.1"
6
+ }
modelling_mobillama.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from transformers.models.llama.configuration_llama import LlamaConfig
34
+
35
+ # from .configuration_mobillama import MobiLlamaConfig
36
+
37
+ from flash_attn import flash_attn_func
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "LlamaConfig"
43
+
44
+
45
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
46
+ def _make_causal_mask(
47
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
48
+ ):
49
+ """
50
+ Make causal mask used for bi-directional self-attention.
51
+ """
52
+ bsz, tgt_len = input_ids_shape
53
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
54
+ mask_cond = torch.arange(mask.size(-1), device=device)
55
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
56
+ mask = mask.to(dtype)
57
+
58
+ if past_key_values_length > 0:
59
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
60
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
61
+
62
+
63
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
64
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
65
+ """
66
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
67
+ """
68
+ bsz, src_len = mask.size()
69
+ tgt_len = tgt_len if tgt_len is not None else src_len
70
+
71
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
72
+
73
+ inverted_mask = 1.0 - expanded_mask
74
+
75
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
76
+
77
+
78
+ class MobiLlamaRMSNorm(nn.Module):
79
+ def __init__(self, hidden_size, eps=1e-6):
80
+ """
81
+ MobiLlamaRMSNorm is equivalent to T5LayerNorm
82
+ """
83
+ super().__init__()
84
+ self.weight = nn.Parameter(torch.ones(hidden_size))
85
+ self.variance_epsilon = eps
86
+
87
+ def forward(self, hidden_states):
88
+ input_dtype = hidden_states.dtype
89
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
90
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
91
+
92
+ return (self.weight * hidden_states).to(input_dtype)
93
+
94
+
95
+ class MobiLlamaRotaryEmbedding(torch.nn.Module):
96
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
97
+ super().__init__()
98
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
99
+ self.register_buffer("inv_freq", inv_freq)
100
+
101
+ # Build here to make `torch.jit.trace` work.
102
+ self.max_seq_len_cached = max_position_embeddings
103
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
104
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
108
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
113
+ if seq_len > self.max_seq_len_cached:
114
+ self.max_seq_len_cached = seq_len
115
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
116
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
119
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
120
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
121
+ return (
122
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
124
+ )
125
+
126
+
127
+ def rotate_half(x):
128
+ """Rotates half the hidden dims of the input."""
129
+ x1 = x[..., : x.shape[-1] // 2]
130
+ x2 = x[..., x.shape[-1] // 2 :]
131
+ return torch.cat((-x2, x1), dim=-1)
132
+
133
+
134
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
135
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
136
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
137
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
138
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
139
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
140
+ q_embed = (q * cos) + (rotate_half(q) * sin)
141
+ k_embed = (k * cos) + (rotate_half(k) * sin)
142
+ return q_embed, k_embed
143
+
144
+
145
+ class MobiLlamaMLP(nn.Module):
146
+ def __init__(
147
+ self,
148
+ hidden_size: int,
149
+ intermediate_size: int,
150
+ hidden_act: str,
151
+ ):
152
+ super().__init__()
153
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
154
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
155
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
156
+ self.act_fn = ACT2FN[hidden_act]
157
+
158
+ def forward(self, x):
159
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
160
+
161
+
162
+ class MobiLlamaAttention(nn.Module):
163
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
164
+
165
+ def __init__(self, config: LlamaConfig):
166
+ super().__init__()
167
+ self.config = config
168
+ self.hidden_size = config.hidden_size
169
+ self.num_heads = config.num_attention_heads
170
+ self.head_dim = self.hidden_size // self.num_heads
171
+ self.max_position_embeddings = config.max_position_embeddings
172
+
173
+ if (self.head_dim * self.num_heads) != self.hidden_size:
174
+ raise ValueError(
175
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
176
+ f" and `num_heads`: {self.num_heads})."
177
+ )
178
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
179
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
180
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
181
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
182
+ self.rotary_emb = MobiLlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
183
+
184
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
185
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
186
+
187
+ def forward(
188
+ self,
189
+ hidden_states: torch.Tensor,
190
+ attention_mask: Optional[torch.Tensor] = None,
191
+ position_ids: Optional[torch.LongTensor] = None,
192
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
193
+ output_attentions: bool = False,
194
+ use_cache: bool = False,
195
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
196
+ bsz, q_len, _ = hidden_states.size()
197
+
198
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
199
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
200
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
201
+
202
+ kv_seq_len = key_states.shape[-2]
203
+ if past_key_value is not None:
204
+ kv_seq_len += past_key_value[0].shape[-2]
205
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
206
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
207
+ # [bsz, nh, t, hd]
208
+
209
+ if past_key_value is not None:
210
+ # reuse k, v, self_attention
211
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
212
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
213
+
214
+ past_key_value = (key_states, value_states) if use_cache else None
215
+
216
+ attn_output = flash_attn_func(
217
+ q=query_states.transpose(1, 2).to(torch.bfloat16),
218
+ k=key_states.transpose(1, 2).to(torch.bfloat16),
219
+ v=value_states.transpose(1, 2).to(torch.bfloat16),
220
+ causal=True)
221
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
222
+ attn_output = attn_output.to(query_states.dtype)
223
+
224
+ attn_output = self.o_proj(attn_output)
225
+
226
+ # if not output_attentions:
227
+ # attn_weights = None
228
+ assert not output_attentions
229
+ attn_weights = None
230
+
231
+ return attn_output, attn_weights, past_key_value
232
+
233
+
234
+ class MobiLlamaDecoderLayer(nn.Module):
235
+ def __init__(self, config: LlamaConfig, mlp):
236
+ super().__init__()
237
+ self.hidden_size = config.hidden_size
238
+ self.self_attn = MobiLlamaAttention(config=config)
239
+ self.mlp = mlp #LlamaMLP(hidden_size=self.hidden_size,intermediate_size=config.intermediate_size,hidden_act=config.hidden_act,)
240
+ self.input_layernorm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
241
+ self.post_attention_layernorm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
242
+
243
+ def forward(
244
+ self,
245
+ hidden_states: torch.Tensor,
246
+ attention_mask: Optional[torch.Tensor] = None,
247
+ position_ids: Optional[torch.LongTensor] = None,
248
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
249
+ output_attentions: Optional[bool] = False,
250
+ use_cache: Optional[bool] = False,
251
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
252
+ """
253
+ Args:
254
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
255
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
256
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
257
+ output_attentions (`bool`, *optional*):
258
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
259
+ returned tensors for more detail.
260
+ use_cache (`bool`, *optional*):
261
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
262
+ (see `past_key_values`).
263
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
264
+ """
265
+
266
+ residual = hidden_states
267
+
268
+ hidden_states = self.input_layernorm(hidden_states)
269
+
270
+ # Self Attention
271
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
272
+ hidden_states=hidden_states,
273
+ attention_mask=attention_mask,
274
+ position_ids=position_ids,
275
+ past_key_value=past_key_value,
276
+ output_attentions=output_attentions,
277
+ use_cache=use_cache,
278
+ )
279
+ hidden_states = residual + hidden_states
280
+
281
+ # Fully Connected
282
+ residual = hidden_states
283
+ hidden_states = self.post_attention_layernorm(hidden_states)
284
+ hidden_states = self.mlp(hidden_states)
285
+ hidden_states = residual + hidden_states
286
+
287
+ outputs = (hidden_states,)
288
+
289
+ if output_attentions:
290
+ outputs += (self_attn_weights,)
291
+
292
+ if use_cache:
293
+ outputs += (present_key_value,)
294
+
295
+ return outputs
296
+
297
+
298
+ MOBILLAMA_START_DOCSTRING = r"""
299
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
300
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
301
+ etc.)
302
+
303
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
304
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
305
+ and behavior.
306
+
307
+ Parameters:
308
+ config ([`LlamaConfig`]):
309
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
310
+ load the weights associated with the model, only the configuration. Check out the
311
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
312
+ """
313
+
314
+
315
+ @add_start_docstrings(
316
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
317
+ MOBILLAMA_START_DOCSTRING,
318
+ )
319
+ class MobiLlamaPreTrainedModel(PreTrainedModel):
320
+ config_class = LlamaConfig
321
+ base_model_prefix = "model"
322
+ supports_gradient_checkpointing = True
323
+ _no_split_modules = ["MobiLlamaDecoderLayer"]
324
+ _skip_keys_device_placement = "past_key_values"
325
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
326
+
327
+ def _init_weights(self, module):
328
+ std = self.config.initializer_range
329
+ if isinstance(module, nn.Linear):
330
+ module.weight.data.normal_(mean=0.0, std=std)
331
+ if module.bias is not None:
332
+ module.bias.data.zero_()
333
+ elif isinstance(module, nn.Embedding):
334
+ module.weight.data.normal_(mean=0.0, std=std)
335
+ if module.padding_idx is not None:
336
+ module.weight.data[module.padding_idx].zero_()
337
+
338
+ def _set_gradient_checkpointing(self, module, value=False):
339
+ if isinstance(module, MobiLlamaModel):
340
+ module.gradient_checkpointing = value
341
+
342
+
343
+ MOBILLAMA_INPUTS_DOCSTRING = r"""
344
+ Args:
345
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
346
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
347
+ it.
348
+
349
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
350
+ [`PreTrainedTokenizer.__call__`] for details.
351
+
352
+ [What are input IDs?](../glossary#input-ids)
353
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
354
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
355
+
356
+ - 1 for tokens that are **not masked**,
357
+ - 0 for tokens that are **masked**.
358
+
359
+ [What are attention masks?](../glossary#attention-mask)
360
+
361
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
362
+ [`PreTrainedTokenizer.__call__`] for details.
363
+
364
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
365
+ `past_key_values`).
366
+
367
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
368
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
369
+ information on the default strategy.
370
+
371
+ - 1 indicates the head is **not masked**,
372
+ - 0 indicates the head is **masked**.
373
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
374
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
375
+ config.n_positions - 1]`.
376
+
377
+ [What are position IDs?](../glossary#position-ids)
378
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
379
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
380
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
381
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
382
+
383
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
384
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
385
+
386
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
387
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
388
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
389
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
390
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
391
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
392
+ model's internal embedding lookup matrix.
393
+ use_cache (`bool`, *optional*):
394
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
395
+ `past_key_values`).
396
+ output_attentions (`bool`, *optional*):
397
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
398
+ tensors for more detail.
399
+ output_hidden_states (`bool`, *optional*):
400
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
401
+ more detail.
402
+ return_dict (`bool`, *optional*):
403
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
404
+ """
405
+
406
+
407
+ @add_start_docstrings(
408
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
409
+ MOBILLAMA_START_DOCSTRING,
410
+ )
411
+ class MobiLlamaModel(MobiLlamaPreTrainedModel):
412
+ """
413
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MobiLlamaDecoderLayer`]
414
+
415
+ Args:
416
+ config: LlamaConfig
417
+ """
418
+
419
+ def __init__(self, config: LlamaConfig):
420
+ super().__init__(config)
421
+ self.padding_idx = config.pad_token_id
422
+ self.vocab_size = config.vocab_size
423
+
424
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
425
+ mlp = MobiLlamaMLP(
426
+ hidden_size=config.hidden_size,
427
+ intermediate_size=config.intermediate_size,
428
+ hidden_act=config.hidden_act,
429
+ )
430
+ self.layers = nn.ModuleList([MobiLlamaDecoderLayer(config, mlp) for _ in range(config.num_hidden_layers)])
431
+ self.norm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
432
+
433
+ self.gradient_checkpointing = False
434
+ # Initialize weights and apply final processing
435
+ self.post_init()
436
+
437
+ def get_input_embeddings(self):
438
+ return self.embed_tokens
439
+
440
+ def set_input_embeddings(self, value):
441
+ self.embed_tokens = value
442
+
443
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
444
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
445
+ # create causal mask
446
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
447
+ combined_attention_mask = None
448
+ if input_shape[-1] > 1:
449
+ combined_attention_mask = _make_causal_mask(
450
+ input_shape,
451
+ inputs_embeds.dtype,
452
+ device=inputs_embeds.device,
453
+ past_key_values_length=past_key_values_length,
454
+ )
455
+
456
+ if attention_mask is not None:
457
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
458
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
459
+ inputs_embeds.device
460
+ )
461
+ combined_attention_mask = (
462
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
463
+ )
464
+
465
+ return combined_attention_mask
466
+
467
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
468
+ def forward(
469
+ self,
470
+ input_ids: torch.LongTensor = None,
471
+ attention_mask: Optional[torch.Tensor] = None,
472
+ position_ids: Optional[torch.LongTensor] = None,
473
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
474
+ inputs_embeds: Optional[torch.FloatTensor] = None,
475
+ use_cache: Optional[bool] = None,
476
+ output_attentions: Optional[bool] = None,
477
+ output_hidden_states: Optional[bool] = None,
478
+ return_dict: Optional[bool] = None,
479
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
480
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
481
+ output_hidden_states = (
482
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
483
+ )
484
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
485
+
486
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
487
+
488
+ # retrieve input_ids and inputs_embeds
489
+ if input_ids is not None and inputs_embeds is not None:
490
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
491
+ elif input_ids is not None:
492
+ batch_size, seq_length = input_ids.shape
493
+ elif inputs_embeds is not None:
494
+ batch_size, seq_length, _ = inputs_embeds.shape
495
+ else:
496
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
497
+
498
+ seq_length_with_past = seq_length
499
+ past_key_values_length = 0
500
+
501
+ if past_key_values is not None:
502
+ past_key_values_length = past_key_values[0][0].shape[2]
503
+ seq_length_with_past = seq_length_with_past + past_key_values_length
504
+
505
+ if position_ids is None:
506
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
507
+ position_ids = torch.arange(
508
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
509
+ )
510
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
511
+ else:
512
+ position_ids = position_ids.view(-1, seq_length).long()
513
+
514
+ if inputs_embeds is None:
515
+ inputs_embeds = self.embed_tokens(input_ids)
516
+ # embed positions
517
+ if attention_mask is None:
518
+ attention_mask = torch.ones(
519
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
520
+ )
521
+ attention_mask = self._prepare_decoder_attention_mask(
522
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
523
+ )
524
+
525
+ hidden_states = inputs_embeds
526
+
527
+ if self.gradient_checkpointing and self.training:
528
+ if use_cache:
529
+ logger.warning_once(
530
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
531
+ )
532
+ use_cache = False
533
+
534
+ # decoder layers
535
+ all_hidden_states = () if output_hidden_states else None
536
+ all_self_attns = () if output_attentions else None
537
+ next_decoder_cache = () if use_cache else None
538
+
539
+ for idx, decoder_layer in enumerate(self.layers):
540
+ if output_hidden_states:
541
+ all_hidden_states += (hidden_states,)
542
+
543
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
544
+
545
+ if self.gradient_checkpointing and self.training:
546
+
547
+ def create_custom_forward(module):
548
+ def custom_forward(*inputs):
549
+ # None for past_key_value
550
+ return module(*inputs, output_attentions, None)
551
+
552
+ return custom_forward
553
+
554
+ layer_outputs = torch.utils.checkpoint.checkpoint(
555
+ create_custom_forward(decoder_layer),
556
+ hidden_states,
557
+ attention_mask,
558
+ position_ids,
559
+ None,
560
+ )
561
+ else:
562
+ layer_outputs = decoder_layer(
563
+ hidden_states,
564
+ attention_mask=attention_mask,
565
+ position_ids=position_ids,
566
+ past_key_value=past_key_value,
567
+ output_attentions=output_attentions,
568
+ use_cache=use_cache,
569
+ )
570
+
571
+ hidden_states = layer_outputs[0]
572
+
573
+ if use_cache:
574
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
575
+
576
+ if output_attentions:
577
+ all_self_attns += (layer_outputs[1],)
578
+
579
+ hidden_states = self.norm(hidden_states)
580
+
581
+ # add hidden states from the last decoder layer
582
+ if output_hidden_states:
583
+ all_hidden_states += (hidden_states,)
584
+
585
+ next_cache = next_decoder_cache if use_cache else None
586
+ if not return_dict:
587
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
588
+ return BaseModelOutputWithPast(
589
+ last_hidden_state=hidden_states,
590
+ past_key_values=next_cache,
591
+ hidden_states=all_hidden_states,
592
+ attentions=all_self_attns,
593
+ )
594
+
595
+
596
+ class MobiLlamaForCausalLM(MobiLlamaPreTrainedModel):
597
+ def __init__(self, config):
598
+ super().__init__(config)
599
+ self.model = MobiLlamaModel(config)
600
+
601
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
602
+
603
+ # Initialize weights and apply final processing
604
+ self.post_init()
605
+
606
+ def get_input_embeddings(self):
607
+ return self.model.embed_tokens
608
+
609
+ def set_input_embeddings(self, value):
610
+ self.model.embed_tokens = value
611
+
612
+ def get_output_embeddings(self):
613
+ return self.lm_head
614
+
615
+ def set_output_embeddings(self, new_embeddings):
616
+ self.lm_head = new_embeddings
617
+
618
+ def set_decoder(self, decoder):
619
+ self.model = decoder
620
+
621
+ def get_decoder(self):
622
+ return self.model
623
+
624
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
625
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
626
+ def forward(
627
+ self,
628
+ input_ids: torch.LongTensor = None,
629
+ attention_mask: Optional[torch.Tensor] = None,
630
+ position_ids: Optional[torch.LongTensor] = None,
631
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
632
+ inputs_embeds: Optional[torch.FloatTensor] = None,
633
+ labels: Optional[torch.LongTensor] = None,
634
+ use_cache: Optional[bool] = None,
635
+ output_attentions: Optional[bool] = None,
636
+ output_hidden_states: Optional[bool] = None,
637
+ return_dict: Optional[bool] = None,
638
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
639
+ r"""
640
+ Args:
641
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
642
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
643
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
644
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
645
+
646
+ Returns:
647
+
648
+ Example:
649
+
650
+ ```python
651
+ >>> from transformers import AutoTokenizer, MobiLlamaForCausalLM
652
+
653
+ >>> model = MobiLlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
654
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
655
+
656
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
657
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
658
+
659
+ >>> # Generate
660
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
661
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
662
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
663
+ ```"""
664
+
665
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
666
+ output_hidden_states = (
667
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
668
+ )
669
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
670
+
671
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
672
+ outputs = self.model(
673
+ input_ids=input_ids,
674
+ attention_mask=attention_mask,
675
+ position_ids=position_ids,
676
+ past_key_values=past_key_values,
677
+ inputs_embeds=inputs_embeds,
678
+ use_cache=use_cache,
679
+ output_attentions=output_attentions,
680
+ output_hidden_states=output_hidden_states,
681
+ return_dict=return_dict,
682
+ )
683
+
684
+ hidden_states = outputs[0]
685
+ logits = self.lm_head(hidden_states)
686
+
687
+ loss = None
688
+ if labels is not None:
689
+ # Shift so that tokens < n predict n
690
+ shift_logits = logits[..., :-1, :].contiguous()
691
+ shift_labels = labels[..., 1:].contiguous()
692
+ # Flatten the tokens
693
+ loss_fct = CrossEntropyLoss()
694
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
695
+ shift_labels = shift_labels.view(-1)
696
+ # Enable model parallelism
697
+ shift_labels = shift_labels.to(shift_logits.device)
698
+ loss = loss_fct(shift_logits, shift_labels)
699
+
700
+ if not return_dict:
701
+ output = (logits,) + outputs[1:]
702
+ return (loss,) + output if loss is not None else output
703
+
704
+ return CausalLMOutputWithPast(
705
+ loss=loss,
706
+ logits=logits,
707
+ past_key_values=outputs.past_key_values,
708
+ hidden_states=outputs.hidden_states,
709
+ attentions=outputs.attentions,
710
+ )
711
+
712
+ def prepare_inputs_for_generation(
713
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
714
+ ):
715
+ if past_key_values:
716
+ input_ids = input_ids[:, -1:]
717
+
718
+ position_ids = kwargs.get("position_ids", None)
719
+ if attention_mask is not None and position_ids is None:
720
+ # create position_ids on the fly for batch generation
721
+ position_ids = attention_mask.long().cumsum(-1) - 1
722
+ position_ids.masked_fill_(attention_mask == 0, 1)
723
+ if past_key_values:
724
+ position_ids = position_ids[:, -1].unsqueeze(-1)
725
+
726
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
727
+ if inputs_embeds is not None and past_key_values is None:
728
+ model_inputs = {"inputs_embeds": inputs_embeds}
729
+ else:
730
+ model_inputs = {"input_ids": input_ids}
731
+
732
+ model_inputs.update(
733
+ {
734
+ "position_ids": position_ids,
735
+ "past_key_values": past_key_values,
736
+ "use_cache": kwargs.get("use_cache"),
737
+ "attention_mask": attention_mask,
738
+ }
739
+ )
740
+ return model_inputs
741
+
742
+ @staticmethod
743
+ def _reorder_cache(past_key_values, beam_idx):
744
+ reordered_past = ()
745
+ for layer_past in past_key_values:
746
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
747
+ return reordered_past
748
+
749
+
750
+ @add_start_docstrings(
751
+ """
752
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
753
+
754
+ [`MobiLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
755
+ (e.g. GPT-2) do.
756
+
757
+ Since it does classification on the last token, it requires to know the position of the last token. If a
758
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
759
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
760
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
761
+ each row of the batch).
762
+ """,
763
+ MOBILLAMA_START_DOCSTRING,
764
+ )
765
+ class MobiLlamaForSequenceClassification(MobiLlamaPreTrainedModel):
766
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
767
+
768
+ def __init__(self, config):
769
+ super().__init__(config)
770
+ self.num_labels = config.num_labels
771
+ self.model = MobiLlamaModel(config)
772
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
773
+
774
+ # Initialize weights and apply final processing
775
+ self.post_init()
776
+
777
+ def get_input_embeddings(self):
778
+ return self.model.embed_tokens
779
+
780
+ def set_input_embeddings(self, value):
781
+ self.model.embed_tokens = value
782
+
783
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
784
+ def forward(
785
+ self,
786
+ input_ids: torch.LongTensor = None,
787
+ attention_mask: Optional[torch.Tensor] = None,
788
+ position_ids: Optional[torch.LongTensor] = None,
789
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
790
+ inputs_embeds: Optional[torch.FloatTensor] = None,
791
+ labels: Optional[torch.LongTensor] = None,
792
+ use_cache: Optional[bool] = None,
793
+ output_attentions: Optional[bool] = None,
794
+ output_hidden_states: Optional[bool] = None,
795
+ return_dict: Optional[bool] = None,
796
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
797
+ r"""
798
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
799
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
800
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
801
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
802
+ """
803
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
804
+
805
+ transformer_outputs = self.model(
806
+ input_ids,
807
+ attention_mask=attention_mask,
808
+ position_ids=position_ids,
809
+ past_key_values=past_key_values,
810
+ inputs_embeds=inputs_embeds,
811
+ use_cache=use_cache,
812
+ output_attentions=output_attentions,
813
+ output_hidden_states=output_hidden_states,
814
+ return_dict=return_dict,
815
+ )
816
+ hidden_states = transformer_outputs[0]
817
+ logits = self.score(hidden_states)
818
+
819
+ if input_ids is not None:
820
+ batch_size = input_ids.shape[0]
821
+ else:
822
+ batch_size = inputs_embeds.shape[0]
823
+
824
+ if self.config.pad_token_id is None and batch_size != 1:
825
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
826
+ if self.config.pad_token_id is None:
827
+ sequence_lengths = -1
828
+ else:
829
+ if input_ids is not None:
830
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
831
+ else:
832
+ sequence_lengths = -1
833
+
834
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
835
+
836
+ loss = None
837
+ if labels is not None:
838
+ labels = labels.to(logits.device)
839
+ if self.config.problem_type is None:
840
+ if self.num_labels == 1:
841
+ self.config.problem_type = "regression"
842
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
843
+ self.config.problem_type = "single_label_classification"
844
+ else:
845
+ self.config.problem_type = "multi_label_classification"
846
+
847
+ if self.config.problem_type == "regression":
848
+ loss_fct = MSELoss()
849
+ if self.num_labels == 1:
850
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
851
+ else:
852
+ loss = loss_fct(pooled_logits, labels)
853
+ elif self.config.problem_type == "single_label_classification":
854
+ loss_fct = CrossEntropyLoss()
855
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
856
+ elif self.config.problem_type == "multi_label_classification":
857
+ loss_fct = BCEWithLogitsLoss()
858
+ loss = loss_fct(pooled_logits, labels)
859
+ if not return_dict:
860
+ output = (pooled_logits,) + transformer_outputs[1:]
861
+ return ((loss,) + output) if loss is not None else output
862
+
863
+ return SequenceClassifierOutputWithPast(
864
+ loss=loss,
865
+ logits=pooled_logits,
866
+ past_key_values=transformer_outputs.past_key_values,
867
+ hidden_states=transformer_outputs.hidden_states,
868
+ attentions=transformer_outputs.attentions,
869
+ )
pytorch_model-00001-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:949d518238605532e8e94f17cc591cc3d7e6ce7bfe9b7d83862bc124e37ad74a
3
+ size 4784055476
pytorch_model-00002-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dfdf75e08ecb0e27c23b7168240c50cf16348a89e483d51ab37597cbd536e36
3
+ size 262145477
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5046119168
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00002-of-00002.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
14
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
15
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
16
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
17
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
18
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
19
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
20
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
21
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
22
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
23
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
24
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
25
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
26
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
27
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
28
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
29
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
30
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
31
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
32
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
33
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
34
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
35
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
36
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
37
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
38
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
39
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
40
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
41
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
42
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
43
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
44
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
45
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
46
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
47
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
48
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
49
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
50
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
51
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
52
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
53
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
54
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
55
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
56
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
57
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
58
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
59
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
60
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
61
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
62
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
63
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
64
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
65
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
66
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
67
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
68
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
69
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
70
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
71
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
72
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
73
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
74
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
75
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
76
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
77
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
78
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
79
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
80
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
81
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
82
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
83
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
84
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
85
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
86
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
87
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
88
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
89
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
90
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
91
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
92
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
93
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
94
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
95
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
96
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
97
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
98
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
99
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
100
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
101
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
102
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
103
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
104
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
105
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
106
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
107
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
108
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
109
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
110
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
111
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
112
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
113
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
114
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
115
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
116
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
117
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
118
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
119
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
120
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
121
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
122
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
123
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
124
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
125
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
126
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
127
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
128
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
129
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
130
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
131
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
132
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
133
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
134
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
135
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
136
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
137
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
138
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
139
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
140
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
141
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
142
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
143
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
144
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
145
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
146
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
147
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
148
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
149
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
150
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
151
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
152
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
153
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
154
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
155
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
156
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
157
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
158
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
159
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
160
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
161
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
162
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
163
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
164
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
165
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
166
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
167
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
168
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
169
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
170
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
171
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
172
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
173
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
174
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
175
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
176
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
177
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
178
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
179
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
180
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
181
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
182
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
183
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
184
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
185
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
186
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
187
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
188
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
189
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
190
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
191
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
192
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
193
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
194
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
195
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
196
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
197
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
198
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
199
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
200
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
201
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
202
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
203
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
204
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
205
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
206
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
207
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
208
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
209
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
210
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
211
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
212
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
213
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
214
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
215
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
216
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
217
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
218
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
219
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
220
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
221
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
222
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
223
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
224
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
225
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
226
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
227
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
228
+ "model.norm.weight": "pytorch_model-00001-of-00002.bin"
229
+ }
230
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
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": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "bos_token": "<s>",
31
+ "clean_up_tokenization_spaces": false,
32
+ "eos_token": "</s>",
33
+ "legacy": false,
34
+ "model_max_length": 1000000000000000019884624838656,
35
+ "pad_token": null,
36
+ "padding_side": "right",
37
+ "sp_model_kwargs": {},
38
+ "tokenizer_class": "LlamaTokenizer",
39
+ "unk_token": "<unk>",
40
+ "use_default_system_prompt": false
41
+ }