xrxing commited on
Commit
8d99091
·
verified ·
1 Parent(s): 47941bc

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ training_args.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
config.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/share/xingxingrun/prune350m_to_yulong/output_350_125_32gpu_ft/checkpoint-500000",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoModel": "inverse_llama2.LlamaModel",
10
+ "AutoModelForCausalLM": "inverse_llama2.LlamaForCausalLM"
11
+ },
12
+ "bos_token_id": 0,
13
+ "eos_token_id": 0,
14
+ "head_dim": 64,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 757,
17
+ "hidden_size_in": 320,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 966,
20
+ "kv_dims": [
21
+ 192,
22
+ 256,
23
+ 256,
24
+ 256,
25
+ 256,
26
+ 256,
27
+ 256,
28
+ 256,
29
+ 192,
30
+ 256,
31
+ 192,
32
+ 256,
33
+ 192,
34
+ 192,
35
+ 256,
36
+ 192,
37
+ 256,
38
+ 192,
39
+ 192,
40
+ 256,
41
+ 192,
42
+ 192,
43
+ 256,
44
+ 192,
45
+ 192,
46
+ 192,
47
+ 192,
48
+ 192,
49
+ 192,
50
+ 320,
51
+ 256,
52
+ 192
53
+ ],
54
+ "m_start": 250,
55
+ "max_position_embeddings": 2048,
56
+ "mlp_bias": false,
57
+ "model_type": "llama",
58
+ "num_attention_heads": 5,
59
+ "num_hidden_layers": 32,
60
+ "num_key_value_heads": 5,
61
+ "pretraining_tp": 1,
62
+ "rms_norm_eps": 1e-05,
63
+ "rope_scaling": null,
64
+ "rope_theta": 10000.0,
65
+ "step_quota": 9,
66
+ "tie_word_embeddings": true,
67
+ "torch_dtype": "bfloat16",
68
+ "transformers_version": "4.42.0",
69
+ "use_cache": true,
70
+ "vocab_size": 49152
71
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "transformers_version": "4.42.0"
6
+ }
inverse_llama2.py ADDED
@@ -0,0 +1,1551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ import math
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, StaticCache
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from transformers.models.llama.configuration_llama import LlamaConfig
52
+
53
+ if is_flash_attn_2_available():
54
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
55
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CONFIG_FOR_DOC = "LlamaConfig"
61
+
62
+ def _get_unpad_data(attention_mask):
63
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
64
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
65
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
66
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
67
+ return (
68
+ indices,
69
+ cu_seqlens,
70
+ max_seqlen_in_batch,
71
+ )
72
+
73
+
74
+ class LlamaRMSNorm(nn.Module):
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ LlamaRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ input_dtype = hidden_states.dtype
85
+ hidden_states = hidden_states.to(torch.float32)
86
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
87
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
88
+ return self.weight * hidden_states.to(input_dtype)
89
+
90
+
91
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
92
+
93
+
94
+ class LlamaRotaryEmbedding(nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
96
+ super().__init__()
97
+ self.scaling_factor = scaling_factor
98
+ self.dim = dim
99
+ self.max_position_embeddings = max_position_embeddings
100
+ self.base = base
101
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
102
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
103
+ # For BC we register cos and sin cached
104
+ self.max_seq_len_cached = max_position_embeddings
105
+
106
+ @torch.no_grad()
107
+ def forward(self, x, position_ids):
108
+ # x: [bs, num_attention_heads, seq_len, head_size]
109
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
110
+ position_ids_expanded = position_ids[:, None, :].float()
111
+ # Force float32 since bfloat16 loses precision on long contexts
112
+ # See https://github.com/huggingface/transformers/pull/29285
113
+ device_type = x.device.type
114
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
115
+ with torch.autocast(device_type=device_type, enabled=False):
116
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
117
+ emb = torch.cat((freqs, freqs), dim=-1)
118
+ cos = emb.cos()
119
+ sin = emb.sin()
120
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
121
+
122
+
123
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
124
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
125
+
126
+ def forward(self, x, position_ids):
127
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
128
+ position_ids = position_ids.float() / self.scaling_factor
129
+ cos, sin = super().forward(x, position_ids)
130
+ return cos, sin
131
+
132
+
133
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
134
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
135
+
136
+ def forward(self, x, position_ids):
137
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
138
+ seq_len = torch.max(position_ids) + 1
139
+ if seq_len > self.max_position_embeddings:
140
+ base = self.base * (
141
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
142
+ ) ** (self.dim / (self.dim - 2))
143
+ inv_freq = 1.0 / (
144
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
145
+ )
146
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
147
+
148
+ cos, sin = super().forward(x, position_ids)
149
+ return cos, sin
150
+
151
+
152
+ def rotate_half(x):
153
+ """Rotates half the hidden dims of the input."""
154
+ x1 = x[..., : x.shape[-1] // 2]
155
+ x2 = x[..., x.shape[-1] // 2 :]
156
+ return torch.cat((-x2, x1), dim=-1)
157
+
158
+
159
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
160
+ """Applies Rotary Position Embedding to the query and key tensors.
161
+
162
+ Args:
163
+ q (`torch.Tensor`): The query tensor.
164
+ k (`torch.Tensor`): The key tensor.
165
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
166
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
167
+ position_ids (`torch.Tensor`, *optional*):
168
+ Deprecated and unused.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos.unsqueeze(unsqueeze_dim)
180
+ sin = sin.unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ class LlamaMLP(nn.Module):
187
+ def __init__(self, config):
188
+ super().__init__()
189
+ self.config = config
190
+ self.hidden_size = config.hidden_size
191
+ self.intermediate_size = config.intermediate_size
192
+
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
196
+
197
+ self.act_fn = ACT2FN[config.hidden_act]
198
+
199
+ def forward(self, x):
200
+ if self.config.pretraining_tp > 1:
201
+ slice = self.intermediate_size // self.config.pretraining_tp
202
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
203
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
204
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
205
+
206
+ gate_proj = torch.cat(
207
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
208
+ )
209
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
210
+
211
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
212
+ down_proj = [
213
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
214
+ ]
215
+ down_proj = sum(down_proj)
216
+ else:
217
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
218
+
219
+ return down_proj
220
+
221
+
222
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
223
+ """
224
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
225
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
226
+ """
227
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
228
+ if n_rep == 1:
229
+ return hidden_states
230
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
231
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
232
+
233
+ def repeat_kv_idx(hidden_states: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
234
+
235
+ # batch, num_key_value_heads, slen, head_dim = hidden_states.shape
236
+ # heads = idx.shape
237
+
238
+ idx = idx.to(torch.int)
239
+
240
+ hidden_states = hidden_states[:, idx, :, :]
241
+
242
+ return hidden_states #.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
243
+
244
+ class LlamaAttention(nn.Module):
245
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
246
+
247
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
248
+ super().__init__()
249
+ self.config = config
250
+ self.layer_idx = layer_idx
251
+ if layer_idx is None:
252
+ logger.warning_once(
253
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
254
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
255
+ "when creating this class."
256
+ )
257
+
258
+ self.attention_dropout = config.attention_dropout
259
+ self.hidden_size = config.hidden_size
260
+ self.hidden_size_in = config.hidden_size_in
261
+
262
+ self.num_heads = config.num_attention_heads
263
+ self.head_dim = self.hidden_size_in // self.num_heads
264
+ self.num_key_value_heads = config.num_key_value_heads
265
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
266
+ self.max_position_embeddings = config.max_position_embeddings
267
+ self.rope_theta = config.rope_theta
268
+ self.is_causal = True
269
+
270
+ self.kv_heads = config.kv_dims[layer_idx] //64
271
+
272
+ if (self.head_dim * self.num_heads) != self.hidden_size_in:
273
+ raise ValueError(
274
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size_in}"
275
+ f" and `num_heads`: {self.num_heads})."
276
+ )
277
+
278
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
279
+ self.k_proj = nn.Linear(self.hidden_size, config.kv_dims[layer_idx], bias=config.attention_bias)
280
+ self.v_proj = nn.Linear(self.hidden_size, config.kv_dims[layer_idx], bias=config.attention_bias)
281
+ self.o_proj = nn.Linear(self.hidden_size_in, self.hidden_size, bias=config.attention_bias)
282
+
283
+ kv_idx = torch.zeros(self.num_heads)
284
+ self.register_buffer('kv_idx', kv_idx)
285
+
286
+ self._init_rope()
287
+
288
+ def _init_rope(self):
289
+ if self.config.rope_scaling is None:
290
+ self.rotary_emb = LlamaRotaryEmbedding(
291
+ self.head_dim,
292
+ max_position_embeddings=self.max_position_embeddings,
293
+ base=self.rope_theta,
294
+ )
295
+ else:
296
+ scaling_type = self.config.rope_scaling["type"]
297
+ scaling_factor = self.config.rope_scaling["factor"]
298
+ if scaling_type == "linear":
299
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
300
+ self.head_dim,
301
+ max_position_embeddings=self.max_position_embeddings,
302
+ scaling_factor=scaling_factor,
303
+ base=self.rope_theta,
304
+ )
305
+ elif scaling_type == "dynamic":
306
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
307
+ self.head_dim,
308
+ max_position_embeddings=self.max_position_embeddings,
309
+ scaling_factor=scaling_factor,
310
+ base=self.rope_theta,
311
+ )
312
+ else:
313
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
314
+
315
+ def forward(
316
+ self,
317
+ hidden_states: torch.Tensor,
318
+ attention_mask: Optional[torch.Tensor] = None,
319
+ position_ids: Optional[torch.LongTensor] = None,
320
+ past_key_value: Optional[Cache] = None,
321
+ output_attentions: bool = False,
322
+ use_cache: bool = False,
323
+ cache_position: Optional[torch.LongTensor] = None,
324
+ **kwargs,
325
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
326
+ bsz, q_len, _ = hidden_states.size()
327
+
328
+ if self.config.pretraining_tp > 1:
329
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
330
+ query_slices = self.q_proj.weight.split(
331
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
332
+ )
333
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
334
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
335
+
336
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
337
+ query_states = torch.cat(query_states, dim=-1)
338
+
339
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
340
+ key_states = torch.cat(key_states, dim=-1)
341
+
342
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
343
+ value_states = torch.cat(value_states, dim=-1)
344
+
345
+ else:
346
+ query_states = self.q_proj(hidden_states)
347
+ key_states = self.k_proj(hidden_states)
348
+ value_states = self.v_proj(hidden_states)
349
+
350
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
351
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
352
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
353
+
354
+ cos, sin = self.rotary_emb(value_states, position_ids)
355
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
356
+
357
+ if past_key_value is not None:
358
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
359
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
360
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
361
+
362
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
363
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
364
+
365
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
366
+
367
+ # breakpoint()
368
+ if attention_mask is not None: # no matter the length, we just slice it
369
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
370
+ attn_weights = attn_weights + causal_mask
371
+
372
+ # upcast attention to fp32
373
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
374
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
375
+ attn_output = torch.matmul(attn_weights, value_states)
376
+
377
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
378
+ raise ValueError(
379
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
380
+ f" {attn_output.size()}"
381
+ )
382
+
383
+ attn_output = attn_output.transpose(1, 2).contiguous()
384
+
385
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_in)
386
+
387
+ if self.config.pretraining_tp > 1:
388
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
389
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
390
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
391
+ else:
392
+ attn_output = self.o_proj(attn_output)
393
+
394
+ if not output_attentions:
395
+ attn_weights = None
396
+
397
+ return attn_output, attn_weights, past_key_value
398
+
399
+
400
+ class LlamaFlashAttention2(LlamaAttention):
401
+ """
402
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
403
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
404
+ flash attention and deal with padding tokens in case the input contains any of them.
405
+ """
406
+
407
+ def __init__(self, *args, **kwargs):
408
+ super().__init__(*args, **kwargs)
409
+
410
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
411
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
412
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
413
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
414
+
415
+ # kv_idx = torch.zeros(self.config.kv_dims[self.layer_idx]//64, dtype=torch.bool)
416
+ # self.register_buffer('kv_idx', kv_idx)
417
+
418
+ def forward(
419
+ self,
420
+ hidden_states: torch.Tensor,
421
+ attention_mask: Optional[torch.LongTensor] = None,
422
+ position_ids: Optional[torch.LongTensor] = None,
423
+ past_key_value: Optional[Cache] = None,
424
+ output_attentions: bool = False,
425
+ use_cache: bool = False,
426
+ cache_position: Optional[torch.LongTensor] = None,
427
+ **kwargs,
428
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
429
+ if isinstance(past_key_value, StaticCache):
430
+ raise ValueError(
431
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
432
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
433
+ )
434
+
435
+ output_attentions = False
436
+
437
+ bsz, q_len, _ = hidden_states.size()
438
+
439
+ query_states = self.q_proj(hidden_states)
440
+ key_states = self.k_proj(hidden_states)
441
+ value_states = self.v_proj(hidden_states)
442
+
443
+ # Flash attention requires the input to have the shape
444
+ # batch_size x seq_length x head_dim x hidden_dim
445
+ # therefore we just need to keep the original shape
446
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
447
+ key_states = key_states.view(bsz, q_len, self.kv_heads, self.head_dim).transpose(1, 2)
448
+ value_states = value_states.view(bsz, q_len, self.kv_heads, self.head_dim).transpose(1, 2)
449
+
450
+ cos, sin = self.rotary_emb(value_states, position_ids)
451
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
452
+
453
+ ##########################
454
+ key_states, value_states = repeat_kv_idx(key_states, self.kv_idx), repeat_kv_idx(value_states, self.kv_idx)
455
+ ##########################
456
+
457
+ if past_key_value is not None:
458
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
459
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
460
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
461
+
462
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
463
+ # to be able to avoid many of these transpose/reshape/view.
464
+ query_states = query_states.transpose(1, 2)
465
+ key_states = key_states.transpose(1, 2)
466
+ value_states = value_states.transpose(1, 2)
467
+
468
+ dropout_rate = self.attention_dropout if self.training else 0.0
469
+
470
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
471
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
472
+ # cast them back in the correct dtype just to be sure everything works as expected.
473
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
474
+ # in fp32. (LlamaRMSNorm handles it correctly)
475
+
476
+ input_dtype = query_states.dtype
477
+ if input_dtype == torch.float32:
478
+ if torch.is_autocast_enabled():
479
+ target_dtype = torch.get_autocast_gpu_dtype()
480
+ # Handle the case where the model is quantized
481
+ elif hasattr(self.config, "_pre_quantization_dtype"):
482
+ target_dtype = self.config._pre_quantization_dtype
483
+ else:
484
+ target_dtype = self.q_proj.weight.dtype
485
+
486
+ logger.warning_once(
487
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
488
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
489
+ f" {target_dtype}."
490
+ )
491
+
492
+ query_states = query_states.to(target_dtype)
493
+ key_states = key_states.to(target_dtype)
494
+ value_states = value_states.to(target_dtype)
495
+
496
+ attn_output = self._flash_attention_forward(
497
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
498
+ )
499
+
500
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_in).contiguous()
501
+ attn_output = self.o_proj(attn_output)
502
+
503
+ if not output_attentions:
504
+ attn_weights = None
505
+
506
+ return attn_output, attn_weights, past_key_value
507
+
508
+ def _flash_attention_forward(
509
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
510
+ ):
511
+ """
512
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
513
+ first unpad the input, then computes the attention scores and pad the final attention scores.
514
+
515
+ Args:
516
+ query_states (`torch.Tensor`):
517
+ Input query states to be passed to Flash Attention API
518
+ key_states (`torch.Tensor`):
519
+ Input key states to be passed to Flash Attention API
520
+ value_states (`torch.Tensor`):
521
+ Input value states to be passed to Flash Attention API
522
+ attention_mask (`torch.Tensor`):
523
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
524
+ position of padding tokens and 1 for the position of non-padding tokens.
525
+ dropout (`float`):
526
+ Attention dropout
527
+ softmax_scale (`float`, *optional*):
528
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
529
+ """
530
+ if not self._flash_attn_uses_top_left_mask:
531
+ causal = self.is_causal
532
+ else:
533
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
534
+ causal = self.is_causal and query_length != 1
535
+
536
+ # Contains at least one padding token in the sequence
537
+ if attention_mask is not None:
538
+ batch_size = query_states.shape[0]
539
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
540
+ query_states, key_states, value_states, attention_mask, query_length
541
+ )
542
+
543
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
544
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
545
+
546
+ attn_output_unpad = flash_attn_varlen_func(
547
+ query_states,
548
+ key_states,
549
+ value_states,
550
+ cu_seqlens_q=cu_seqlens_q,
551
+ cu_seqlens_k=cu_seqlens_k,
552
+ max_seqlen_q=max_seqlen_in_batch_q,
553
+ max_seqlen_k=max_seqlen_in_batch_k,
554
+ dropout_p=dropout,
555
+ softmax_scale=softmax_scale,
556
+ causal=causal,
557
+ )
558
+
559
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
560
+ else:
561
+ attn_output = flash_attn_func(
562
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
563
+ )
564
+
565
+ return attn_output
566
+
567
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
568
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
569
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
570
+
571
+ key_layer = index_first_axis(
572
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
573
+ )
574
+ value_layer = index_first_axis(
575
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
576
+ )
577
+ if query_length == kv_seq_len:
578
+ query_layer = index_first_axis(
579
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
580
+ )
581
+ cu_seqlens_q = cu_seqlens_k
582
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
583
+ indices_q = indices_k
584
+ elif query_length == 1:
585
+ max_seqlen_in_batch_q = 1
586
+ cu_seqlens_q = torch.arange(
587
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
588
+ ) # There is a memcpy here, that is very bad.
589
+ indices_q = cu_seqlens_q[:-1]
590
+ query_layer = query_layer.squeeze(1)
591
+ else:
592
+ # The -q_len: slice assumes left padding.
593
+ attention_mask = attention_mask[:, -query_length:]
594
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
595
+
596
+ return (
597
+ query_layer,
598
+ key_layer,
599
+ value_layer,
600
+ indices_q,
601
+ (cu_seqlens_q, cu_seqlens_k),
602
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
603
+ )
604
+
605
+
606
+ class LlamaSdpaAttention(LlamaAttention):
607
+ """
608
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
609
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
610
+ SDPA API.
611
+ """
612
+
613
+ # Adapted from LlamaAttention.forward
614
+ def forward(
615
+ self,
616
+ hidden_states: torch.Tensor,
617
+ attention_mask: Optional[torch.Tensor] = None,
618
+ position_ids: Optional[torch.LongTensor] = None,
619
+ past_key_value: Optional[Cache] = None,
620
+ output_attentions: bool = False,
621
+ use_cache: bool = False,
622
+ cache_position: Optional[torch.LongTensor] = None,
623
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
624
+ if output_attentions:
625
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
626
+ logger.warning_once(
627
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
628
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
629
+ )
630
+ return super().forward(
631
+ hidden_states=hidden_states,
632
+ attention_mask=attention_mask,
633
+ position_ids=position_ids,
634
+ past_key_value=past_key_value,
635
+ output_attentions=output_attentions,
636
+ use_cache=use_cache,
637
+ cache_position=cache_position,
638
+ )
639
+
640
+ bsz, q_len, _ = hidden_states.size()
641
+
642
+ query_states = self.q_proj(hidden_states)
643
+ key_states = self.k_proj(hidden_states)
644
+ value_states = self.v_proj(hidden_states)
645
+
646
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
647
+ key_states = key_states.view(bsz, q_len, self.kv_heads, self.head_dim).transpose(1, 2)
648
+ value_states = value_states.view(bsz, q_len, self.kv_heads, self.head_dim).transpose(1, 2)
649
+
650
+ cos, sin = self.rotary_emb(value_states, position_ids)
651
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
652
+
653
+ if past_key_value is not None:
654
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
655
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
656
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
657
+
658
+ # key_states = repeat_kv(key_states, self.num_key_value_groups)
659
+ # value_states = repeat_kv(value_states, self.num_key_value_groups)
660
+ ##########################
661
+ key_states, value_states = repeat_kv_idx(key_states, self.kv_idx), repeat_kv_idx(value_states, self.kv_idx)
662
+ ##########################
663
+
664
+ causal_mask = attention_mask
665
+ if attention_mask is not None:
666
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
667
+
668
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
669
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
670
+ if query_states.device.type == "cuda" and causal_mask is not None:
671
+ query_states = query_states.contiguous()
672
+ key_states = key_states.contiguous()
673
+ value_states = value_states.contiguous()
674
+
675
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
676
+ # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
677
+ is_causal = True if causal_mask is None and q_len > 1 else False
678
+
679
+ # breakpoint()
680
+
681
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
682
+ query_states,
683
+ key_states,
684
+ value_states,
685
+ attn_mask=causal_mask,
686
+ dropout_p=self.attention_dropout if self.training else 0.0,
687
+ is_causal=is_causal,
688
+ )
689
+
690
+ attn_output = attn_output.transpose(1, 2).contiguous()
691
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size_in)
692
+
693
+ attn_output = self.o_proj(attn_output)
694
+
695
+ return attn_output, None, past_key_value
696
+
697
+
698
+ LLAMA_ATTENTION_CLASSES = {
699
+ "eager": LlamaAttention,
700
+ "flash_attention_2": LlamaFlashAttention2,
701
+ "sdpa": LlamaSdpaAttention,
702
+ }
703
+
704
+
705
+ class LlamaDecoderLayer(nn.Module):
706
+ def __init__(self, config: LlamaConfig, layer_idx: int):
707
+ super().__init__()
708
+ self.hidden_size = config.hidden_size
709
+
710
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
711
+
712
+ self.mlp = LlamaMLP(config)
713
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
714
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
715
+
716
+ def forward(
717
+ self,
718
+ hidden_states: torch.Tensor,
719
+ attention_mask: Optional[torch.Tensor] = None,
720
+ position_ids: Optional[torch.LongTensor] = None,
721
+ past_key_value: Optional[Cache] = None,
722
+ output_attentions: Optional[bool] = False,
723
+ use_cache: Optional[bool] = False,
724
+ cache_position: Optional[torch.LongTensor] = None,
725
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
726
+ """
727
+ Args:
728
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
729
+ attention_mask (`torch.FloatTensor`, *optional*):
730
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
731
+ query_sequence_length, key_sequence_length)` if default attention is used.
732
+ output_attentions (`bool`, *optional*):
733
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
734
+ returned tensors for more detail.
735
+ use_cache (`bool`, *optional*):
736
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
737
+ (see `past_key_values`).
738
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
739
+ """
740
+ residual = hidden_states
741
+
742
+ hidden_states = self.input_layernorm(hidden_states)
743
+
744
+ # Self Attention
745
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
746
+ hidden_states=hidden_states,
747
+ attention_mask=attention_mask,
748
+ position_ids=position_ids,
749
+ past_key_value=past_key_value,
750
+ output_attentions=output_attentions,
751
+ use_cache=use_cache,
752
+ cache_position=cache_position,
753
+ )
754
+ hidden_states = residual + hidden_states
755
+
756
+ # Fully Connected
757
+ residual = hidden_states
758
+ hidden_states = self.post_attention_layernorm(hidden_states)
759
+ hidden_states = self.mlp(hidden_states)
760
+ hidden_states = residual + hidden_states
761
+
762
+ outputs = (hidden_states,)
763
+
764
+ if output_attentions:
765
+ outputs += (self_attn_weights,)
766
+
767
+ if use_cache:
768
+ outputs += (present_key_value,)
769
+
770
+ return outputs
771
+
772
+
773
+ LLAMA_START_DOCSTRING = r"""
774
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
775
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
776
+ etc.)
777
+
778
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
779
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
780
+ and behavior.
781
+
782
+ Parameters:
783
+ config ([`LlamaConfig`]):
784
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
785
+ load the weights associated with the model, only the configuration. Check out the
786
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
787
+ """
788
+
789
+
790
+ @add_start_docstrings(
791
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
792
+ LLAMA_START_DOCSTRING,
793
+ )
794
+ class LlamaPreTrainedModel(PreTrainedModel):
795
+ config_class = LlamaConfig
796
+ base_model_prefix = "model"
797
+ supports_gradient_checkpointing = True
798
+ _no_split_modules = ["LlamaDecoderLayer"]
799
+ _skip_keys_device_placement = ["past_key_values"]
800
+ _supports_flash_attn_2 = True
801
+ _supports_sdpa = True
802
+ _supports_cache_class = True
803
+ _supports_static_cache = True
804
+
805
+ def _init_weights(self, module):
806
+ std = self.config.initializer_range
807
+ if isinstance(module, nn.Linear):
808
+ module.weight.data.normal_(mean=0.0, std=std)
809
+ if module.bias is not None:
810
+ module.bias.data.zero_()
811
+ elif isinstance(module, nn.Embedding):
812
+ module.weight.data.normal_(mean=0.0, std=std)
813
+ if module.padding_idx is not None:
814
+ module.weight.data[module.padding_idx].zero_()
815
+
816
+
817
+ LLAMA_INPUTS_DOCSTRING = r"""
818
+ Args:
819
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
820
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
821
+ it.
822
+
823
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
824
+ [`PreTrainedTokenizer.__call__`] for details.
825
+
826
+ [What are input IDs?](../glossary#input-ids)
827
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
828
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
829
+
830
+ - 1 for tokens that are **not masked**,
831
+ - 0 for tokens that are **masked**.
832
+
833
+ [What are attention masks?](../glossary#attention-mask)
834
+
835
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
836
+ [`PreTrainedTokenizer.__call__`] for details.
837
+
838
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
839
+ `past_key_values`).
840
+
841
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
842
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
843
+ information on the default strategy.
844
+
845
+ - 1 indicates the head is **not masked**,
846
+ - 0 indicates the head is **masked**.
847
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
848
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
849
+ config.n_positions - 1]`.
850
+
851
+ [What are position IDs?](../glossary#position-ids)
852
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
853
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
854
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
855
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
856
+
857
+ Two formats are allowed:
858
+ - a [`~cache_utils.Cache`] instance;
859
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
860
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
861
+ cache format.
862
+
863
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
864
+ legacy cache format will be returned.
865
+
866
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
867
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
868
+ of shape `(batch_size, sequence_length)`.
869
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
870
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
871
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
872
+ model's internal embedding lookup matrix.
873
+ use_cache (`bool`, *optional*):
874
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
875
+ `past_key_values`).
876
+ output_attentions (`bool`, *optional*):
877
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
878
+ tensors for more detail.
879
+ output_hidden_states (`bool`, *optional*):
880
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
881
+ more detail.
882
+ return_dict (`bool`, *optional*):
883
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
884
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
885
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
886
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
887
+ the complete sequence length.
888
+ """
889
+
890
+
891
+ @add_start_docstrings(
892
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
893
+ LLAMA_START_DOCSTRING,
894
+ )
895
+ class LlamaModel(LlamaPreTrainedModel):
896
+ """
897
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
898
+
899
+ Args:
900
+ config: LlamaConfig
901
+ """
902
+
903
+ def __init__(self, config: LlamaConfig):
904
+ super().__init__(config)
905
+ self.padding_idx = config.pad_token_id
906
+ self.vocab_size = config.vocab_size
907
+
908
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
909
+ self.layers = nn.ModuleList(
910
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
911
+ )
912
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
913
+ self.gradient_checkpointing = False
914
+
915
+ # Initialize weights and apply final processing
916
+ self.post_init()
917
+
918
+ def get_input_embeddings(self):
919
+ return self.embed_tokens
920
+
921
+ def set_input_embeddings(self, value):
922
+ self.embed_tokens = value
923
+
924
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
925
+ def forward(
926
+ self,
927
+ input_ids: torch.LongTensor = None,
928
+ attention_mask: Optional[torch.Tensor] = None,
929
+ position_ids: Optional[torch.LongTensor] = None,
930
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
931
+ inputs_embeds: Optional[torch.FloatTensor] = None,
932
+ use_cache: Optional[bool] = None,
933
+ output_attentions: Optional[bool] = None,
934
+ output_hidden_states: Optional[bool] = None,
935
+ return_dict: Optional[bool] = None,
936
+ cache_position: Optional[torch.LongTensor] = None,
937
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
938
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
939
+ output_hidden_states = (
940
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
941
+ )
942
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
943
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
944
+
945
+ if (input_ids is None) ^ (inputs_embeds is not None):
946
+ raise ValueError(
947
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
948
+ )
949
+
950
+ if self.gradient_checkpointing and self.training and use_cache:
951
+ logger.warning_once(
952
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
953
+ )
954
+ use_cache = False
955
+
956
+ if inputs_embeds is None:
957
+ inputs_embeds = self.embed_tokens(input_ids)
958
+
959
+ return_legacy_cache = False
960
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
961
+ return_legacy_cache = True
962
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
963
+
964
+ if cache_position is None:
965
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
966
+ cache_position = torch.arange(
967
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
968
+ )
969
+ if position_ids is None:
970
+ position_ids = cache_position.unsqueeze(0)
971
+
972
+ causal_mask = self._update_causal_mask(
973
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
974
+ )
975
+
976
+ # embed positions
977
+ hidden_states = inputs_embeds
978
+
979
+ # decoder layers
980
+ all_hidden_states = () if output_hidden_states else None
981
+ all_self_attns = () if output_attentions else None
982
+ next_decoder_cache = None
983
+
984
+ for decoder_layer in self.layers:
985
+ if output_hidden_states:
986
+ all_hidden_states += (hidden_states,)
987
+
988
+ if self.gradient_checkpointing and self.training:
989
+ layer_outputs = self._gradient_checkpointing_func(
990
+ decoder_layer.__call__,
991
+ hidden_states,
992
+ causal_mask,
993
+ position_ids,
994
+ past_key_values,
995
+ output_attentions,
996
+ use_cache,
997
+ cache_position,
998
+ )
999
+ else:
1000
+ layer_outputs = decoder_layer(
1001
+ hidden_states,
1002
+ attention_mask=causal_mask,
1003
+ position_ids=position_ids,
1004
+ past_key_value=past_key_values,
1005
+ output_attentions=output_attentions,
1006
+ use_cache=use_cache,
1007
+ cache_position=cache_position,
1008
+ )
1009
+
1010
+ hidden_states = layer_outputs[0]
1011
+
1012
+ if use_cache:
1013
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1014
+
1015
+ if output_attentions:
1016
+ all_self_attns += (layer_outputs[1],)
1017
+
1018
+ hidden_states = self.norm(hidden_states)
1019
+
1020
+ # add hidden states from the last decoder layer
1021
+ if output_hidden_states:
1022
+ all_hidden_states += (hidden_states,)
1023
+
1024
+ next_cache = next_decoder_cache if use_cache else None
1025
+ if return_legacy_cache:
1026
+ next_cache = next_cache.to_legacy_cache()
1027
+
1028
+ if not return_dict:
1029
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1030
+ return BaseModelOutputWithPast(
1031
+ last_hidden_state=hidden_states,
1032
+ past_key_values=next_cache,
1033
+ hidden_states=all_hidden_states,
1034
+ attentions=all_self_attns,
1035
+ )
1036
+
1037
+ def _update_causal_mask(
1038
+ self,
1039
+ attention_mask: torch.Tensor,
1040
+ input_tensor: torch.Tensor,
1041
+ cache_position: torch.Tensor,
1042
+ past_key_values: Cache,
1043
+ output_attentions: bool,
1044
+ ):
1045
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1046
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1047
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1048
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1049
+
1050
+ if self.config._attn_implementation == "flash_attention_2":
1051
+ if attention_mask is not None and 0.0 in attention_mask:
1052
+ return attention_mask
1053
+ return None
1054
+
1055
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1056
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1057
+ # to infer the attention mask.
1058
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1059
+ using_static_cache = isinstance(past_key_values, StaticCache)
1060
+
1061
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1062
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1063
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1064
+ attention_mask,
1065
+ inputs_embeds=input_tensor,
1066
+ past_key_values_length=past_seen_tokens,
1067
+ is_training=self.training,
1068
+ ):
1069
+ return None
1070
+
1071
+ dtype, device = input_tensor.dtype, input_tensor.device
1072
+ min_dtype = torch.finfo(dtype).min
1073
+ sequence_length = input_tensor.shape[1]
1074
+ if using_static_cache:
1075
+ target_length = past_key_values.get_max_length()
1076
+ else:
1077
+ target_length = (
1078
+ attention_mask.shape[-1]
1079
+ if isinstance(attention_mask, torch.Tensor)
1080
+ else past_seen_tokens + sequence_length + 1
1081
+ )
1082
+
1083
+ if attention_mask is not None and attention_mask.dim() == 4:
1084
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1085
+ if attention_mask.max() != 0:
1086
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1087
+ causal_mask = attention_mask
1088
+ else:
1089
+ causal_mask = torch.full(
1090
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1091
+ )
1092
+ if sequence_length != 1:
1093
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1094
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1095
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1096
+ if attention_mask is not None:
1097
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1098
+ mask_length = attention_mask.shape[-1]
1099
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1100
+ padding_mask = padding_mask == 0
1101
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1102
+ padding_mask, min_dtype
1103
+ )
1104
+ if (
1105
+ self.config._attn_implementation == "sdpa"
1106
+ and attention_mask is not None
1107
+ and attention_mask.device.type == "cuda"
1108
+ and not output_attentions
1109
+ ):
1110
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1111
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1112
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1113
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1114
+
1115
+ return causal_mask
1116
+
1117
+
1118
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1119
+ _tied_weights_keys = ["lm_head.weight"]
1120
+
1121
+ def __init__(self, config):
1122
+ super().__init__(config)
1123
+ self.model = LlamaModel(config)
1124
+ self.vocab_size = config.vocab_size
1125
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1126
+
1127
+ # Initialize weights and apply final processing
1128
+ self.post_init()
1129
+
1130
+ def get_input_embeddings(self):
1131
+ return self.model.embed_tokens
1132
+
1133
+ def set_input_embeddings(self, value):
1134
+ self.model.embed_tokens = value
1135
+
1136
+ def get_output_embeddings(self):
1137
+ return self.lm_head
1138
+
1139
+ def set_output_embeddings(self, new_embeddings):
1140
+ self.lm_head = new_embeddings
1141
+
1142
+ def set_decoder(self, decoder):
1143
+ self.model = decoder
1144
+
1145
+ def get_decoder(self):
1146
+ return self.model
1147
+
1148
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1149
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1150
+ def forward(
1151
+ self,
1152
+ input_ids: torch.LongTensor = None,
1153
+ attention_mask: Optional[torch.Tensor] = None,
1154
+ position_ids: Optional[torch.LongTensor] = None,
1155
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1156
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1157
+ labels: Optional[torch.LongTensor] = None,
1158
+ use_cache: Optional[bool] = None,
1159
+ output_attentions: Optional[bool] = None,
1160
+ output_hidden_states: Optional[bool] = None,
1161
+ return_dict: Optional[bool] = None,
1162
+ cache_position: Optional[torch.LongTensor] = None,
1163
+ global_step = None
1164
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1165
+ r"""
1166
+ Args:
1167
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1168
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1169
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1170
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1171
+
1172
+ Returns:
1173
+
1174
+ Example:
1175
+
1176
+ ```python
1177
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1178
+
1179
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1180
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1181
+
1182
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1183
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1184
+
1185
+ >>> # Generate
1186
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1187
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1188
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1189
+ ```"""
1190
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1191
+ output_hidden_states = (
1192
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1193
+ )
1194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1195
+
1196
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1197
+ outputs = self.model(
1198
+ input_ids=input_ids,
1199
+ attention_mask=attention_mask,
1200
+ position_ids=position_ids,
1201
+ past_key_values=past_key_values,
1202
+ inputs_embeds=inputs_embeds,
1203
+ use_cache=use_cache,
1204
+ output_attentions=output_attentions,
1205
+ output_hidden_states=output_hidden_states,
1206
+ return_dict=return_dict,
1207
+ cache_position=cache_position,
1208
+ )
1209
+
1210
+ hidden_states = outputs[0]
1211
+ if self.config.pretraining_tp > 1:
1212
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1213
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1214
+ logits = torch.cat(logits, dim=-1)
1215
+ else:
1216
+ logits = self.lm_head(hidden_states)
1217
+ logits = logits.float()
1218
+
1219
+ loss = None
1220
+ if labels is not None:
1221
+ # Shift so that tokens < n predict n
1222
+ shift_logits = logits[..., :-1, :].contiguous()
1223
+ shift_labels = labels[..., 1:].contiguous()
1224
+ # Flatten the tokens
1225
+ loss_fct = CrossEntropyLoss()
1226
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1227
+ shift_labels = shift_labels.view(-1)
1228
+ # Enable model parallelism
1229
+ shift_labels = shift_labels.to(shift_logits.device)
1230
+ loss = loss_fct(shift_logits, shift_labels)
1231
+
1232
+ if not return_dict:
1233
+ output = (logits,) + outputs[1:]
1234
+ return (loss,) + output if loss is not None else output
1235
+
1236
+ return CausalLMOutputWithPast(
1237
+ loss=loss,
1238
+ logits=logits,
1239
+ past_key_values=outputs.past_key_values,
1240
+ hidden_states=outputs.hidden_states,
1241
+ attentions=outputs.attentions,
1242
+ )
1243
+
1244
+ def prepare_inputs_for_generation(
1245
+ self,
1246
+ input_ids,
1247
+ past_key_values=None,
1248
+ attention_mask=None,
1249
+ inputs_embeds=None,
1250
+ cache_position=None,
1251
+ use_cache=True,
1252
+ **kwargs,
1253
+ ):
1254
+ past_length = 0
1255
+ if past_key_values is not None:
1256
+ if isinstance(past_key_values, Cache):
1257
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1258
+ max_cache_length = (
1259
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1260
+ if past_key_values.get_max_length() is not None
1261
+ else None
1262
+ )
1263
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1264
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1265
+ else:
1266
+ cache_length = past_length = past_key_values[0][0].shape[2]
1267
+ max_cache_length = None
1268
+
1269
+ # Keep only the unprocessed tokens:
1270
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1271
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1272
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1273
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1274
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1275
+ # input_ids based on the past_length.
1276
+ elif past_length < input_ids.shape[1]:
1277
+ input_ids = input_ids[:, past_length:]
1278
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1279
+
1280
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1281
+ if (
1282
+ max_cache_length is not None
1283
+ and attention_mask is not None
1284
+ and cache_length + input_ids.shape[1] > max_cache_length
1285
+ ):
1286
+ attention_mask = attention_mask[:, -max_cache_length:]
1287
+
1288
+ position_ids = kwargs.get("position_ids", None)
1289
+ if attention_mask is not None and position_ids is None:
1290
+ # create position_ids on the fly for batch generation
1291
+ position_ids = attention_mask.long().cumsum(-1) - 1
1292
+ position_ids.masked_fill_(attention_mask == 0, 1)
1293
+ if past_key_values:
1294
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1295
+
1296
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1297
+ if inputs_embeds is not None and past_key_values is None:
1298
+ model_inputs = {"inputs_embeds": inputs_embeds}
1299
+ else:
1300
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1301
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1302
+ # TODO: use `next_tokens` directly instead.
1303
+ model_inputs = {"input_ids": input_ids.contiguous()}
1304
+
1305
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1306
+ if cache_position is None:
1307
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1308
+ elif use_cache:
1309
+ cache_position = cache_position[-input_length:]
1310
+
1311
+ model_inputs.update(
1312
+ {
1313
+ "position_ids": position_ids,
1314
+ "cache_position": cache_position,
1315
+ "past_key_values": past_key_values,
1316
+ "use_cache": use_cache,
1317
+ "attention_mask": attention_mask,
1318
+ }
1319
+ )
1320
+ return model_inputs
1321
+
1322
+ @staticmethod
1323
+ def _reorder_cache(past_key_values, beam_idx):
1324
+ reordered_past = ()
1325
+ for layer_past in past_key_values:
1326
+ reordered_past += (
1327
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1328
+ )
1329
+ return reordered_past
1330
+
1331
+
1332
+ @add_start_docstrings(
1333
+ """
1334
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1335
+
1336
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1337
+ (e.g. GPT-2) do.
1338
+
1339
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1340
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1341
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1342
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1343
+ each row of the batch).
1344
+ """,
1345
+ LLAMA_START_DOCSTRING,
1346
+ )
1347
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1348
+ def __init__(self, config):
1349
+ super().__init__(config)
1350
+ self.num_labels = config.num_labels
1351
+ self.model = LlamaModel(config)
1352
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ def get_input_embeddings(self):
1358
+ return self.model.embed_tokens
1359
+
1360
+ def set_input_embeddings(self, value):
1361
+ self.model.embed_tokens = value
1362
+
1363
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1364
+ def forward(
1365
+ self,
1366
+ input_ids: torch.LongTensor = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ position_ids: Optional[torch.LongTensor] = None,
1369
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1370
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1371
+ labels: Optional[torch.LongTensor] = None,
1372
+ use_cache: Optional[bool] = None,
1373
+ output_attentions: Optional[bool] = None,
1374
+ output_hidden_states: Optional[bool] = None,
1375
+ return_dict: Optional[bool] = None,
1376
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1377
+ r"""
1378
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1379
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1380
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1381
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1382
+ """
1383
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1384
+
1385
+ transformer_outputs = self.model(
1386
+ input_ids,
1387
+ attention_mask=attention_mask,
1388
+ position_ids=position_ids,
1389
+ past_key_values=past_key_values,
1390
+ inputs_embeds=inputs_embeds,
1391
+ use_cache=use_cache,
1392
+ output_attentions=output_attentions,
1393
+ output_hidden_states=output_hidden_states,
1394
+ return_dict=return_dict,
1395
+ )
1396
+ hidden_states = transformer_outputs[0]
1397
+ logits = self.score(hidden_states)
1398
+
1399
+ if input_ids is not None:
1400
+ batch_size = input_ids.shape[0]
1401
+ else:
1402
+ batch_size = inputs_embeds.shape[0]
1403
+
1404
+ if self.config.pad_token_id is None and batch_size != 1:
1405
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1406
+ if self.config.pad_token_id is None:
1407
+ sequence_lengths = -1
1408
+ else:
1409
+ if input_ids is not None:
1410
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1411
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1412
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1413
+ sequence_lengths = sequence_lengths.to(logits.device)
1414
+ else:
1415
+ sequence_lengths = -1
1416
+
1417
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1418
+
1419
+ loss = None
1420
+ if labels is not None:
1421
+ labels = labels.to(logits.device)
1422
+ if self.config.problem_type is None:
1423
+ if self.num_labels == 1:
1424
+ self.config.problem_type = "regression"
1425
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1426
+ self.config.problem_type = "single_label_classification"
1427
+ else:
1428
+ self.config.problem_type = "multi_label_classification"
1429
+
1430
+ if self.config.problem_type == "regression":
1431
+ loss_fct = MSELoss()
1432
+ if self.num_labels == 1:
1433
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1434
+ else:
1435
+ loss = loss_fct(pooled_logits, labels)
1436
+ elif self.config.problem_type == "single_label_classification":
1437
+ loss_fct = CrossEntropyLoss()
1438
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1439
+ elif self.config.problem_type == "multi_label_classification":
1440
+ loss_fct = BCEWithLogitsLoss()
1441
+ loss = loss_fct(pooled_logits, labels)
1442
+ if not return_dict:
1443
+ output = (pooled_logits,) + transformer_outputs[1:]
1444
+ return ((loss,) + output) if loss is not None else output
1445
+
1446
+ return SequenceClassifierOutputWithPast(
1447
+ loss=loss,
1448
+ logits=pooled_logits,
1449
+ past_key_values=transformer_outputs.past_key_values,
1450
+ hidden_states=transformer_outputs.hidden_states,
1451
+ attentions=transformer_outputs.attentions,
1452
+ )
1453
+
1454
+
1455
+ @add_start_docstrings(
1456
+ """
1457
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1458
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1459
+ """,
1460
+ LLAMA_START_DOCSTRING,
1461
+ )
1462
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1463
+ base_model_prefix = "transformer"
1464
+
1465
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1466
+ def __init__(self, config):
1467
+ super().__init__(config)
1468
+ self.transformer = LlamaModel(config)
1469
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1470
+
1471
+ # Initialize weights and apply final processing
1472
+ self.post_init()
1473
+
1474
+ def get_input_embeddings(self):
1475
+ return self.transformer.embed_tokens
1476
+
1477
+ def set_input_embeddings(self, value):
1478
+ self.transformer.embed_tokens = value
1479
+
1480
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1481
+ def forward(
1482
+ self,
1483
+ input_ids: Optional[torch.LongTensor] = None,
1484
+ attention_mask: Optional[torch.FloatTensor] = None,
1485
+ position_ids: Optional[torch.LongTensor] = None,
1486
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1487
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1488
+ start_positions: Optional[torch.LongTensor] = None,
1489
+ end_positions: Optional[torch.LongTensor] = None,
1490
+ output_attentions: Optional[bool] = None,
1491
+ output_hidden_states: Optional[bool] = None,
1492
+ return_dict: Optional[bool] = None,
1493
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1494
+ r"""
1495
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1496
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1497
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1498
+ are not taken into account for computing the loss.
1499
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1500
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1501
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1502
+ are not taken into account for computing the loss.
1503
+ """
1504
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1505
+
1506
+ outputs = self.transformer(
1507
+ input_ids,
1508
+ attention_mask=attention_mask,
1509
+ position_ids=position_ids,
1510
+ past_key_values=past_key_values,
1511
+ inputs_embeds=inputs_embeds,
1512
+ output_attentions=output_attentions,
1513
+ output_hidden_states=output_hidden_states,
1514
+ return_dict=return_dict,
1515
+ )
1516
+
1517
+ sequence_output = outputs[0]
1518
+
1519
+ logits = self.qa_outputs(sequence_output)
1520
+ start_logits, end_logits = logits.split(1, dim=-1)
1521
+ start_logits = start_logits.squeeze(-1).contiguous()
1522
+ end_logits = end_logits.squeeze(-1).contiguous()
1523
+
1524
+ total_loss = None
1525
+ if start_positions is not None and end_positions is not None:
1526
+ # If we are on multi-GPU, split add a dimension
1527
+ if len(start_positions.size()) > 1:
1528
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1529
+ if len(end_positions.size()) > 1:
1530
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1531
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1532
+ ignored_index = start_logits.size(1)
1533
+ start_positions = start_positions.clamp(0, ignored_index)
1534
+ end_positions = end_positions.clamp(0, ignored_index)
1535
+
1536
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1537
+ start_loss = loss_fct(start_logits, start_positions)
1538
+ end_loss = loss_fct(end_logits, end_positions)
1539
+ total_loss = (start_loss + end_loss) / 2
1540
+
1541
+ if not return_dict:
1542
+ output = (start_logits, end_logits) + outputs[2:]
1543
+ return ((total_loss,) + output) if total_loss is not None else output
1544
+
1545
+ return QuestionAnsweringModelOutput(
1546
+ loss=total_loss,
1547
+ start_logits=start_logits,
1548
+ end_logits=end_logits,
1549
+ hidden_states=outputs.hidden_states,
1550
+ attentions=outputs.attentions,
1551
+ )
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:136896497666d06e02b7fb44bc315cb8bc5b1963f95d2411a75df6c23eb7afd5
3
+ size 267664306
special_tokens_map.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|endoftext|>",
4
+ "<|im_start|>",
5
+ "<|im_end|>",
6
+ "<repo_name>",
7
+ "<reponame>",
8
+ "<file_sep>",
9
+ "<filename>",
10
+ "<gh_stars>",
11
+ "<issue_start>",
12
+ "<issue_comment>",
13
+ "<issue_closed>",
14
+ "<jupyter_start>",
15
+ "<jupyter_text>",
16
+ "<jupyter_code>",
17
+ "<jupyter_output>",
18
+ "<jupyter_script>",
19
+ "<empty_output>"
20
+ ],
21
+ "bos_token": {
22
+ "content": "<|endoftext|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false
27
+ },
28
+ "eos_token": {
29
+ "content": "<|endoftext|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ },
35
+ "unk_token": {
36
+ "content": "<|endoftext|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false
41
+ }
42
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<repo_name>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "4": {
38
+ "content": "<reponame>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "5": {
46
+ "content": "<file_sep>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "6": {
54
+ "content": "<filename>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "7": {
62
+ "content": "<gh_stars>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "8": {
70
+ "content": "<issue_start>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "9": {
78
+ "content": "<issue_comment>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "10": {
86
+ "content": "<issue_closed>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "11": {
94
+ "content": "<jupyter_start>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "12": {
102
+ "content": "<jupyter_text>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "13": {
110
+ "content": "<jupyter_code>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "14": {
118
+ "content": "<jupyter_output>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "15": {
126
+ "content": "<jupyter_script>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "16": {
134
+ "content": "<empty_output>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": true
140
+ }
141
+ },
142
+ "additional_special_tokens": [
143
+ "<|endoftext|>",
144
+ "<|im_start|>",
145
+ "<|im_end|>",
146
+ "<repo_name>",
147
+ "<reponame>",
148
+ "<file_sep>",
149
+ "<filename>",
150
+ "<gh_stars>",
151
+ "<issue_start>",
152
+ "<issue_comment>",
153
+ "<issue_closed>",
154
+ "<jupyter_start>",
155
+ "<jupyter_text>",
156
+ "<jupyter_code>",
157
+ "<jupyter_output>",
158
+ "<jupyter_script>",
159
+ "<empty_output>"
160
+ ],
161
+ "bos_token": "<|endoftext|>",
162
+ "clean_up_tokenization_spaces": false,
163
+ "eos_token": "<|endoftext|>",
164
+ "errors": "replace",
165
+ "model_max_length": 2048,
166
+ "pad_token": null,
167
+ "padding_side": "right",
168
+ "tokenizer_class": "GPT2Tokenizer",
169
+ "unk_token": "<|endoftext|>",
170
+ "vocab_size": 49152
171
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a89b9c0cac28413b2abbf8b5f5f47b0b4bdbb1ed6e112527dc00fd67b47623c0
3
+ size 5112
vocab.json ADDED
The diff for this file is too large to render. See raw diff