Tangshengku commited on
Commit
9989e2b
·
1 Parent(s): 7c7a18d
Files changed (2) hide show
  1. configuration_llama.py +0 -276
  2. modeling_llama_3.py +0 -1797
configuration_llama.py DELETED
@@ -1,276 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
- # and OPT implementations in this library. It has been modified from its
6
- # original forms to accommodate minor architectural differences compared
7
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
- #
9
- # Licensed under the Apache License, Version 2.0 (the "License");
10
- # you may not use this file except in compliance with the License.
11
- # You may obtain a copy of the License at
12
- #
13
- # http://www.apache.org/licenses/LICENSE-2.0
14
- #
15
- # Unless required by applicable law or agreed to in writing, software
16
- # distributed under the License is distributed on an "AS IS" BASIS,
17
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- # See the License for the specific language governing permissions and
19
- # limitations under the License.
20
- """LLaMA model configuration"""
21
-
22
- from transformers import PretrainedConfig
23
- from transformers.modeling_rope_utils import rope_config_validation
24
-
25
-
26
- class DarwinLMConfig(PretrainedConfig):
27
- r"""
28
- This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
29
- model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
- defaults will yield a similar configuration to that of the LLaMA-7B.
31
-
32
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
- documentation from [`PretrainedConfig`] for more information.
34
-
35
-
36
- Args:
37
- vocab_size (`int`, *optional*, defaults to 32000):
38
- Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
39
- `inputs_ids` passed when calling [`LlamaModel`]
40
- hidden_size (`int`, *optional*, defaults to 4096):
41
- Dimension of the hidden representations.
42
- intermediate_size (`int`, *optional*, defaults to 11008):
43
- Dimension of the MLP representations.
44
- num_hidden_layers (`int`, *optional*, defaults to 32):
45
- Number of hidden layers in the Transformer decoder.
46
- num_attention_heads (`int`, *optional*, defaults to 32):
47
- Number of attention heads for each attention layer in the Transformer decoder.
48
- num_key_value_heads (`int`, *optional*):
49
- This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
- `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
- `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
- converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
- by meanpooling all the original heads within that group. For more details checkout [this
54
- paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
55
- `num_attention_heads`.
56
- hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
- The non-linear activation function (function or string) in the decoder.
58
- max_position_embeddings (`int`, *optional*, defaults to 2048):
59
- The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
60
- Llama 2 up to 4096, CodeLlama up to 16384.
61
- initializer_range (`float`, *optional*, defaults to 0.02):
62
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
- rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
- The epsilon used by the rms normalization layers.
65
- use_cache (`bool`, *optional*, defaults to `True`):
66
- Whether or not the model should return the last key/values attentions (not used by all models). Only
67
- relevant if `config.is_decoder=True`.
68
- pad_token_id (`int`, *optional*):
69
- Padding token id.
70
- bos_token_id (`int`, *optional*, defaults to 1):
71
- Beginning of stream token id.
72
- eos_token_id (`int`, *optional*, defaults to 2):
73
- End of stream token id.
74
- pretraining_tp (`int`, *optional*, defaults to 1):
75
- Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
- document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
- understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
- results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
- tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
- Whether to tie weight embeddings
81
- rope_theta (`float`, *optional*, defaults to 10000.0):
82
- The base period of the RoPE embeddings.
83
- rope_scaling (`Dict`, *optional*):
84
- Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
- and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
- accordingly.
87
- Expected contents:
88
- `rope_type` (`str`):
89
- The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
- 'llama3'], with 'default' being the original RoPE implementation.
91
- `factor` (`float`, *optional*):
92
- Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
- most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
- original maximum pre-trained length.
95
- `original_max_position_embeddings` (`int`, *optional*):
96
- Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
- pretraining.
98
- `attention_factor` (`float`, *optional*):
99
- Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
- computation. If unspecified, it defaults to value recommended by the implementation, using the
101
- `factor` field to infer the suggested value.
102
- `beta_fast` (`float`, *optional*):
103
- Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
- ramp function. If unspecified, it defaults to 32.
105
- `beta_slow` (`float`, *optional*):
106
- Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
- ramp function. If unspecified, it defaults to 1.
108
- `short_factor` (`List[float]`, *optional*):
109
- Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
- size divided by the number of attention heads divided by 2
112
- `long_factor` (`List[float]`, *optional*):
113
- Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
- size divided by the number of attention heads divided by 2
116
- `low_freq_factor` (`float`, *optional*):
117
- Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
- `high_freq_factor` (`float`, *optional*):
119
- Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
- attention_bias (`bool`, *optional*, defaults to `False`):
121
- Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
- attention_dropout (`float`, *optional*, defaults to 0.0):
123
- The dropout ratio for the attention probabilities.
124
- mlp_bias (`bool`, *optional*, defaults to `False`):
125
- Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
- head_dim (`int`, *optional*):
127
- The attention head dimension. If None, it will default to hidden_size // num_attention_heads
128
-
129
- ```python
130
- >>> from transformers import LlamaModel, LlamaConfig
131
-
132
- >>> # Initializing a LLaMA llama-7b style configuration
133
- >>> configuration = LlamaConfig()
134
-
135
- >>> # Initializing a model from the llama-7b style configuration
136
- >>> model = LlamaModel(configuration)
137
-
138
- >>> # Accessing the model configuration
139
- >>> configuration = model.config
140
- ```"""
141
-
142
- model_type = "darwinlm"
143
- keys_to_ignore_at_inference = ["past_key_values"]
144
- # Default tensor parallel plan for base model `LlamaModel`
145
- base_model_tp_plan = {
146
- "layers.*.self_attn.q_proj": "colwise",
147
- "layers.*.self_attn.k_proj": "colwise",
148
- "layers.*.self_attn.v_proj": "colwise",
149
- "layers.*.self_attn.o_proj": "rowwise",
150
- "layers.*.mlp.gate_proj": "colwise",
151
- "layers.*.mlp.up_proj": "colwise",
152
- "layers.*.mlp.down_proj": "rowwise",
153
- }
154
- base_model_pp_plan = {
155
- "embed_tokens": (["input_ids"], ["inputs_embeds"]),
156
- "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
157
- "norm": (["hidden_states"], ["hidden_states"]),
158
- }
159
-
160
- def __init__(
161
- self,
162
- vocab_size=32000,
163
- hidden_size=4096,
164
- intermediate_size=11008,
165
- num_hidden_layers=32,
166
- num_attention_heads=32,
167
- num_key_value_heads=None,
168
- hidden_act="silu",
169
- max_position_embeddings=2048,
170
- initializer_range=0.02,
171
- rms_norm_eps=1e-6,
172
- use_cache=True,
173
- pad_token_id=None,
174
- bos_token_id=1,
175
- eos_token_id=2,
176
- pretraining_tp=1,
177
- tie_word_embeddings=False,
178
- rope_theta=10000.0,
179
- rope_scaling=None,
180
- attention_bias=False,
181
- attention_dropout=0.0,
182
- mlp_bias=False,
183
- head_dim=None,
184
- kv_ignore=False,
185
- dim_each_mlp={"0.mlp.down_proj": 11008, "1.mlp.down_proj": 11008,
186
- "2.mlp.down_proj": 11008, "3.mlp.down_proj": 11008,
187
- "4.mlp.down_proj": 11008, "5.mlp.down_proj": 11008,
188
- "6.mlp.down_proj": 11008, "7.mlp.down_proj": 11008,
189
- "8.mlp.down_proj": 11008, "9.mlp.down_proj": 11008,
190
- "10.mlp.down_proj": 11008, "11.mlp.down_proj": 11008,
191
- "12.mlp.down_proj": 11008, "13.mlp.down_proj": 11008,
192
- "14.mlp.down_proj": 11008, "15.mlp.down_proj": 11008,
193
- "16.mlp.down_proj": 11008, "17.mlp.down_proj": 11008,
194
- "18.mlp.down_proj": 11008, "19.mlp.down_proj": 11008,
195
- "20.mlp.down_proj": 11008, "21.mlp.down_proj": 11008,
196
- "22.mlp.down_proj": 11008, "23.mlp.down_proj": 11008,
197
- "24.mlp.down_proj": 11008, "25.mlp.down_proj": 11008,
198
- "26.mlp.down_proj": 11008, "27.mlp.down_proj": 11008,
199
- "28.mlp.down_proj": 11008, "29.mlp.down_proj": 11008,
200
- "30.mlp.down_proj": 11008, "31.mlp.down_proj": 11008,
201
- "32.mlp.down_proj": 11008, "33.mlp.down_proj": 11008,
202
- "34.mlp.down_proj": 11008, "35.mlp.down_proj": 11008,
203
- "36.mlp.down_proj": 11008, "37.mlp.down_proj": 11008,
204
- "38.mlp.down_proj": 11008, "39.mlp.down_proj": 11008,
205
- "40.mlp.down_proj": 11008, "41.mlp.down_proj": 11008,
206
- "42.mlp.down_proj": 11008, "43.mlp.down_proj": 11008,
207
- "44.mlp.down_proj": 11008, "45.mlp.down_proj": 11008,
208
- "46.mlp.down_proj": 11008, "47.mlp.down_proj": 11008,},
209
- heads_each_attn={"0.self_attn.o_proj": 32, "1.self_attn.o_proj": 32,
210
- "2.self_attn.o_proj": 32, "3.self_attn.o_proj": 32,
211
- "4.self_attn.o_proj": 32, "5.self_attn.o_proj": 32,
212
- "6.self_attn.o_proj": 32, "7.self_attn.o_proj": 32,
213
- "8.self_attn.o_proj": 32, "9.self_attn.o_proj": 32,
214
- "10.self_attn.o_proj": 32, "11.self_attn.o_proj": 32,
215
- "12.self_attn.o_proj": 32, "13.self_attn.o_proj": 32,
216
- "14.self_attn.o_proj": 32, "15.self_attn.o_proj": 32,
217
- "16.self_attn.o_proj": 32, "17.self_attn.o_proj": 32,
218
- "18.self_attn.o_proj": 32, "19.self_attn.o_proj": 32,
219
- "20.self_attn.o_proj": 32, "21.self_attn.o_proj": 32,
220
- "22.self_attn.o_proj": 32, "23.self_attn.o_proj": 32,
221
- "24.self_attn.o_proj": 32, "25.self_attn.o_proj": 32,
222
- "26.self_attn.o_proj": 32, "27.self_attn.o_proj": 32,
223
- "28.self_attn.o_proj": 32, "29.self_attn.o_proj": 32,
224
- "30.self_attn.o_proj": 32, "31.self_attn.o_proj": 32,
225
- "32.self_attn.o_proj": 32, "33.self_attn.o_proj": 32,
226
- "34.self_attn.o_proj": 32, "35.self_attn.o_proj": 32,
227
- "36.self_attn.o_proj": 32, "37.self_attn.o_proj": 32,
228
- "38.self_attn.o_proj": 32, "39.self_attn.o_proj": 32,
229
- "40.self_attn.o_proj": 32, "41.self_attn.o_proj": 32,
230
- "42.self_attn.o_proj": 32, "43.self_attn.o_proj": 32,
231
- "44.self_attn.o_proj": 32, "45.self_attn.o_proj": 32,
232
- "46.self_attn.o_proj": 32, "47.self_attn.o_proj": 32,},
233
- **kwargs,
234
- ):
235
- self.vocab_size = vocab_size
236
- self.max_position_embeddings = max_position_embeddings
237
- self.hidden_size = hidden_size
238
- self.intermediate_size = intermediate_size
239
- self.num_hidden_layers = num_hidden_layers
240
- self.num_attention_heads = num_attention_heads
241
- self.kv_ignore = kv_ignore
242
- self.heads_each_attn = heads_each_attn
243
- self.dim_each_mlp = dim_each_mlp
244
-
245
- # for backward compatibility
246
- if num_key_value_heads is None:
247
- num_key_value_heads = num_attention_heads
248
-
249
- self.num_key_value_heads = num_key_value_heads
250
- self.hidden_act = hidden_act
251
- self.initializer_range = initializer_range
252
- self.rms_norm_eps = rms_norm_eps
253
- self.pretraining_tp = pretraining_tp
254
- self.use_cache = use_cache
255
- self.rope_theta = rope_theta
256
- self.rope_scaling = rope_scaling
257
- self.attention_bias = attention_bias
258
- self.attention_dropout = attention_dropout
259
- self.mlp_bias = mlp_bias
260
- self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
261
- # Validate the correctness of rotary position embeddings parameters
262
- # BC: if there is a 'type' field, copy it it to 'rope_type'.
263
- if self.rope_scaling is not None and "type" in self.rope_scaling:
264
- self.rope_scaling["rope_type"] = self.rope_scaling["type"]
265
- rope_config_validation(self)
266
-
267
- super().__init__(
268
- pad_token_id=pad_token_id,
269
- bos_token_id=bos_token_id,
270
- eos_token_id=eos_token_id,
271
- tie_word_embeddings=tie_word_embeddings,
272
- **kwargs,
273
- )
274
-
275
-
276
- __all__ = ["LlamaConfig"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modeling_llama_3.py DELETED
@@ -1,1797 +0,0 @@
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
- import math
21
- from typing import List, Optional, Tuple, Union
22
-
23
- import torch
24
- import torch.nn.functional as F
25
- import torch.utils.checkpoint
26
- from torch import nn
27
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
-
29
- from transformers.activations import ACT2FN
30
- from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
- from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
- from transformers.modeling_flash_attention_utils import _flash_attention_forward
33
- from transformers.modeling_outputs import (
34
- BaseModelOutputWithPast,
35
- CausalLMOutputWithPast,
36
- QuestionAnsweringModelOutput,
37
- SequenceClassifierOutputWithPast,
38
- TokenClassifierOutput,
39
- )
40
- from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
- from transformers.modeling_utils import PreTrainedModel, prune_linear_layer, find_pruneable_heads_and_indices
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_greater_or_equal_2_10,
47
- is_torchdynamo_compiling,
48
- logging,
49
- replace_return_docstrings,
50
- )
51
- from .configuration_llama import DarwinLMConfig
52
-
53
-
54
- logger = logging.get_logger(__name__)
55
-
56
- _CONFIG_FOR_DOC = "DarwinLMConfig"
57
-
58
- class NoAttention(nn.Module):
59
- def forward(
60
- self,
61
- hidden_states: torch.Tensor,
62
- attention_mask: Optional[torch.Tensor] = None,
63
- position_ids: Optional[torch.LongTensor] = None,
64
- past_key_value = None,
65
- output_attentions: bool = False,
66
- use_cache: bool = False,
67
- cache_position: Optional[torch.LongTensor] = None,
68
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
69
- **kwargs,
70
- ):
71
- return (0, None, None)
72
-
73
-
74
- class NoIntermediate(nn.Module):
75
- def forward(self, hidden_states):
76
- return hidden_states
77
-
78
-
79
- class NoOutput(nn.Module):
80
- def forward(self, hidden_states):
81
- return 0
82
-
83
-
84
- def _prepare_4d_causal_attention_mask_with_cache_position(
85
- attention_mask: torch.Tensor,
86
- sequence_length: int,
87
- target_length: int,
88
- dtype: torch.dtype,
89
- device: torch.device,
90
- min_dtype: float,
91
- cache_position: torch.Tensor,
92
- batch_size: int,
93
- ):
94
- """
95
- Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
96
- `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
97
-
98
- Args:
99
- attention_mask (`torch.Tensor`):
100
- A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
101
- sequence_length (`int`):
102
- The sequence length being processed.
103
- target_length (`int`):
104
- The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
105
- dtype (`torch.dtype`):
106
- The dtype to use for the 4D attention mask.
107
- device (`torch.device`):
108
- The device to plcae the 4D attention mask on.
109
- min_dtype (`float`):
110
- The minimum value representable with the dtype `dtype`.
111
- cache_position (`torch.Tensor`):
112
- Indices depicting the position of the input sequence tokens in the sequence.
113
- batch_size (`torch.Tensor`):
114
- Batch size.
115
- """
116
- if attention_mask is not None and attention_mask.dim() == 4:
117
- # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
118
- causal_mask = attention_mask
119
- else:
120
- causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
121
- if sequence_length != 1:
122
- causal_mask = torch.triu(causal_mask, diagonal=1)
123
- causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
124
- causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
125
- if attention_mask is not None:
126
- causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
127
- mask_length = attention_mask.shape[-1]
128
- padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
129
- padding_mask = padding_mask == 0
130
- causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
131
- padding_mask, min_dtype
132
- )
133
-
134
- return causal_mask
135
-
136
-
137
- class LlamaRMSNorm(nn.Module):
138
- def __init__(self, hidden_size, eps=1e-6):
139
- """
140
- LlamaRMSNorm is equivalent to T5LayerNorm
141
- """
142
- super().__init__()
143
- self.weight = nn.Parameter(torch.ones(hidden_size))
144
- self.variance_epsilon = eps
145
-
146
- def forward(self, hidden_states):
147
- input_dtype = hidden_states.dtype
148
- hidden_states = hidden_states.to(torch.float32)
149
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
150
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
151
- return self.weight * hidden_states.to(input_dtype)
152
-
153
- def extra_repr(self):
154
- return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
155
-
156
-
157
- ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
158
-
159
-
160
- class LlamaRotaryEmbedding(nn.Module):
161
- def __init__(
162
- self,
163
- dim=None,
164
- max_position_embeddings=2048,
165
- base=10000,
166
- device=None,
167
- scaling_factor=1.0,
168
- rope_type="default",
169
- config: Optional[DarwinLMConfig] = None,
170
- ):
171
- super().__init__()
172
- # TODO (joao): remove the `if` below, only used for BC
173
- self.rope_kwargs = {}
174
- if config is None:
175
- logger.warning_once(
176
- "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
177
- "`config` argument. All other arguments will be removed in v4.45"
178
- )
179
- self.rope_kwargs = {
180
- "rope_type": rope_type,
181
- "factor": scaling_factor,
182
- "dim": dim,
183
- "base": base,
184
- "max_position_embeddings": max_position_embeddings,
185
- }
186
- self.rope_type = rope_type
187
- self.max_seq_len_cached = max_position_embeddings
188
- self.original_max_seq_len = max_position_embeddings
189
- else:
190
- # BC: "rope_type" was originally "type"
191
- if config.rope_scaling is not None:
192
- self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
193
- else:
194
- self.rope_type = "default"
195
- self.max_seq_len_cached = config.max_position_embeddings
196
- self.original_max_seq_len = config.max_position_embeddings
197
-
198
- self.config = config
199
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
200
-
201
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
202
- self.register_buffer("inv_freq", inv_freq, persistent=False)
203
- self.original_inv_freq = self.inv_freq
204
-
205
- def _dynamic_frequency_update(self, position_ids, device):
206
- """
207
- dynamic RoPE layers should recompute `inv_freq` in the following situations:
208
- 1 - growing beyond the cached sequence length (allow scaling)
209
- 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
210
- """
211
- seq_len = torch.max(position_ids) + 1
212
- if seq_len > self.max_seq_len_cached: # growth
213
- inv_freq, self.attention_scaling = self.rope_init_fn(
214
- self.config, device, seq_len=seq_len, **self.rope_kwargs
215
- )
216
- self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
217
- self.max_seq_len_cached = seq_len
218
-
219
- if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
220
- self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
221
- self.max_seq_len_cached = self.original_max_seq_len
222
-
223
- @torch.no_grad()
224
- def forward(self, x, position_ids):
225
- if "dynamic" in self.rope_type:
226
- self._dynamic_frequency_update(position_ids, device=x.device)
227
-
228
- # Core RoPE block
229
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
230
- position_ids_expanded = position_ids[:, None, :].float()
231
- # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
232
- device_type = x.device.type
233
- device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
234
- with torch.autocast(device_type=device_type, enabled=False):
235
- freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
236
- emb = torch.cat((freqs, freqs), dim=-1)
237
- cos = emb.cos()
238
- sin = emb.sin()
239
-
240
- # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
241
- cos = cos * self.attention_scaling
242
- sin = sin * self.attention_scaling
243
-
244
- return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
245
-
246
-
247
- class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
248
- """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
249
-
250
- def __init__(self, *args, **kwargs):
251
- logger.warning_once(
252
- "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
253
- "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
254
- )
255
- kwargs["rope_type"] = "linear"
256
- super().__init__(*args, **kwargs)
257
-
258
-
259
- class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
260
- """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
261
-
262
- def __init__(self, *args, **kwargs):
263
- logger.warning_once(
264
- "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
265
- "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
266
- "__init__)."
267
- )
268
- kwargs["rope_type"] = "dynamic"
269
- super().__init__(*args, **kwargs)
270
-
271
-
272
- def rotate_half(x):
273
- """Rotates half the hidden dims of the input."""
274
- x1 = x[..., : x.shape[-1] // 2]
275
- x2 = x[..., x.shape[-1] // 2 :]
276
- return torch.cat((-x2, x1), dim=-1)
277
-
278
-
279
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
280
- """Applies Rotary Position Embedding to the query and key tensors.
281
-
282
- Args:
283
- q (`torch.Tensor`): The query tensor.
284
- k (`torch.Tensor`): The key tensor.
285
- cos (`torch.Tensor`): The cosine part of the rotary embedding.
286
- sin (`torch.Tensor`): The sine part of the rotary embedding.
287
- position_ids (`torch.Tensor`, *optional*):
288
- Deprecated and unused.
289
- unsqueeze_dim (`int`, *optional*, defaults to 1):
290
- The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
291
- sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
292
- that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
293
- k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
294
- cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
295
- the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
296
- Returns:
297
- `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
298
- """
299
- cos = cos.unsqueeze(unsqueeze_dim)
300
- sin = sin.unsqueeze(unsqueeze_dim)
301
- q_embed = (q * cos) + (rotate_half(q) * sin)
302
- k_embed = (k * cos) + (rotate_half(k) * sin)
303
- return q_embed, k_embed
304
-
305
-
306
- class LlamaMLP(nn.Module):
307
- def __init__(self, config):
308
- super().__init__()
309
- self.config = config
310
- self.hidden_size = config.hidden_size
311
- self.intermediate_size = config.intermediate_size
312
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
313
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
314
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
315
- self.act_fn = ACT2FN[config.hidden_act]
316
-
317
- def prune_mlp(self, idx):
318
- self.gate_proj = prune_linear_layer(self.gate_proj, idx)
319
- self.up_proj = prune_linear_layer(self.up_proj, idx)
320
- self.down_proj = prune_linear_layer(self.down_proj, idx, dim=1)
321
-
322
- def forward(self, x):
323
- if self.config.pretraining_tp > 1:
324
- slice = self.intermediate_size // self.config.pretraining_tp
325
- gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
326
- up_proj_slices = self.up_proj.weight.split(slice, dim=0)
327
- down_proj_slices = self.down_proj.weight.split(slice, dim=1)
328
-
329
- gate_proj = torch.cat(
330
- [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
331
- )
332
- up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
333
-
334
- intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
335
- down_proj = [
336
- F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
337
- ]
338
- down_proj = sum(down_proj)
339
- else:
340
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
341
-
342
- return down_proj
343
-
344
-
345
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int, index: Optional[torch.LongTensor] = None) -> torch.Tensor:
346
- """
347
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
348
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
349
- """
350
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
351
- if n_rep == 1:
352
- return hidden_states
353
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
354
- hidden_states = hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
355
- # For pruned Llama3.1, we select corresponding matrix if Q is pruned.
356
- if index is not None:
357
- hidden_states = hidden_states.index_select(dim=1, index=index)
358
- return hidden_states
359
-
360
-
361
- class LlamaAttention(nn.Module):
362
- """Multi-headed attention from 'Attention Is All You Need' paper"""
363
-
364
- def __init__(self, config: DarwinLMConfig, layer_idx: Optional[int] = None):
365
- super().__init__()
366
- self.config = config
367
- self.layer_idx = layer_idx
368
- if layer_idx is None:
369
- logger.warning_once(
370
- f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
371
- "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
372
- "when creating this class."
373
- )
374
-
375
- self.attention_dropout = config.attention_dropout
376
- self.hidden_size = config.hidden_size
377
- self.num_heads = config.num_attention_heads
378
- import copy
379
- self.ori_num_heads = copy.deepcopy(self.num_heads)
380
- self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
381
- self.num_key_value_heads = config.num_key_value_heads
382
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
383
- self.max_position_embeddings = config.max_position_embeddings
384
- self.rope_theta = config.rope_theta
385
- self.is_causal = True
386
-
387
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
388
- self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
389
- self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
390
- self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
391
-
392
- # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
393
- self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
394
- self.pruned_heads = set()
395
- self.pruned_kv_heads = set()
396
-
397
- # Added by Bryson for structural pruning in LLama
398
- # if kv_ignore = True, K and V will not be pruned. Applied in Llama3.1(GQA) pruning.
399
- def prune_heads(self, heads, kv_ignore=False):
400
- if len(heads) == 0:
401
- return
402
- heads, index = find_pruneable_heads_and_indices(
403
- heads, self.num_heads, self.head_dim, self.pruned_heads
404
- )
405
- # Prune linear layers
406
- self.q_proj = prune_linear_layer(self.q_proj, index)
407
- if not kv_ignore:
408
- self.k_proj = prune_linear_layer(self.k_proj, index)
409
- self.v_proj = prune_linear_layer(self.v_proj, index)
410
- self.o_proj = prune_linear_layer(self.o_proj, index, dim=1)
411
-
412
- # Update hyper params and store pruned heads
413
- self.num_heads = self.num_heads - len(heads)
414
- if not kv_ignore:
415
- self.num_key_value_heads = self.num_key_value_heads - len(heads)
416
- self.hidden_size = self.head_dim * self.num_heads
417
- self.pruned_heads = self.pruned_heads.union(heads)
418
-
419
- # Structural Pruning for GQA, prune K,V and prune the corresponding weight group in Q and O
420
- # The input heads are the pruned index in K and V
421
- # Note: Not Applied in DarwinLM experiments
422
- def prune_group_heads(self, heads):
423
- if len(heads) == 0:
424
- return
425
-
426
- heads, index = find_pruneable_heads_and_indices(
427
- heads, self.num_key_value_heads, self.head_dim, self.pruned_kv_heads
428
- )
429
- self.k_proj = prune_linear_layer(self.k_proj, index)
430
- self.v_proj = prune_linear_layer(self.v_proj, index)
431
-
432
- self.num_key_value_heads = self.num_key_value_heads - len(heads)
433
- self.pruned_kv_heads = self.pruned_heads.union(heads)
434
-
435
- q_o_heads = []
436
- for head in heads:
437
- for i in range(head * self.num_key_value_groups, head * self.num_key_value_groups + self.num_key_value_groups):
438
- q_o_heads.append(i)
439
- # print(q_o_heads)
440
- heads, index = find_pruneable_heads_and_indices(
441
- q_o_heads, self.num_heads, self.head_dim, self.pruned_heads
442
- )
443
- # Prune linear layers
444
- self.q_proj = prune_linear_layer(self.q_proj, index)
445
- self.o_proj = prune_linear_layer(self.o_proj, index, dim=1)
446
-
447
- # Update hyper params and store pruned heads
448
- self.num_heads = self.num_heads - len(q_o_heads)
449
- self.hidden_size = self.head_dim * self.num_heads
450
- self.pruned_heads = self.pruned_heads.union(q_o_heads)
451
-
452
-
453
- def forward(
454
- self,
455
- hidden_states: torch.Tensor,
456
- attention_mask: Optional[torch.Tensor] = None,
457
- position_ids: Optional[torch.LongTensor] = None,
458
- past_key_value: Optional[Cache] = None,
459
- output_attentions: bool = False,
460
- use_cache: bool = False,
461
- cache_position: Optional[torch.LongTensor] = None,
462
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
463
- **kwargs,
464
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
465
- bsz, q_len, _ = hidden_states.size()
466
-
467
- if self.config.pretraining_tp > 1:
468
- key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
469
- query_slices = self.q_proj.weight.split(
470
- (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
471
- )
472
- key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
473
- value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
474
-
475
- query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
476
- query_states = torch.cat(query_states, dim=-1)
477
-
478
- key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
479
- key_states = torch.cat(key_states, dim=-1)
480
-
481
- value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
482
- value_states = torch.cat(value_states, dim=-1)
483
-
484
- else:
485
- query_states = self.q_proj(hidden_states)
486
- key_states = self.k_proj(hidden_states)
487
- value_states = self.v_proj(hidden_states)
488
-
489
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
490
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
491
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
492
-
493
- if position_embeddings is None:
494
- logger.warning_once(
495
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
496
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
497
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
498
- "removed and `position_embeddings` will be mandatory."
499
- )
500
- cos, sin = self.rotary_emb(value_states, position_ids)
501
- else:
502
- cos, sin = position_embeddings
503
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
504
-
505
- if past_key_value is not None:
506
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
507
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
508
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
509
-
510
- # if self.num_key_value_heads == self.num_heads:
511
- # head_index_kv = None
512
- # else:
513
- # remaining_head_index = []
514
- # for i in range(self.ori_num_heads):
515
- # if i not in self.pruned_heads:
516
- # remaining_head_index.append(i)
517
- # head_index_kv = torch.tensor(remaining_head_index).long().to(key_states.device)
518
- head_index_kv = None
519
- # key_states = repeat_kv(key_states, self.num_key_value_groups, index=head_index_kv)
520
- # value_states = repeat_kv(value_states, self.num_key_value_groups, index=head_index_kv)
521
- if query_states.shape[1] != key_states.shape[1]:
522
- num_q_heads = query_states.shape[1]
523
- num_kv_heads = key_states.shape[1]
524
- remaining_head_index = []
525
- for i in range(self.ori_num_heads):
526
- if i not in self.pruned_heads:
527
- remaining_head_index.append(i)
528
- head_index_kv = torch.tensor(remaining_head_index).long().to(key_states.device)
529
- key_states = repeat_kv(key_states, self.num_key_value_groups, index=head_index_kv)
530
- value_states = repeat_kv(value_states, self.num_key_value_groups, index=head_index_kv)
531
-
532
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
533
-
534
- if attention_mask is not None: # no matter the length, we just slice it
535
- causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
536
- attn_weights = attn_weights + causal_mask
537
-
538
- # upcast attention to fp32
539
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
540
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
541
- attn_output = torch.matmul(attn_weights, value_states)
542
-
543
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
544
- raise ValueError(
545
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
546
- f" {attn_output.size()}"
547
- )
548
-
549
- attn_output = attn_output.transpose(1, 2).contiguous()
550
-
551
- attn_output = attn_output.reshape(bsz, q_len, -1)
552
-
553
- if self.config.pretraining_tp > 1:
554
- attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
555
- o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
556
- attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
557
- else:
558
- attn_output = self.o_proj(attn_output)
559
-
560
- if not output_attentions:
561
- attn_weights = None
562
-
563
- return attn_output, attn_weights, past_key_value
564
-
565
-
566
- class LlamaFlashAttention2(LlamaAttention):
567
- """
568
- Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
569
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
570
- flash attention and deal with padding tokens in case the input contains any of them.
571
- """
572
-
573
- def __init__(self, *args, **kwargs):
574
- super().__init__(*args, **kwargs)
575
-
576
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
577
- # 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.
578
- # 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).
579
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
580
-
581
- def forward(
582
- self,
583
- hidden_states: torch.Tensor,
584
- attention_mask: Optional[torch.LongTensor] = None,
585
- position_ids: Optional[torch.LongTensor] = None,
586
- past_key_value: Optional[Cache] = None,
587
- output_attentions: bool = False,
588
- use_cache: bool = False,
589
- cache_position: Optional[torch.LongTensor] = None,
590
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
591
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
592
- if isinstance(past_key_value, StaticCache):
593
- raise ValueError(
594
- "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
595
- "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
596
- )
597
-
598
- output_attentions = False
599
-
600
- bsz, q_len, _ = hidden_states.size()
601
-
602
- query_states = self.q_proj(hidden_states)
603
- key_states = self.k_proj(hidden_states)
604
- value_states = self.v_proj(hidden_states)
605
-
606
- # Flash attention requires the input to have the shape
607
- # batch_size x seq_length x head_dim x hidden_dim
608
- # therefore we just need to keep the original shape
609
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
610
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
611
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
612
-
613
- if position_embeddings is None:
614
- logger.warning_once(
615
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
616
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
617
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
618
- "removed and `position_embeddings` will be mandatory."
619
- )
620
- cos, sin = self.rotary_emb(value_states, position_ids)
621
- else:
622
- cos, sin = position_embeddings
623
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
624
-
625
- # if past_key_value is not None:
626
- # # sin and cos are specific to RoPE models; cache_position needed for the static cache
627
- # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
628
- # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
629
- if query_states.shape[1] != key_states.shape[1]:
630
- num_q_heads = query_states.shape[1]
631
- num_kv_heads = key_states.shape[1]
632
- remaining_head_index = []
633
- for i in range(self.ori_num_heads):
634
- if i not in self.pruned_heads:
635
- remaining_head_index.append(i)
636
- head_index_kv = torch.tensor(remaining_head_index).long().to(key_states.device)
637
- key_states = repeat_kv(key_states, self.num_key_value_groups, index=head_index_kv)
638
- value_states = repeat_kv(value_states, self.num_key_value_groups, index=head_index_kv)
639
-
640
- # 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
641
- # to be able to avoid many of these transpose/reshape/view.
642
- query_states = query_states.transpose(1, 2)
643
- key_states = key_states.transpose(1, 2)
644
- value_states = value_states.transpose(1, 2)
645
-
646
- dropout_rate = self.attention_dropout if self.training else 0.0
647
-
648
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
649
- # therefore the input hidden states gets silently casted in float32. Hence, we need
650
- # cast them back in the correct dtype just to be sure everything works as expected.
651
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
652
- # in fp32. (LlamaRMSNorm handles it correctly)
653
-
654
- input_dtype = query_states.dtype
655
- if input_dtype == torch.float32:
656
- if torch.is_autocast_enabled():
657
- target_dtype = torch.get_autocast_gpu_dtype()
658
- # Handle the case where the model is quantized
659
- elif hasattr(self.config, "_pre_quantization_dtype"):
660
- target_dtype = self.config._pre_quantization_dtype
661
- else:
662
- target_dtype = self.q_proj.weight.dtype
663
-
664
- logger.warning_once(
665
- f"The input hidden states seems to be silently casted in float32, this might be related to"
666
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
667
- f" {target_dtype}."
668
- )
669
-
670
- query_states = query_states.to(target_dtype)
671
- key_states = key_states.to(target_dtype)
672
- value_states = value_states.to(target_dtype)
673
-
674
- attn_output = _flash_attention_forward(
675
- query_states,
676
- key_states,
677
- value_states,
678
- attention_mask,
679
- q_len,
680
- position_ids=position_ids,
681
- dropout=dropout_rate,
682
- sliding_window=getattr(self, "sliding_window", None),
683
- use_top_left_mask=self._flash_attn_uses_top_left_mask,
684
- is_causal=self.is_causal,
685
- )
686
-
687
- attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
688
- attn_output = self.o_proj(attn_output)
689
-
690
- if not output_attentions:
691
- attn_weights = None
692
-
693
- return attn_output, attn_weights, past_key_value
694
-
695
-
696
- class LlamaSdpaAttention(LlamaAttention):
697
- """
698
- Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
- `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
- SDPA API.
701
- """
702
-
703
- # Adapted from LlamaAttention.forward
704
- def forward(
705
- self,
706
- hidden_states: torch.Tensor,
707
- attention_mask: Optional[torch.Tensor] = None,
708
- position_ids: Optional[torch.LongTensor] = None,
709
- past_key_value: Optional[Cache] = None,
710
- output_attentions: bool = False,
711
- use_cache: bool = False,
712
- cache_position: Optional[torch.LongTensor] = None,
713
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
714
- **kwargs,
715
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
716
- if output_attentions:
717
- # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
718
- logger.warning_once(
719
- "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, "
720
- '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.'
721
- )
722
- return super().forward(
723
- hidden_states=hidden_states,
724
- attention_mask=attention_mask,
725
- position_ids=position_ids,
726
- past_key_value=past_key_value,
727
- output_attentions=output_attentions,
728
- use_cache=use_cache,
729
- cache_position=cache_position,
730
- position_embeddings=position_embeddings,
731
- )
732
-
733
- bsz, q_len, _ = hidden_states.size()
734
-
735
- query_states = self.q_proj(hidden_states)
736
- key_states = self.k_proj(hidden_states)
737
- value_states = self.v_proj(hidden_states)
738
-
739
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
740
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
741
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
742
-
743
- if position_embeddings is None:
744
- logger.warning_once(
745
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
746
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
747
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
748
- "removed and `position_embeddings` will be mandatory."
749
- )
750
- cos, sin = self.rotary_emb(value_states, position_ids)
751
- else:
752
- cos, sin = position_embeddings
753
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
754
-
755
- # if past_key_value is not None:
756
- # # sin and cos are specific to RoPE models; cache_position needed for the static cache
757
- # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
758
- # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
759
- # if self.num_key_value_heads == self.num_heads:
760
- # head_index_kv = None
761
- # else:
762
- # remaining_head_index = []
763
- # for i in range(self.ori_num_heads):
764
- # if i not in self.pruned_heads:
765
- # remaining_head_index.append(i)
766
- # head_index_kv = torch.tensor(remaining_head_index).long().to(key_states.device)
767
- # head_index_kv = None
768
- # key_states = repeat_kv(key_states, self.num_key_value_groups, index=head_index_kv)
769
- # value_states = repeat_kv(value_states, self.num_key_value_groups, index=head_index_kv)
770
- if query_states.shape[1] != key_states.shape[1]:
771
- num_q_heads = query_states.shape[1]
772
- num_kv_heads = key_states.shape[1]
773
- remaining_head_index = []
774
- for i in range(self.ori_num_heads):
775
- if i not in self.pruned_heads:
776
- remaining_head_index.append(i)
777
- head_index_kv = torch.tensor(remaining_head_index).long().to(key_states.device)
778
- key_states = repeat_kv(key_states, self.num_key_value_groups, index=head_index_kv)
779
- value_states = repeat_kv(value_states, self.num_key_value_groups, index=head_index_kv)
780
-
781
- # if num_q_heads > num_kv_heads:
782
- # # Repeat key and value states to cover all query heads
783
- # repeat_factor = num_q_heads // num_kv_heads # Ceiling division
784
- # key_states = repeat_kv(key_states, repeat_factor)[:, :num_q_heads, :, :]
785
- # value_states = repeat_kv(value_states, repeat_factor)[:, :num_q_heads, :, :]
786
- # else:
787
- # # Truncate key and value states to match query heads
788
- # key_states = key_states[:, :num_q_heads, :, :]
789
- # value_states = value_states[:, :num_q_heads, :, :]
790
- causal_mask = attention_mask
791
- if attention_mask is not None:
792
- causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
793
-
794
- # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
795
- # Reference: https://github.com/pytorch/pytorch/issues/112577.
796
- if query_states.device.type == "cuda" and causal_mask is not None:
797
- query_states = query_states.contiguous()
798
- key_states = key_states.contiguous()
799
- value_states = value_states.contiguous()
800
-
801
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
802
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
803
- is_causal = True if causal_mask is None and q_len > 1 else False
804
-
805
- attn_output = torch.nn.functional.scaled_dot_product_attention(
806
- query_states,
807
- key_states,
808
- value_states,
809
- attn_mask=causal_mask,
810
- dropout_p=self.attention_dropout if self.training else 0.0,
811
- is_causal=is_causal,
812
- )
813
-
814
- attn_output = attn_output.transpose(1, 2).contiguous()
815
- attn_output = attn_output.view(bsz, q_len, -1)
816
-
817
- attn_output = self.o_proj(attn_output)
818
-
819
- return attn_output, None, past_key_value
820
-
821
-
822
- LLAMA_ATTENTION_CLASSES = {
823
- "eager": LlamaAttention,
824
- "flash_attention_2": LlamaFlashAttention2,
825
- "sdpa": LlamaSdpaAttention,
826
- }
827
-
828
-
829
- class LlamaDecoderLayer(nn.Module):
830
- def __init__(self, config: DarwinLMConfig, layer_idx: int):
831
- super().__init__()
832
- self.hidden_size = config.hidden_size
833
- self.layer_idx = layer_idx
834
-
835
- self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
836
-
837
- self.mlp = LlamaMLP(config)
838
- self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
839
- self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
840
-
841
- def forward(
842
- self,
843
- hidden_states: torch.Tensor,
844
- attention_mask: Optional[torch.Tensor] = None,
845
- position_ids: Optional[torch.LongTensor] = None,
846
- past_key_value: Optional[Cache] = None,
847
- output_attentions: Optional[bool] = False,
848
- use_cache: Optional[bool] = False,
849
- cache_position: Optional[torch.LongTensor] = None,
850
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
851
- **kwargs,
852
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
853
- """
854
- Args:
855
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
856
- attention_mask (`torch.FloatTensor`, *optional*):
857
- attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
858
- query_sequence_length, key_sequence_length)` if default attention is used.
859
- output_attentions (`bool`, *optional*):
860
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
861
- returned tensors for more detail.
862
- use_cache (`bool`, *optional*):
863
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
864
- (see `past_key_values`).
865
- past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
866
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
867
- Indices depicting the position of the input sequence tokens in the sequence
868
- position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
869
- Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
870
- with `head_dim` being the embedding dimension of each attention head.
871
- kwargs (`dict`, *optional*):
872
- Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
873
- into the model
874
- """
875
- residual = hidden_states
876
-
877
- hidden_states = self.input_layernorm(hidden_states)
878
-
879
- # Self Attention
880
- # Modified for Time Profiling
881
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
882
- hidden_states,
883
- attention_mask,
884
- position_ids,
885
- past_key_value,
886
- output_attentions,
887
- use_cache,
888
- cache_position,
889
- position_embeddings,
890
- **kwargs,
891
- )
892
- hidden_states = residual + hidden_states
893
-
894
- # Fully Connected
895
- residual = hidden_states
896
- hidden_states = self.post_attention_layernorm(hidden_states)
897
- hidden_states = self.mlp(hidden_states)
898
- hidden_states = residual + hidden_states
899
-
900
- outputs = (hidden_states,)
901
-
902
- if output_attentions:
903
- outputs += (self_attn_weights,)
904
-
905
- if use_cache:
906
- outputs += (present_key_value,)
907
-
908
- return outputs
909
-
910
-
911
- LLAMA_START_DOCSTRING = r"""
912
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
913
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
914
- etc.)
915
-
916
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
917
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
918
- and behavior.
919
-
920
- Parameters:
921
- config ([`DarwinLMConfig`]):
922
- Model configuration class with all the parameters of the model. Initializing with a config file does not
923
- load the weights associated with the model, only the configuration. Check out the
924
- [`~PreTrainedModel.from_pretrained`] method to load the model weights.
925
- """
926
-
927
-
928
- @add_start_docstrings(
929
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
930
- LLAMA_START_DOCSTRING,
931
- )
932
- class LlamaPreTrainedModel(PreTrainedModel):
933
- config_class = DarwinLMConfig
934
- base_model_prefix = "model"
935
- supports_gradient_checkpointing = True
936
- _no_split_modules = ["LlamaDecoderLayer"]
937
- _skip_keys_device_placement = ["past_key_values"]
938
- _supports_flash_attn_2 = True
939
- _supports_sdpa = True
940
- _supports_cache_class = True
941
- _supports_quantized_cache = True
942
- _supports_static_cache = True
943
-
944
- def _init_weights(self, module):
945
- std = self.config.initializer_range
946
- if isinstance(module, nn.Linear):
947
- module.weight.data.normal_(mean=0.0, std=std)
948
- if module.bias is not None:
949
- module.bias.data.zero_()
950
- elif isinstance(module, nn.Embedding):
951
- module.weight.data.normal_(mean=0.0, std=std)
952
- if module.padding_idx is not None:
953
- module.weight.data[module.padding_idx].zero_()
954
-
955
-
956
- LLAMA_INPUTS_DOCSTRING = r"""
957
- Args:
958
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
959
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
960
- it.
961
-
962
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
963
- [`PreTrainedTokenizer.__call__`] for details.
964
-
965
- [What are input IDs?](../glossary#input-ids)
966
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
967
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
968
-
969
- - 1 for tokens that are **not masked**,
970
- - 0 for tokens that are **masked**.
971
-
972
- [What are attention masks?](../glossary#attention-mask)
973
-
974
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
975
- [`PreTrainedTokenizer.__call__`] for details.
976
-
977
- If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
978
- `past_key_values`).
979
-
980
- If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
981
- and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
982
- information on the default strategy.
983
-
984
- - 1 indicates the head is **not masked**,
985
- - 0 indicates the head is **masked**.
986
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
987
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
988
- config.n_positions - 1]`.
989
-
990
- [What are position IDs?](../glossary#position-ids)
991
- past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
992
- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
993
- blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
994
- returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
995
-
996
- Two formats are allowed:
997
- - a [`~cache_utils.Cache`] instance;
998
- - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
999
- shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1000
- cache format.
1001
-
1002
- The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1003
- legacy cache format will be returned.
1004
-
1005
- If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1006
- have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1007
- of shape `(batch_size, sequence_length)`.
1008
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1009
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1010
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1011
- model's internal embedding lookup matrix.
1012
- use_cache (`bool`, *optional*):
1013
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1014
- `past_key_values`).
1015
- output_attentions (`bool`, *optional*):
1016
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1017
- tensors for more detail.
1018
- output_hidden_states (`bool`, *optional*):
1019
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1020
- more detail.
1021
- return_dict (`bool`, *optional*):
1022
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1023
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1024
- Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1025
- this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1026
- the complete sequence length.
1027
- """
1028
-
1029
-
1030
- @add_start_docstrings(
1031
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1032
- LLAMA_START_DOCSTRING,
1033
- )
1034
- class LlamaModel(LlamaPreTrainedModel):
1035
- """
1036
- Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
1037
-
1038
- Args:
1039
- config: DarwinLMConfig
1040
- """
1041
-
1042
- def __init__(self, config: DarwinLMConfig):
1043
- super().__init__(config)
1044
- self.padding_idx = config.pad_token_id
1045
- self.vocab_size = config.vocab_size
1046
-
1047
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1048
- self.layers = nn.ModuleList(
1049
- [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1050
- )
1051
- self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1052
- self.rotary_emb = LlamaRotaryEmbedding(config=config)
1053
- self.gradient_checkpointing = False
1054
-
1055
- # Initialize weights and apply final processing
1056
- self.post_init()
1057
- self.heads_each_attn = config.heads_each_attn
1058
- self.dim_each_mlp = config.dim_each_mlp
1059
- self.kv_ignore = config.kv_ignore
1060
- self.prune_model(self.heads_each_attn, self.dim_each_mlp, self.kv_ignore)
1061
-
1062
-
1063
- def prune_model(self, heads_each_attn, dim_each_mlp, kv_ignore):
1064
- for name, heads_num in heads_each_attn.items():
1065
- layer_idx = int(name.split(".")[0])
1066
- attn = self.layers[layer_idx].self_attn
1067
- if heads_num == 32:
1068
- self.layers[layer_idx].self_attn = NoAttention()
1069
- continue
1070
- heads = [i for i in range(heads_num)]
1071
- attn.prune_heads(heads, kv_ignore)
1072
-
1073
- for name, dim in dim_each_mlp.items():
1074
- layer_idx = int(name.split(".")[0])
1075
- mlp = self.layers[layer_idx].mlp
1076
- if dim == 0:
1077
- mlp.up_proj = NoIntermediate()
1078
- mlp.gate_proj = NoIntermediate()
1079
- mlp.down_proj = NoOutput()
1080
- continue
1081
- dims = [i for i in range(dim)]
1082
- dims = torch.tensor(dims).long()
1083
- mlp.prune_mlp(dims)
1084
-
1085
-
1086
-
1087
- def get_input_embeddings(self):
1088
- return self.embed_tokens
1089
-
1090
- def set_input_embeddings(self, value):
1091
- self.embed_tokens = value
1092
-
1093
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1094
- def forward(
1095
- self,
1096
- input_ids: torch.LongTensor = None,
1097
- attention_mask: Optional[torch.Tensor] = None,
1098
- position_ids: Optional[torch.LongTensor] = None,
1099
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1100
- inputs_embeds: Optional[torch.FloatTensor] = None,
1101
- use_cache: Optional[bool] = None,
1102
- output_attentions: Optional[bool] = None,
1103
- output_hidden_states: Optional[bool] = None,
1104
- return_dict: Optional[bool] = None,
1105
- cache_position: Optional[torch.LongTensor] = None,
1106
- ) -> Union[Tuple, BaseModelOutputWithPast]:
1107
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1108
- output_hidden_states = (
1109
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1110
- )
1111
- use_cache = use_cache if use_cache is not None else self.config.use_cache
1112
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1113
-
1114
- if (input_ids is None) ^ (inputs_embeds is not None):
1115
- raise ValueError(
1116
- "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1117
- )
1118
-
1119
- if self.gradient_checkpointing and self.training and use_cache:
1120
- logger.warning_once(
1121
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1122
- )
1123
- use_cache = False
1124
-
1125
- if inputs_embeds is None:
1126
- inputs_embeds = self.embed_tokens(input_ids)
1127
-
1128
- return_legacy_cache = False
1129
- if (
1130
- use_cache and not isinstance(past_key_values, Cache) and not self.training
1131
- ): # kept for BC (non `Cache` `past_key_values` inputs)
1132
- return_legacy_cache = True
1133
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1134
- logger.warning_once(
1135
- "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1136
- "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/internal/generation_utils#transformers.Cache)"
1137
- )
1138
-
1139
- if cache_position is None:
1140
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1141
- cache_position = torch.arange(
1142
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1143
- )
1144
- if position_ids is None:
1145
- position_ids = cache_position.unsqueeze(0)
1146
-
1147
- causal_mask = self._update_causal_mask(
1148
- attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1149
- )
1150
- hidden_states = inputs_embeds
1151
-
1152
- # create position embeddings to be shared across the decoder layers
1153
- position_embeddings = self.rotary_emb(hidden_states, position_ids)
1154
-
1155
- # decoder layers
1156
- all_hidden_states = () if output_hidden_states else None
1157
- all_self_attns = () if output_attentions else None
1158
- next_decoder_cache = None
1159
-
1160
- for i, decoder_layer in enumerate(self.layers):
1161
- if output_hidden_states:
1162
- all_hidden_states += (hidden_states,)
1163
-
1164
- if self.gradient_checkpointing and self.training:
1165
- layer_outputs = self._gradient_checkpointing_func(
1166
- decoder_layer.__call__,
1167
- hidden_states,
1168
- causal_mask,
1169
- position_ids,
1170
- past_key_values,
1171
- output_attentions,
1172
- use_cache,
1173
- cache_position,
1174
- position_embeddings,
1175
- )
1176
- else:
1177
- layer_outputs = decoder_layer(
1178
- hidden_states,
1179
- causal_mask,
1180
- position_ids,
1181
- past_key_values,
1182
- output_attentions,
1183
- use_cache,
1184
- cache_position,
1185
- position_embeddings,
1186
- )
1187
-
1188
- hidden_states = layer_outputs[0]
1189
-
1190
- if use_cache:
1191
- next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1192
-
1193
- if output_attentions:
1194
- all_self_attns += (layer_outputs[1],)
1195
-
1196
- hidden_states = self.norm(hidden_states)
1197
-
1198
- # add hidden states from the last decoder layer
1199
- if output_hidden_states:
1200
- all_hidden_states += (hidden_states,)
1201
-
1202
- next_cache = next_decoder_cache if use_cache else None
1203
- return_legacy_cache = False
1204
- if return_legacy_cache:
1205
- next_cache = next_cache.to_legacy_cache()
1206
-
1207
- if not return_dict:
1208
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1209
- return BaseModelOutputWithPast(
1210
- last_hidden_state=hidden_states,
1211
- past_key_values=next_cache,
1212
- hidden_states=all_hidden_states,
1213
- attentions=all_self_attns,
1214
- )
1215
-
1216
- def _update_causal_mask(
1217
- self,
1218
- attention_mask: torch.Tensor,
1219
- input_tensor: torch.Tensor,
1220
- cache_position: torch.Tensor,
1221
- past_key_values: Cache,
1222
- output_attentions: bool,
1223
- ):
1224
- if self.config._attn_implementation == "flash_attention_2":
1225
- if attention_mask is not None and 0.0 in attention_mask:
1226
- return attention_mask
1227
- return None
1228
-
1229
- # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1230
- # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1231
- # to infer the attention mask.
1232
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1233
- using_static_cache = isinstance(past_key_values, StaticCache)
1234
-
1235
- # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1236
- if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1237
- if AttentionMaskConverter._ignore_causal_mask_sdpa(
1238
- attention_mask,
1239
- inputs_embeds=input_tensor,
1240
- past_key_values_length=past_seen_tokens,
1241
- is_training=self.training,
1242
- ):
1243
- return None
1244
-
1245
- dtype, device = input_tensor.dtype, input_tensor.device
1246
- min_dtype = torch.finfo(dtype).min
1247
- sequence_length = input_tensor.shape[1]
1248
- if using_static_cache:
1249
- target_length = past_key_values.get_max_length()
1250
- else:
1251
- target_length = (
1252
- attention_mask.shape[-1]
1253
- if isinstance(attention_mask, torch.Tensor)
1254
- else past_seen_tokens + sequence_length + 1
1255
- )
1256
-
1257
- # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1258
- causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1259
- attention_mask,
1260
- sequence_length=sequence_length,
1261
- target_length=target_length,
1262
- dtype=dtype,
1263
- device=device,
1264
- min_dtype=min_dtype,
1265
- cache_position=cache_position,
1266
- batch_size=input_tensor.shape[0],
1267
- )
1268
-
1269
- if (
1270
- self.config._attn_implementation == "sdpa"
1271
- and attention_mask is not None
1272
- and attention_mask.device.type == "cuda"
1273
- and not output_attentions
1274
- ):
1275
- # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1276
- # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1277
- # Details: https://github.com/pytorch/pytorch/issues/110213
1278
- causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1279
-
1280
- return causal_mask
1281
-
1282
-
1283
- class LlamaForCausalLM(LlamaPreTrainedModel):
1284
- _tied_weights_keys = ["lm_head.weight"]
1285
-
1286
- def __init__(self, config):
1287
- super().__init__(config)
1288
- self.model = LlamaModel(config)
1289
- self.vocab_size = config.vocab_size
1290
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1291
-
1292
- # Initialize weights and apply final processing
1293
- self.post_init()
1294
-
1295
- def get_input_embeddings(self):
1296
- return self.model.embed_tokens
1297
-
1298
- def set_input_embeddings(self, value):
1299
- self.model.embed_tokens = value
1300
-
1301
- def get_output_embeddings(self):
1302
- return self.lm_head
1303
-
1304
- def set_output_embeddings(self, new_embeddings):
1305
- self.lm_head = new_embeddings
1306
-
1307
- def set_decoder(self, decoder):
1308
- self.model = decoder
1309
-
1310
- def get_decoder(self):
1311
- return self.model
1312
-
1313
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1314
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1315
- def forward(
1316
- self,
1317
- input_ids: torch.LongTensor = None,
1318
- attention_mask: Optional[torch.Tensor] = None,
1319
- position_ids: Optional[torch.LongTensor] = None,
1320
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1321
- inputs_embeds: Optional[torch.FloatTensor] = None,
1322
- labels: Optional[torch.LongTensor] = None,
1323
- use_cache: Optional[bool] = None,
1324
- output_attentions: Optional[bool] = None,
1325
- output_hidden_states: Optional[bool] = None,
1326
- return_dict: Optional[bool] = None,
1327
- cache_position: Optional[torch.LongTensor] = None,
1328
- num_logits_to_keep: int = 0,
1329
- ) -> Union[Tuple, CausalLMOutputWithPast]:
1330
- r"""
1331
- Args:
1332
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1333
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1334
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1335
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1336
-
1337
- num_logits_to_keep (`int`, *optional*):
1338
- Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1339
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1340
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1341
-
1342
- Returns:
1343
-
1344
- Example:
1345
-
1346
- ```python
1347
- >>> from transformers import AutoTokenizer, LlamaForCausalLM
1348
-
1349
- >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1350
- >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1351
-
1352
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
1353
- >>> inputs = tokenizer(prompt, return_tensors="pt")
1354
-
1355
- >>> # Generate
1356
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1357
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1358
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1359
- ```"""
1360
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1361
- output_hidden_states = (
1362
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1363
- )
1364
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1365
-
1366
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1367
- outputs = self.model(
1368
- input_ids=input_ids,
1369
- attention_mask=attention_mask,
1370
- position_ids=position_ids,
1371
- past_key_values=past_key_values,
1372
- inputs_embeds=inputs_embeds,
1373
- use_cache=use_cache,
1374
- output_attentions=output_attentions,
1375
- output_hidden_states=output_hidden_states,
1376
- return_dict=return_dict,
1377
- cache_position=cache_position,
1378
- )
1379
-
1380
- hidden_states = outputs[0]
1381
- if self.config.pretraining_tp > 1:
1382
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1383
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1384
- logits = torch.cat(logits, dim=-1)
1385
- else:
1386
- if labels is None and not is_torchdynamo_compiling():
1387
- logger.warning_once(
1388
- "Starting from v4.46, the `logits` model output will have the same type as the model (except at train time, where it will always be FP32)"
1389
- )
1390
- # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1391
- # TODO: remove the float() operation in v4.46
1392
- logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
1393
-
1394
- loss = None
1395
- if labels is not None:
1396
- # Upcast to float if we need to compute the loss to avoid potential precision issues
1397
- logits = logits.float()
1398
- # Shift so that tokens < n predict n
1399
- shift_logits = logits[..., :-1, :].contiguous()
1400
- shift_labels = labels[..., 1:].contiguous()
1401
- # Flatten the tokens
1402
- loss_fct = CrossEntropyLoss()
1403
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
1404
- shift_labels = shift_labels.view(-1)
1405
- # Enable model parallelism
1406
- shift_labels = shift_labels.to(shift_logits.device)
1407
- loss = loss_fct(shift_logits, shift_labels)
1408
-
1409
- if not return_dict:
1410
- output = (logits,) + outputs[1:]
1411
- return (loss,) + output if loss is not None else output
1412
-
1413
- return CausalLMOutputWithPast(
1414
- loss=loss,
1415
- logits=logits,
1416
- past_key_values=outputs.past_key_values,
1417
- hidden_states=outputs.hidden_states,
1418
- attentions=outputs.attentions,
1419
- )
1420
-
1421
- def prepare_inputs_for_generation(
1422
- self,
1423
- input_ids,
1424
- past_key_values=None,
1425
- attention_mask=None,
1426
- inputs_embeds=None,
1427
- cache_position=None,
1428
- position_ids=None,
1429
- use_cache=True,
1430
- num_logits_to_keep=0,
1431
- **kwargs,
1432
- ):
1433
- # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1434
- # Exception 1: when passing input_embeds, input_ids may be missing entries
1435
- # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1436
- if past_key_values is not None:
1437
- if inputs_embeds is not None: # Exception 1
1438
- input_ids = input_ids[:, -cache_position.shape[0] :]
1439
- elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1440
- input_ids = input_ids[:, cache_position]
1441
-
1442
- if attention_mask is not None and position_ids is None:
1443
- # create position_ids on the fly for batch generation
1444
- position_ids = attention_mask.long().cumsum(-1) - 1
1445
- position_ids.masked_fill_(attention_mask == 0, 1)
1446
- if past_key_values:
1447
- position_ids = position_ids[:, -input_ids.shape[1] :]
1448
-
1449
- # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1450
- position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1451
-
1452
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1453
- if inputs_embeds is not None and cache_position[0] == 0:
1454
- model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1455
- else:
1456
- # The clone here is for the same reason as for `position_ids`.
1457
- model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1458
-
1459
- if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1460
- if model_inputs["inputs_embeds"] is not None:
1461
- batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1462
- device = model_inputs["inputs_embeds"].device
1463
- else:
1464
- batch_size, sequence_length = model_inputs["input_ids"].shape
1465
- device = model_inputs["input_ids"].device
1466
-
1467
- dtype = self.lm_head.weight.dtype
1468
- min_dtype = torch.finfo(dtype).min
1469
-
1470
- attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1471
- attention_mask,
1472
- sequence_length=sequence_length,
1473
- target_length=past_key_values.get_max_length(),
1474
- dtype=dtype,
1475
- device=device,
1476
- min_dtype=min_dtype,
1477
- cache_position=cache_position,
1478
- batch_size=batch_size,
1479
- )
1480
-
1481
- model_inputs.update(
1482
- {
1483
- "position_ids": position_ids,
1484
- "cache_position": cache_position,
1485
- "past_key_values": past_key_values,
1486
- "use_cache": use_cache,
1487
- "attention_mask": attention_mask,
1488
- "num_logits_to_keep": num_logits_to_keep,
1489
- }
1490
- )
1491
- return model_inputs
1492
-
1493
-
1494
- @add_start_docstrings(
1495
- """
1496
- The LLaMa Model transformer with a sequence classification head on top (linear layer).
1497
-
1498
- [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1499
- (e.g. GPT-2) do.
1500
-
1501
- Since it does classification on the last token, it requires to know the position of the last token. If a
1502
- `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1503
- no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1504
- padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1505
- each row of the batch).
1506
- """,
1507
- LLAMA_START_DOCSTRING,
1508
- )
1509
- class LlamaForSequenceClassification(LlamaPreTrainedModel):
1510
- def __init__(self, config):
1511
- super().__init__(config)
1512
- self.num_labels = config.num_labels
1513
- self.model = LlamaModel(config)
1514
- self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1515
-
1516
- # Initialize weights and apply final processing
1517
- self.post_init()
1518
-
1519
- def get_input_embeddings(self):
1520
- return self.model.embed_tokens
1521
-
1522
- def set_input_embeddings(self, value):
1523
- self.model.embed_tokens = value
1524
-
1525
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1526
- def forward(
1527
- self,
1528
- input_ids: Optional[torch.LongTensor] = None,
1529
- attention_mask: Optional[torch.Tensor] = None,
1530
- position_ids: Optional[torch.LongTensor] = None,
1531
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1532
- inputs_embeds: Optional[torch.FloatTensor] = None,
1533
- labels: Optional[torch.LongTensor] = None,
1534
- use_cache: Optional[bool] = None,
1535
- output_attentions: Optional[bool] = None,
1536
- output_hidden_states: Optional[bool] = None,
1537
- return_dict: Optional[bool] = None,
1538
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1539
- r"""
1540
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1541
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1542
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1543
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1544
- """
1545
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1546
-
1547
- transformer_outputs = self.model(
1548
- input_ids,
1549
- attention_mask=attention_mask,
1550
- position_ids=position_ids,
1551
- past_key_values=past_key_values,
1552
- inputs_embeds=inputs_embeds,
1553
- use_cache=use_cache,
1554
- output_attentions=output_attentions,
1555
- output_hidden_states=output_hidden_states,
1556
- return_dict=return_dict,
1557
- )
1558
- hidden_states = transformer_outputs[0]
1559
- logits = self.score(hidden_states)
1560
-
1561
- if input_ids is not None:
1562
- batch_size = input_ids.shape[0]
1563
- else:
1564
- batch_size = inputs_embeds.shape[0]
1565
-
1566
- if self.config.pad_token_id is None and batch_size != 1:
1567
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1568
- if self.config.pad_token_id is None:
1569
- sequence_lengths = -1
1570
- else:
1571
- if input_ids is not None:
1572
- # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1573
- sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1574
- sequence_lengths = sequence_lengths % input_ids.shape[-1]
1575
- sequence_lengths = sequence_lengths.to(logits.device)
1576
- else:
1577
- sequence_lengths = -1
1578
-
1579
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1580
-
1581
- loss = None
1582
- if labels is not None:
1583
- labels = labels.to(logits.device)
1584
- if self.config.problem_type is None:
1585
- if self.num_labels == 1:
1586
- self.config.problem_type = "regression"
1587
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1588
- self.config.problem_type = "single_label_classification"
1589
- else:
1590
- self.config.problem_type = "multi_label_classification"
1591
-
1592
- if self.config.problem_type == "regression":
1593
- loss_fct = MSELoss()
1594
- if self.num_labels == 1:
1595
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1596
- else:
1597
- loss = loss_fct(pooled_logits, labels)
1598
- elif self.config.problem_type == "single_label_classification":
1599
- loss_fct = CrossEntropyLoss()
1600
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1601
- elif self.config.problem_type == "multi_label_classification":
1602
- loss_fct = BCEWithLogitsLoss()
1603
- loss = loss_fct(pooled_logits, labels)
1604
- if not return_dict:
1605
- output = (pooled_logits,) + transformer_outputs[1:]
1606
- return ((loss,) + output) if loss is not None else output
1607
-
1608
- return SequenceClassifierOutputWithPast(
1609
- loss=loss,
1610
- logits=pooled_logits,
1611
- past_key_values=transformer_outputs.past_key_values,
1612
- hidden_states=transformer_outputs.hidden_states,
1613
- attentions=transformer_outputs.attentions,
1614
- )
1615
-
1616
-
1617
- @add_start_docstrings(
1618
- """
1619
- The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1620
- SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1621
- """,
1622
- LLAMA_START_DOCSTRING,
1623
- )
1624
- class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1625
- base_model_prefix = "transformer"
1626
-
1627
- # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1628
- def __init__(self, config):
1629
- super().__init__(config)
1630
- self.transformer = LlamaModel(config)
1631
- self.qa_outputs = nn.Linear(config.hidden_size, 2)
1632
-
1633
- # Initialize weights and apply final processing
1634
- self.post_init()
1635
-
1636
- def get_input_embeddings(self):
1637
- return self.transformer.embed_tokens
1638
-
1639
- def set_input_embeddings(self, value):
1640
- self.transformer.embed_tokens = value
1641
-
1642
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1643
- def forward(
1644
- self,
1645
- input_ids: Optional[torch.LongTensor] = None,
1646
- attention_mask: Optional[torch.FloatTensor] = None,
1647
- position_ids: Optional[torch.LongTensor] = None,
1648
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1649
- inputs_embeds: Optional[torch.FloatTensor] = None,
1650
- start_positions: Optional[torch.LongTensor] = None,
1651
- end_positions: Optional[torch.LongTensor] = None,
1652
- output_attentions: Optional[bool] = None,
1653
- output_hidden_states: Optional[bool] = None,
1654
- return_dict: Optional[bool] = None,
1655
- ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1656
- r"""
1657
- start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1658
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
1659
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1660
- are not taken into account for computing the loss.
1661
- end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1662
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
1663
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1664
- are not taken into account for computing the loss.
1665
- """
1666
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1667
-
1668
- outputs = self.transformer(
1669
- input_ids,
1670
- attention_mask=attention_mask,
1671
- position_ids=position_ids,
1672
- past_key_values=past_key_values,
1673
- inputs_embeds=inputs_embeds,
1674
- output_attentions=output_attentions,
1675
- output_hidden_states=output_hidden_states,
1676
- return_dict=return_dict,
1677
- )
1678
-
1679
- sequence_output = outputs[0]
1680
-
1681
- logits = self.qa_outputs(sequence_output)
1682
- start_logits, end_logits = logits.split(1, dim=-1)
1683
- start_logits = start_logits.squeeze(-1).contiguous()
1684
- end_logits = end_logits.squeeze(-1).contiguous()
1685
-
1686
- total_loss = None
1687
- if start_positions is not None and end_positions is not None:
1688
- # If we are on multi-GPU, split add a dimension
1689
- if len(start_positions.size()) > 1:
1690
- start_positions = start_positions.squeeze(-1).to(start_logits.device)
1691
- if len(end_positions.size()) > 1:
1692
- end_positions = end_positions.squeeze(-1).to(end_logits.device)
1693
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
1694
- ignored_index = start_logits.size(1)
1695
- start_positions = start_positions.clamp(0, ignored_index)
1696
- end_positions = end_positions.clamp(0, ignored_index)
1697
-
1698
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1699
- start_loss = loss_fct(start_logits, start_positions)
1700
- end_loss = loss_fct(end_logits, end_positions)
1701
- total_loss = (start_loss + end_loss) / 2
1702
-
1703
- if not return_dict:
1704
- output = (start_logits, end_logits) + outputs[2:]
1705
- return ((total_loss,) + output) if total_loss is not None else output
1706
-
1707
- return QuestionAnsweringModelOutput(
1708
- loss=total_loss,
1709
- start_logits=start_logits,
1710
- end_logits=end_logits,
1711
- hidden_states=outputs.hidden_states,
1712
- attentions=outputs.attentions,
1713
- )
1714
-
1715
-
1716
- @add_start_docstrings(
1717
- """
1718
- The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1719
- output) e.g. for Named-Entity-Recognition (NER) tasks.
1720
- """,
1721
- LLAMA_START_DOCSTRING,
1722
- )
1723
- class LlamaForTokenClassification(LlamaPreTrainedModel):
1724
- def __init__(self, config):
1725
- super().__init__(config)
1726
- self.num_labels = config.num_labels
1727
- self.model = LlamaModel(config)
1728
- if getattr(config, "classifier_dropout", None) is not None:
1729
- classifier_dropout = config.classifier_dropout
1730
- elif getattr(config, "hidden_dropout", None) is not None:
1731
- classifier_dropout = config.hidden_dropout
1732
- else:
1733
- classifier_dropout = 0.1
1734
- self.dropout = nn.Dropout(classifier_dropout)
1735
- self.score = nn.Linear(config.hidden_size, config.num_labels)
1736
-
1737
- # Initialize weights and apply final processing
1738
- self.post_init()
1739
-
1740
- def get_input_embeddings(self):
1741
- return self.model.embed_tokens
1742
-
1743
- def set_input_embeddings(self, value):
1744
- self.model.embed_tokens = value
1745
-
1746
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1747
- def forward(
1748
- self,
1749
- input_ids: Optional[torch.LongTensor] = None,
1750
- attention_mask: Optional[torch.Tensor] = None,
1751
- position_ids: Optional[torch.LongTensor] = None,
1752
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1753
- inputs_embeds: Optional[torch.FloatTensor] = None,
1754
- labels: Optional[torch.LongTensor] = None,
1755
- use_cache: Optional[bool] = None,
1756
- output_attentions: Optional[bool] = None,
1757
- output_hidden_states: Optional[bool] = None,
1758
- return_dict: Optional[bool] = None,
1759
- ) -> Union[Tuple, TokenClassifierOutput]:
1760
- r"""
1761
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1762
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1763
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1764
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1765
- """
1766
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1767
-
1768
- outputs = self.model(
1769
- input_ids,
1770
- attention_mask=attention_mask,
1771
- position_ids=position_ids,
1772
- past_key_values=past_key_values,
1773
- inputs_embeds=inputs_embeds,
1774
- use_cache=use_cache,
1775
- output_attentions=output_attentions,
1776
- output_hidden_states=output_hidden_states,
1777
- return_dict=return_dict,
1778
- )
1779
- sequence_output = outputs[0]
1780
- sequence_output = self.dropout(sequence_output)
1781
- logits = self.score(sequence_output)
1782
-
1783
- loss = None
1784
- if labels is not None:
1785
- loss_fct = CrossEntropyLoss()
1786
- loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1787
-
1788
- if not return_dict:
1789
- output = (logits,) + outputs[2:]
1790
- return ((loss,) + output) if loss is not None else output
1791
-
1792
- return TokenClassifierOutput(
1793
- loss=loss,
1794
- logits=logits,
1795
- hidden_states=outputs.hidden_states,
1796
- attentions=outputs.attentions,
1797
- )