emozilla commited on
Commit
c420b13
1 Parent(s): 307dab4

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_llama.py +188 -0
  2. modeling_llama_yarn.py +1577 -0
configuration_llama.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class LlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ pretraining_tp (`int`, *optional*, defaults to `1`):
62
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
63
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
64
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
65
+ issue](https://github.com/pytorch/pytorch/issues/76232).
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
70
+ just in case (e.g., 512 or 1024 or 2048).
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`.
78
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling
82
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
83
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
89
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
90
+ attention_dropout (`float`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the attention probabilities.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import LlamaModel, LlamaConfig
97
+
98
+ >>> # Initializing a LLaMA llama-7b style configuration
99
+ >>> configuration = LlamaConfig()
100
+
101
+ >>> # Initializing a model from the llama-7b style configuration
102
+ >>> model = LlamaModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+ model_type = "llama"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+
110
+ def __init__(
111
+ self,
112
+ vocab_size=32000,
113
+ hidden_size=4096,
114
+ intermediate_size=11008,
115
+ num_hidden_layers=32,
116
+ num_attention_heads=32,
117
+ num_key_value_heads=None,
118
+ hidden_act="silu",
119
+ max_position_embeddings=2048,
120
+ initializer_range=0.02,
121
+ rms_norm_eps=1e-6,
122
+ use_cache=True,
123
+ pad_token_id=0,
124
+ bos_token_id=1,
125
+ eos_token_id=2,
126
+ pretraining_tp=1,
127
+ tie_word_embeddings=False,
128
+ rope_theta=10000,
129
+ rope_scaling=None,
130
+ attention_bias=False,
131
+ attention_dropout=0.0,
132
+ **kwargs,
133
+ ):
134
+ self.vocab_size = vocab_size
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.hidden_size = hidden_size
137
+ self.intermediate_size = intermediate_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+
141
+ # for backward compatibility
142
+ if num_key_value_heads is None:
143
+ num_key_value_heads = num_attention_heads
144
+
145
+ self.num_key_value_heads = num_key_value_heads
146
+ self.hidden_act = hidden_act
147
+ self.initializer_range = initializer_range
148
+ self.rms_norm_eps = rms_norm_eps
149
+ self.pretraining_tp = pretraining_tp
150
+ self.use_cache = use_cache
151
+ self.rope_theta = rope_theta
152
+ self.rope_scaling = rope_scaling
153
+ self._rope_scaling_validation()
154
+ self.attention_bias = attention_bias
155
+ self.attention_dropout = attention_dropout
156
+
157
+ super().__init__(
158
+ pad_token_id=pad_token_id,
159
+ bos_token_id=bos_token_id,
160
+ eos_token_id=eos_token_id,
161
+ tie_word_embeddings=tie_word_embeddings,
162
+ **kwargs,
163
+ )
164
+
165
+ def _rope_scaling_validation(self):
166
+ """
167
+ Validate the `rope_scaling` configuration.
168
+ """
169
+ if self.rope_scaling is None:
170
+ return
171
+
172
+ if not isinstance(self.rope_scaling, dict):
173
+ raise ValueError(
174
+ "`rope_scaling` must be a dictionary, "
175
+ f"got {self.rope_scaling}"
176
+ )
177
+ rope_scaling_type = self.rope_scaling.get("type", None)
178
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
179
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", "yarn", "dynamic-yarn"]:
180
+ raise ValueError(
181
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic', 'yarn', 'dynamic-yarn'], got {rope_scaling_type}"
182
+ )
183
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
184
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
185
+ if rope_scaling_type == "yarn" or rope_scaling_type == "dynamic-yarn":
186
+ original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)
187
+ if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
188
+ raise ValueError(f"`rope_scaling.original_max_position_embeddings` must be set to an int when using yarn, and dynamic-yarn")
modeling_llama_yarn.py ADDED
@@ -0,0 +1,1577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_llama import LlamaConfig
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
60
+ # It means that the function will not be traced through and simply appear as a node in the graph.
61
+ if is_torch_fx_available():
62
+ if not is_torch_greater_or_equal_than_1_13:
63
+ import torch.fx
64
+
65
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
66
+
67
+
68
+ logger = logging.get_logger(__name__)
69
+
70
+ _CONFIG_FOR_DOC = "LlamaConfig"
71
+
72
+
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
86
+ warnings.warn(
87
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
88
+ )
89
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
90
+
91
+
92
+ def _make_causal_mask(
93
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
94
+ ):
95
+ warnings.warn(
96
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
97
+ )
98
+ return AttentionMaskConverter._make_causal_mask(
99
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
100
+ )
101
+
102
+ # Inverse dim formula to find dim based on number of rotations
103
+ def _yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
104
+ return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
105
+
106
+ # Find dim range bounds based on rotations
107
+ def _yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
108
+ low = math.floor(_yarn_find_correction_dim(
109
+ low_rot, dim, base, max_position_embeddings))
110
+ high = math.ceil(_yarn_find_correction_dim(
111
+ high_rot, dim, base, max_position_embeddings))
112
+ return max(low, 0), min(high, dim-1) # Clamp values just in case
113
+
114
+ def _yarn_linear_ramp_mask(min, max, dim):
115
+ if min == max:
116
+ max += 0.001 # Prevent singularity
117
+
118
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
119
+ ramp_func = torch.clamp(linear_func, 0, 1)
120
+ return ramp_func
121
+
122
+ def _yarn_get_mscale(scale=1):
123
+ if scale <= 1:
124
+ return 1.0
125
+ return 0.1 * math.log(scale) + 1.0
126
+
127
+ class LlamaRMSNorm(nn.Module):
128
+ def __init__(self, hidden_size, eps=1e-6):
129
+ """
130
+ LlamaRMSNorm is equivalent to T5LayerNorm
131
+ """
132
+ super().__init__()
133
+ self.weight = nn.Parameter(torch.ones(hidden_size))
134
+ self.variance_epsilon = eps
135
+
136
+ def forward(self, hidden_states):
137
+ input_dtype = hidden_states.dtype
138
+ hidden_states = hidden_states.to(torch.float32)
139
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
140
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
141
+ return self.weight * hidden_states.to(input_dtype)
142
+
143
+
144
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
145
+
146
+
147
+ class LlamaRotaryEmbedding(nn.Module):
148
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
149
+ super().__init__()
150
+
151
+ self.dim = dim
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.base = base
154
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
155
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
156
+
157
+ # Build here to make `torch.jit.trace` work.
158
+ self._set_cos_sin_cache(
159
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
160
+ )
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
165
+
166
+ freqs = torch.outer(t, self.inv_freq)
167
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
170
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
171
+
172
+ def forward(self, x, seq_len=None):
173
+ # x: [bs, num_attention_heads, seq_len, head_size]
174
+ if seq_len > self.max_seq_len_cached:
175
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
176
+
177
+ return (
178
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
179
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
180
+ )
181
+
182
+
183
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
184
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
185
+
186
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
187
+ self.scaling_factor = scaling_factor
188
+ super().__init__(dim, max_position_embeddings, base, device)
189
+
190
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
191
+ self.max_seq_len_cached = seq_len
192
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
193
+ t = t / self.scaling_factor
194
+
195
+ freqs = torch.outer(t, self.inv_freq)
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1)
198
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
199
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
200
+
201
+
202
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
203
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
204
+
205
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
206
+ self.scaling_factor = scaling_factor
207
+ super().__init__(dim, max_position_embeddings, base, device)
208
+
209
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
210
+ self.max_seq_len_cached = seq_len
211
+
212
+ if seq_len > self.max_position_embeddings:
213
+ base = self.base * (
214
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
215
+ ) ** (self.dim / (self.dim - 2))
216
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
217
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
218
+
219
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
220
+
221
+ freqs = torch.outer(t, self.inv_freq)
222
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
223
+ emb = torch.cat((freqs, freqs), dim=-1)
224
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
225
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
226
+
227
+
228
+ class LlamaYaRNScaledRotaryEmbedding(torch.nn.Module):
229
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
230
+ super().__init__()
231
+
232
+ self.dim = dim
233
+ self.max_position_embeddings = max_position_embeddings
234
+ self.base = base
235
+ self.scale = scale
236
+ self.original_max_position_embeddings = original_max_position_embeddings
237
+ self.extrapolation_factor = extrapolation_factor
238
+ self.attn_factor = attn_factor
239
+ self.beta_fast = beta_fast
240
+ self.beta_slow = beta_slow
241
+
242
+ self.yarn(device)
243
+
244
+ # Build here to make `torch.jit.trace` work.
245
+ self.max_seq_len_cached = max_position_embeddings
246
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
247
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
248
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
249
+ emb = torch.cat((freqs, freqs), dim=-1)
250
+ dtype = torch.get_default_dtype()
251
+
252
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
253
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
254
+
255
+ def forward(self, x, seq_len=None):
256
+ # x: [bs, num_attention_heads, seq_len, head_size]
257
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
258
+ if seq_len > self.max_seq_len_cached:
259
+ self.max_seq_len_cached = seq_len
260
+
261
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
262
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
263
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
264
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
265
+
266
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
267
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
268
+ return (
269
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
270
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
271
+ )
272
+
273
+ def yarn(self, device):
274
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
275
+ inv_freq_extrapolation = 1.0 / pos_freqs
276
+ inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
277
+
278
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
279
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
280
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
281
+
282
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
283
+ self.mscale = float(_yarn_get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
284
+
285
+
286
+ class LlamaDynamicYaRNScaledRotaryEmbedding(torch.nn.Module):
287
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
288
+ super().__init__()
289
+
290
+ self.dim = dim
291
+ self.max_position_embeddings = max_position_embeddings
292
+ self.base = base
293
+ self.original_max_position_embeddings = original_max_position_embeddings
294
+ self.extrapolation_factor = extrapolation_factor
295
+ self.attn_factor = attn_factor
296
+ self.beta_fast = beta_fast
297
+ self.beta_slow = beta_slow
298
+
299
+ if finetuned:
300
+ self.yarn(self.max_position_embeddings / self.original_max_position_embeddings, device)
301
+ else:
302
+ inv_freq = 1.0 / \
303
+ (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
304
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
305
+ self.mscale = 1
306
+
307
+ # Build here to make `torch.jit.trace` work.
308
+ self.max_seq_len_cached = max_position_embeddings
309
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
310
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
311
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
312
+ emb = torch.cat((freqs, freqs), dim=-1)
313
+ dtype = torch.get_default_dtype()
314
+
315
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
316
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
317
+
318
+ def forward(self, x, seq_len=None):
319
+ # x: [bs, num_attention_heads, seq_len, head_size]
320
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
321
+ if seq_len > self.max_seq_len_cached:
322
+ self.max_seq_len_cached = seq_len
323
+
324
+ self.yarn(seq_len / self.max_position_embeddings, x.device)
325
+
326
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
327
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
328
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
329
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
330
+
331
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
332
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
333
+ return (
334
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
335
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
336
+ )
337
+
338
+ def yarn(self, scale, device):
339
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
340
+ inv_freq_extrapolation = 1.0 / pos_freqs
341
+ inv_freq_interpolation = 1.0 / (scale * pos_freqs)
342
+
343
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
344
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
345
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
346
+
347
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
348
+ self.mscale = float(_yarn_get_mscale(scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
349
+
350
+
351
+ def rotate_half(x):
352
+ """Rotates half the hidden dims of the input."""
353
+ x1 = x[..., : x.shape[-1] // 2]
354
+ x2 = x[..., x.shape[-1] // 2 :]
355
+ return torch.cat((-x2, x1), dim=-1)
356
+
357
+
358
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
359
+ """Applies Rotary Position Embedding to the query and key tensors.
360
+
361
+ Args:
362
+ q (`torch.Tensor`): The query tensor.
363
+ k (`torch.Tensor`): The key tensor.
364
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
365
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
366
+ position_ids (`torch.Tensor`):
367
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
368
+ used to pass offsetted position ids when working with a KV-cache.
369
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
370
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
371
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
372
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
373
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
374
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
375
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
376
+ Returns:
377
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
378
+ """
379
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
380
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
381
+ q_embed = (q * cos) + (rotate_half(q) * sin)
382
+ k_embed = (k * cos) + (rotate_half(k) * sin)
383
+ return q_embed, k_embed
384
+
385
+
386
+ class LlamaMLP(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.config = config
390
+ self.hidden_size = config.hidden_size
391
+ self.intermediate_size = config.intermediate_size
392
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
393
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
394
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
395
+ self.act_fn = ACT2FN[config.hidden_act]
396
+
397
+ def forward(self, x):
398
+ if self.config.pretraining_tp > 1:
399
+ slice = self.intermediate_size // self.config.pretraining_tp
400
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
401
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
402
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
403
+
404
+ gate_proj = torch.cat(
405
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
406
+ )
407
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
408
+
409
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
410
+ down_proj = [
411
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
412
+ ]
413
+ down_proj = sum(down_proj)
414
+ else:
415
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
416
+
417
+ return down_proj
418
+
419
+
420
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
421
+ """
422
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
423
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
424
+ """
425
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
426
+ if n_rep == 1:
427
+ return hidden_states
428
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
429
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
430
+
431
+
432
+ class LlamaAttention(nn.Module):
433
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
434
+
435
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
436
+ super().__init__()
437
+ self.config = config
438
+ self.layer_idx = layer_idx
439
+ if layer_idx is None:
440
+ logger.warning_once(
441
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
442
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
443
+ "when creating this class."
444
+ )
445
+
446
+ self.attention_dropout = config.attention_dropout
447
+ self.hidden_size = config.hidden_size
448
+ self.num_heads = config.num_attention_heads
449
+ self.head_dim = self.hidden_size // self.num_heads
450
+ self.num_key_value_heads = config.num_key_value_heads
451
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
452
+ self.max_position_embeddings = config.max_position_embeddings
453
+ self.rope_theta = config.rope_theta
454
+ self.is_causal = True
455
+
456
+ if (self.head_dim * self.num_heads) != self.hidden_size:
457
+ raise ValueError(
458
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
459
+ f" and `num_heads`: {self.num_heads})."
460
+ )
461
+
462
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
463
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
464
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
465
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
466
+ self._init_rope()
467
+
468
+ def _init_rope(self):
469
+ if self.config.rope_scaling is None:
470
+ self.rotary_emb = LlamaRotaryEmbedding(
471
+ self.head_dim,
472
+ max_position_embeddings=self.max_position_embeddings,
473
+ base=self.rope_theta,
474
+ )
475
+ else:
476
+ scaling_type = self.config.rope_scaling["type"]
477
+ scaling_factor = self.config.rope_scaling["factor"]
478
+ if scaling_type == "linear":
479
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
480
+ self.head_dim,
481
+ max_position_embeddings=self.max_position_embeddings,
482
+ scaling_factor=scaling_factor,
483
+ base=self.rope_theta,
484
+ )
485
+ elif scaling_type == "dynamic":
486
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
487
+ self.head_dim,
488
+ max_position_embeddings=self.max_position_embeddings,
489
+ scaling_factor=scaling_factor,
490
+ base=self.rope_theta,
491
+ )
492
+ elif scaling_type == "yarn":
493
+ original_max_position_embeddings = self.config.rope_scaling["original_max_position_embeddings"]
494
+ self.rotary_emb = LlamaYaRNScaledRotaryEmbedding(
495
+ self.head_dim,
496
+ max_position_embeddings=self.max_position_embeddings,
497
+ scale=scaling_factor,
498
+ original_max_position_embeddings=original_max_position_embeddings
499
+ )
500
+ elif scaling_type == "dynamic-yarn":
501
+ original_max_position_embeddings = self.config.rope_scaling["original_max_position_embeddings"]
502
+ self.rotary_emb = LlamaDynamicYaRNScaledRotaryEmbedding(
503
+ self.head_dim,
504
+ max_position_embeddings=self.max_position_embeddings,
505
+ original_max_position_embeddings=original_max_position_embeddings
506
+ )
507
+ else:
508
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
509
+
510
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
511
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.Tensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_value: Optional[Cache] = None,
519
+ output_attentions: bool = False,
520
+ use_cache: bool = False,
521
+ **kwargs,
522
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
523
+ if "padding_mask" in kwargs:
524
+ warnings.warn(
525
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
526
+ )
527
+
528
+ bsz, q_len, _ = hidden_states.size()
529
+
530
+ if self.config.pretraining_tp > 1:
531
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
532
+ query_slices = self.q_proj.weight.split(
533
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
534
+ )
535
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
536
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
537
+
538
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
539
+ query_states = torch.cat(query_states, dim=-1)
540
+
541
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
542
+ key_states = torch.cat(key_states, dim=-1)
543
+
544
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
545
+ value_states = torch.cat(value_states, dim=-1)
546
+
547
+ else:
548
+ query_states = self.q_proj(hidden_states)
549
+ key_states = self.k_proj(hidden_states)
550
+ value_states = self.v_proj(hidden_states)
551
+
552
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
553
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
554
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
555
+
556
+ kv_seq_len = key_states.shape[-2]
557
+ if past_key_value is not None:
558
+ if self.layer_idx is None:
559
+ raise ValueError(
560
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
561
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
562
+ "with a layer index."
563
+ )
564
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
565
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
566
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
567
+
568
+ if past_key_value is not None:
569
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
570
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
571
+
572
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
573
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
574
+
575
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
576
+
577
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
578
+ raise ValueError(
579
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
580
+ f" {attn_weights.size()}"
581
+ )
582
+
583
+ if attention_mask is not None:
584
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
585
+ raise ValueError(
586
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
587
+ )
588
+ attn_weights = attn_weights + attention_mask
589
+
590
+ # upcast attention to fp32
591
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
592
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
593
+ attn_output = torch.matmul(attn_weights, value_states)
594
+
595
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
596
+ raise ValueError(
597
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
598
+ f" {attn_output.size()}"
599
+ )
600
+
601
+ attn_output = attn_output.transpose(1, 2).contiguous()
602
+
603
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
604
+
605
+ if self.config.pretraining_tp > 1:
606
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
607
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
608
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
609
+ else:
610
+ attn_output = self.o_proj(attn_output)
611
+
612
+ if not output_attentions:
613
+ attn_weights = None
614
+
615
+ return attn_output, attn_weights, past_key_value
616
+
617
+
618
+ class LlamaFlashAttention2(LlamaAttention):
619
+ """
620
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
621
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
622
+ flash attention and deal with padding tokens in case the input contains any of them.
623
+ """
624
+
625
+ def __init__(self, *args, **kwargs):
626
+ super().__init__(*args, **kwargs)
627
+
628
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
629
+ # 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.
630
+ # 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).
631
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
632
+
633
+ def forward(
634
+ self,
635
+ hidden_states: torch.Tensor,
636
+ attention_mask: Optional[torch.LongTensor] = None,
637
+ position_ids: Optional[torch.LongTensor] = None,
638
+ past_key_value: Optional[Cache] = None,
639
+ output_attentions: bool = False,
640
+ use_cache: bool = False,
641
+ **kwargs,
642
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
643
+ # LlamaFlashAttention2 attention does not support output_attentions
644
+ if "padding_mask" in kwargs:
645
+ warnings.warn(
646
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
647
+ )
648
+
649
+ # overwrite attention_mask with padding_mask
650
+ attention_mask = kwargs.pop("padding_mask")
651
+
652
+ output_attentions = False
653
+
654
+ bsz, q_len, _ = hidden_states.size()
655
+
656
+ query_states = self.q_proj(hidden_states)
657
+ key_states = self.k_proj(hidden_states)
658
+ value_states = self.v_proj(hidden_states)
659
+
660
+ # Flash attention requires the input to have the shape
661
+ # batch_size x seq_length x head_dim x hidden_dim
662
+ # therefore we just need to keep the original shape
663
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
664
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
665
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
666
+
667
+ kv_seq_len = key_states.shape[-2]
668
+ if past_key_value is not None:
669
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
670
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
671
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
672
+
673
+ if past_key_value is not None:
674
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
675
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
676
+
677
+ # 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
678
+ # to be able to avoid many of these transpose/reshape/view.
679
+ query_states = query_states.transpose(1, 2)
680
+ key_states = key_states.transpose(1, 2)
681
+ value_states = value_states.transpose(1, 2)
682
+
683
+ dropout_rate = self.attention_dropout if self.training else 0.0
684
+
685
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
686
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
687
+ # cast them back in the correct dtype just to be sure everything works as expected.
688
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
689
+ # in fp32. (LlamaRMSNorm handles it correctly)
690
+
691
+ input_dtype = query_states.dtype
692
+ if input_dtype == torch.float32:
693
+ if torch.is_autocast_enabled():
694
+ target_dtype = torch.get_autocast_gpu_dtype()
695
+ # Handle the case where the model is quantized
696
+ elif hasattr(self.config, "_pre_quantization_dtype"):
697
+ target_dtype = self.config._pre_quantization_dtype
698
+ else:
699
+ target_dtype = self.q_proj.weight.dtype
700
+
701
+ logger.warning_once(
702
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
703
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
704
+ f" {target_dtype}."
705
+ )
706
+
707
+ query_states = query_states.to(target_dtype)
708
+ key_states = key_states.to(target_dtype)
709
+ value_states = value_states.to(target_dtype)
710
+
711
+ attn_output = self._flash_attention_forward(
712
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
713
+ )
714
+
715
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
716
+ attn_output = self.o_proj(attn_output)
717
+
718
+ if not output_attentions:
719
+ attn_weights = None
720
+
721
+ return attn_output, attn_weights, past_key_value
722
+
723
+ def _flash_attention_forward(
724
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
725
+ ):
726
+ """
727
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
728
+ first unpad the input, then computes the attention scores and pad the final attention scores.
729
+
730
+ Args:
731
+ query_states (`torch.Tensor`):
732
+ Input query states to be passed to Flash Attention API
733
+ key_states (`torch.Tensor`):
734
+ Input key states to be passed to Flash Attention API
735
+ value_states (`torch.Tensor`):
736
+ Input value states to be passed to Flash Attention API
737
+ attention_mask (`torch.Tensor`):
738
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
739
+ position of padding tokens and 1 for the position of non-padding tokens.
740
+ dropout (`int`, *optional*):
741
+ Attention dropout
742
+ softmax_scale (`float`, *optional*):
743
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
744
+ """
745
+ if not self._flash_attn_uses_top_left_mask:
746
+ causal = self.is_causal
747
+ else:
748
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
749
+ causal = self.is_causal and query_length != 1
750
+
751
+ # Contains at least one padding token in the sequence
752
+ if attention_mask is not None:
753
+ batch_size = query_states.shape[0]
754
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
755
+ query_states, key_states, value_states, attention_mask, query_length
756
+ )
757
+
758
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
759
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
760
+
761
+ attn_output_unpad = flash_attn_varlen_func(
762
+ query_states,
763
+ key_states,
764
+ value_states,
765
+ cu_seqlens_q=cu_seqlens_q,
766
+ cu_seqlens_k=cu_seqlens_k,
767
+ max_seqlen_q=max_seqlen_in_batch_q,
768
+ max_seqlen_k=max_seqlen_in_batch_k,
769
+ dropout_p=dropout,
770
+ softmax_scale=softmax_scale,
771
+ causal=causal,
772
+ )
773
+
774
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
775
+ else:
776
+ attn_output = flash_attn_func(
777
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
778
+ )
779
+
780
+ return attn_output
781
+
782
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
783
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
784
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
785
+
786
+ key_layer = index_first_axis(
787
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
788
+ )
789
+ value_layer = index_first_axis(
790
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
791
+ )
792
+ if query_length == kv_seq_len:
793
+ query_layer = index_first_axis(
794
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
795
+ )
796
+ cu_seqlens_q = cu_seqlens_k
797
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
798
+ indices_q = indices_k
799
+ elif query_length == 1:
800
+ max_seqlen_in_batch_q = 1
801
+ cu_seqlens_q = torch.arange(
802
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
803
+ ) # There is a memcpy here, that is very bad.
804
+ indices_q = cu_seqlens_q[:-1]
805
+ query_layer = query_layer.squeeze(1)
806
+ else:
807
+ # The -q_len: slice assumes left padding.
808
+ attention_mask = attention_mask[:, -query_length:]
809
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
810
+
811
+ return (
812
+ query_layer,
813
+ key_layer,
814
+ value_layer,
815
+ indices_q,
816
+ (cu_seqlens_q, cu_seqlens_k),
817
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
818
+ )
819
+
820
+
821
+ class LlamaSdpaAttention(LlamaAttention):
822
+ """
823
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
824
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
825
+ SDPA API.
826
+ """
827
+
828
+ # Adapted from LlamaAttention.forward
829
+ def forward(
830
+ self,
831
+ hidden_states: torch.Tensor,
832
+ attention_mask: Optional[torch.Tensor] = None,
833
+ position_ids: Optional[torch.LongTensor] = None,
834
+ past_key_value: Optional[Cache] = None,
835
+ output_attentions: bool = False,
836
+ use_cache: bool = False,
837
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
838
+ if output_attentions:
839
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
840
+ logger.warning_once(
841
+ "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, "
842
+ '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.'
843
+ )
844
+ return super().forward(
845
+ hidden_states=hidden_states,
846
+ attention_mask=attention_mask,
847
+ position_ids=position_ids,
848
+ past_key_value=past_key_value,
849
+ output_attentions=output_attentions,
850
+ use_cache=use_cache,
851
+ )
852
+
853
+ bsz, q_len, _ = hidden_states.size()
854
+
855
+ query_states = self.q_proj(hidden_states)
856
+ key_states = self.k_proj(hidden_states)
857
+ value_states = self.v_proj(hidden_states)
858
+
859
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
860
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
861
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
862
+
863
+ kv_seq_len = key_states.shape[-2]
864
+ if past_key_value is not None:
865
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
866
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
867
+
868
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
869
+
870
+ if past_key_value is not None:
871
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
872
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
873
+
874
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
875
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
876
+
877
+ if attention_mask is not None:
878
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
879
+ raise ValueError(
880
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
881
+ )
882
+
883
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
884
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
885
+ if query_states.device.type == "cuda" and attention_mask is not None:
886
+ query_states = query_states.contiguous()
887
+ key_states = key_states.contiguous()
888
+ value_states = value_states.contiguous()
889
+
890
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
891
+ query_states,
892
+ key_states,
893
+ value_states,
894
+ attn_mask=attention_mask,
895
+ dropout_p=self.attention_dropout if self.training else 0.0,
896
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
897
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
898
+ )
899
+
900
+ attn_output = attn_output.transpose(1, 2).contiguous()
901
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
902
+
903
+ attn_output = self.o_proj(attn_output)
904
+
905
+ return attn_output, None, past_key_value
906
+
907
+
908
+ LLAMA_ATTENTION_CLASSES = {
909
+ "eager": LlamaAttention,
910
+ "flash_attention_2": LlamaFlashAttention2,
911
+ "sdpa": LlamaSdpaAttention,
912
+ }
913
+
914
+
915
+ class LlamaDecoderLayer(nn.Module):
916
+ def __init__(self, config: LlamaConfig, layer_idx: int):
917
+ super().__init__()
918
+ self.hidden_size = config.hidden_size
919
+
920
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
921
+
922
+ self.mlp = LlamaMLP(config)
923
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
924
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
925
+
926
+ def forward(
927
+ self,
928
+ hidden_states: torch.Tensor,
929
+ attention_mask: Optional[torch.Tensor] = None,
930
+ position_ids: Optional[torch.LongTensor] = None,
931
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
932
+ output_attentions: Optional[bool] = False,
933
+ use_cache: Optional[bool] = False,
934
+ **kwargs,
935
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
936
+ """
937
+ Args:
938
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
939
+ attention_mask (`torch.FloatTensor`, *optional*):
940
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
941
+ query_sequence_length, key_sequence_length)` if default attention is used.
942
+ output_attentions (`bool`, *optional*):
943
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
944
+ returned tensors for more detail.
945
+ use_cache (`bool`, *optional*):
946
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
947
+ (see `past_key_values`).
948
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
949
+ """
950
+ if "padding_mask" in kwargs:
951
+ warnings.warn(
952
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
953
+ )
954
+
955
+ residual = hidden_states
956
+
957
+ hidden_states = self.input_layernorm(hidden_states)
958
+
959
+ # Self Attention
960
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
961
+ hidden_states=hidden_states,
962
+ attention_mask=attention_mask,
963
+ position_ids=position_ids,
964
+ past_key_value=past_key_value,
965
+ output_attentions=output_attentions,
966
+ use_cache=use_cache,
967
+ **kwargs,
968
+ )
969
+ hidden_states = residual + hidden_states
970
+
971
+ # Fully Connected
972
+ residual = hidden_states
973
+ hidden_states = self.post_attention_layernorm(hidden_states)
974
+ hidden_states = self.mlp(hidden_states)
975
+ hidden_states = residual + hidden_states
976
+
977
+ outputs = (hidden_states,)
978
+
979
+ if output_attentions:
980
+ outputs += (self_attn_weights,)
981
+
982
+ if use_cache:
983
+ outputs += (present_key_value,)
984
+
985
+ return outputs
986
+
987
+
988
+ LLAMA_START_DOCSTRING = r"""
989
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
990
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
991
+ etc.)
992
+
993
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
994
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
995
+ and behavior.
996
+
997
+ Parameters:
998
+ config ([`LlamaConfig`]):
999
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1000
+ load the weights associated with the model, only the configuration. Check out the
1001
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1002
+ """
1003
+
1004
+
1005
+ @add_start_docstrings(
1006
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1007
+ LLAMA_START_DOCSTRING,
1008
+ )
1009
+ class LlamaPreTrainedModel(PreTrainedModel):
1010
+ config_class = LlamaConfig
1011
+ base_model_prefix = "model"
1012
+ supports_gradient_checkpointing = True
1013
+ _no_split_modules = ["LlamaDecoderLayer"]
1014
+ _skip_keys_device_placement = "past_key_values"
1015
+ _supports_flash_attn_2 = True
1016
+ _supports_sdpa = True
1017
+ _supports_cache_class = True
1018
+
1019
+ def _init_weights(self, module):
1020
+ std = self.config.initializer_range
1021
+ if isinstance(module, nn.Linear):
1022
+ module.weight.data.normal_(mean=0.0, std=std)
1023
+ if module.bias is not None:
1024
+ module.bias.data.zero_()
1025
+ elif isinstance(module, nn.Embedding):
1026
+ module.weight.data.normal_(mean=0.0, std=std)
1027
+ if module.padding_idx is not None:
1028
+ module.weight.data[module.padding_idx].zero_()
1029
+
1030
+
1031
+ LLAMA_INPUTS_DOCSTRING = r"""
1032
+ Args:
1033
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1034
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1035
+ it.
1036
+
1037
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1038
+ [`PreTrainedTokenizer.__call__`] for details.
1039
+
1040
+ [What are input IDs?](../glossary#input-ids)
1041
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1042
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1043
+
1044
+ - 1 for tokens that are **not masked**,
1045
+ - 0 for tokens that are **masked**.
1046
+
1047
+ [What are attention masks?](../glossary#attention-mask)
1048
+
1049
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1050
+ [`PreTrainedTokenizer.__call__`] for details.
1051
+
1052
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1053
+ `past_key_values`).
1054
+
1055
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1056
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1057
+ information on the default strategy.
1058
+
1059
+ - 1 indicates the head is **not masked**,
1060
+ - 0 indicates the head is **masked**.
1061
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1062
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1063
+ config.n_positions - 1]`.
1064
+
1065
+ [What are position IDs?](../glossary#position-ids)
1066
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1067
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1068
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1069
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1070
+
1071
+ Two formats are allowed:
1072
+ - a [`~cache_utils.Cache`] instance;
1073
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1074
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1075
+ cache format.
1076
+
1077
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1078
+ legacy cache format will be returned.
1079
+
1080
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1081
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1082
+ of shape `(batch_size, sequence_length)`.
1083
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1084
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1085
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1086
+ model's internal embedding lookup matrix.
1087
+ use_cache (`bool`, *optional*):
1088
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1089
+ `past_key_values`).
1090
+ output_attentions (`bool`, *optional*):
1091
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1092
+ tensors for more detail.
1093
+ output_hidden_states (`bool`, *optional*):
1094
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1095
+ more detail.
1096
+ return_dict (`bool`, *optional*):
1097
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1098
+ """
1099
+
1100
+
1101
+ @add_start_docstrings(
1102
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1103
+ LLAMA_START_DOCSTRING,
1104
+ )
1105
+ class LlamaModel(LlamaPreTrainedModel):
1106
+ """
1107
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
1108
+
1109
+ Args:
1110
+ config: LlamaConfig
1111
+ """
1112
+
1113
+ def __init__(self, config: LlamaConfig):
1114
+ super().__init__(config)
1115
+ self.padding_idx = config.pad_token_id
1116
+ self.vocab_size = config.vocab_size
1117
+
1118
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1119
+ self.layers = nn.ModuleList(
1120
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1121
+ )
1122
+ self._use_sdpa = config._attn_implementation == "sdpa"
1123
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1124
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1125
+
1126
+ self.gradient_checkpointing = False
1127
+ # Initialize weights and apply final processing
1128
+ self.post_init()
1129
+
1130
+ def get_input_embeddings(self):
1131
+ return self.embed_tokens
1132
+
1133
+ def set_input_embeddings(self, value):
1134
+ self.embed_tokens = value
1135
+
1136
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1137
+ def forward(
1138
+ self,
1139
+ input_ids: torch.LongTensor = None,
1140
+ attention_mask: Optional[torch.Tensor] = None,
1141
+ position_ids: Optional[torch.LongTensor] = None,
1142
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1143
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1144
+ use_cache: Optional[bool] = None,
1145
+ output_attentions: Optional[bool] = None,
1146
+ output_hidden_states: Optional[bool] = None,
1147
+ return_dict: Optional[bool] = None,
1148
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1149
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1150
+ output_hidden_states = (
1151
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1152
+ )
1153
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1154
+
1155
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1156
+
1157
+ # retrieve input_ids and inputs_embeds
1158
+ if input_ids is not None and inputs_embeds is not None:
1159
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1160
+ elif input_ids is not None:
1161
+ batch_size, seq_length = input_ids.shape[:2]
1162
+ elif inputs_embeds is not None:
1163
+ batch_size, seq_length = inputs_embeds.shape[:2]
1164
+ else:
1165
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1166
+
1167
+ if self.gradient_checkpointing and self.training:
1168
+ if use_cache:
1169
+ logger.warning_once(
1170
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1171
+ )
1172
+ use_cache = False
1173
+
1174
+ past_key_values_length = 0
1175
+ if use_cache:
1176
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1177
+ if use_legacy_cache:
1178
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1179
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1180
+
1181
+ if position_ids is None:
1182
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1183
+ position_ids = torch.arange(
1184
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1185
+ )
1186
+ position_ids = position_ids.unsqueeze(0)
1187
+
1188
+ if inputs_embeds is None:
1189
+ inputs_embeds = self.embed_tokens(input_ids)
1190
+
1191
+ if self._use_flash_attention_2:
1192
+ # 2d mask is passed through the layers
1193
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1194
+ elif self._use_sdpa and not output_attentions:
1195
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1196
+ # the manual implementation that requires a 4D causal mask in all cases.
1197
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1198
+ attention_mask,
1199
+ (batch_size, seq_length),
1200
+ inputs_embeds,
1201
+ past_key_values_length,
1202
+ )
1203
+ else:
1204
+ # 4d mask is passed through the layers
1205
+ attention_mask = _prepare_4d_causal_attention_mask(
1206
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1207
+ )
1208
+
1209
+ # embed positions
1210
+ hidden_states = inputs_embeds
1211
+
1212
+ # decoder layers
1213
+ all_hidden_states = () if output_hidden_states else None
1214
+ all_self_attns = () if output_attentions else None
1215
+ next_decoder_cache = None
1216
+
1217
+ for decoder_layer in self.layers:
1218
+ if output_hidden_states:
1219
+ all_hidden_states += (hidden_states,)
1220
+
1221
+ if self.gradient_checkpointing and self.training:
1222
+ layer_outputs = self._gradient_checkpointing_func(
1223
+ decoder_layer.__call__,
1224
+ hidden_states,
1225
+ attention_mask,
1226
+ position_ids,
1227
+ past_key_values,
1228
+ output_attentions,
1229
+ use_cache,
1230
+ )
1231
+ else:
1232
+ layer_outputs = decoder_layer(
1233
+ hidden_states,
1234
+ attention_mask=attention_mask,
1235
+ position_ids=position_ids,
1236
+ past_key_value=past_key_values,
1237
+ output_attentions=output_attentions,
1238
+ use_cache=use_cache,
1239
+ )
1240
+
1241
+ hidden_states = layer_outputs[0]
1242
+
1243
+ if use_cache:
1244
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1245
+
1246
+ if output_attentions:
1247
+ all_self_attns += (layer_outputs[1],)
1248
+
1249
+ hidden_states = self.norm(hidden_states)
1250
+
1251
+ # add hidden states from the last decoder layer
1252
+ if output_hidden_states:
1253
+ all_hidden_states += (hidden_states,)
1254
+
1255
+ next_cache = None
1256
+ if use_cache:
1257
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1258
+ if not return_dict:
1259
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1260
+ return BaseModelOutputWithPast(
1261
+ last_hidden_state=hidden_states,
1262
+ past_key_values=next_cache,
1263
+ hidden_states=all_hidden_states,
1264
+ attentions=all_self_attns,
1265
+ )
1266
+
1267
+
1268
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1269
+ _tied_weights_keys = ["lm_head.weight"]
1270
+
1271
+ def __init__(self, config):
1272
+ super().__init__(config)
1273
+ self.model = LlamaModel(config)
1274
+ self.vocab_size = config.vocab_size
1275
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1276
+
1277
+ # Initialize weights and apply final processing
1278
+ self.post_init()
1279
+
1280
+ def get_input_embeddings(self):
1281
+ return self.model.embed_tokens
1282
+
1283
+ def set_input_embeddings(self, value):
1284
+ self.model.embed_tokens = value
1285
+
1286
+ def get_output_embeddings(self):
1287
+ return self.lm_head
1288
+
1289
+ def set_output_embeddings(self, new_embeddings):
1290
+ self.lm_head = new_embeddings
1291
+
1292
+ def set_decoder(self, decoder):
1293
+ self.model = decoder
1294
+
1295
+ def get_decoder(self):
1296
+ return self.model
1297
+
1298
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1299
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1300
+ def forward(
1301
+ self,
1302
+ input_ids: torch.LongTensor = None,
1303
+ attention_mask: Optional[torch.Tensor] = None,
1304
+ position_ids: Optional[torch.LongTensor] = None,
1305
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1306
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1307
+ labels: Optional[torch.LongTensor] = None,
1308
+ use_cache: Optional[bool] = None,
1309
+ output_attentions: Optional[bool] = None,
1310
+ output_hidden_states: Optional[bool] = None,
1311
+ return_dict: Optional[bool] = None,
1312
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1313
+ r"""
1314
+ Args:
1315
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1316
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1317
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1318
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1319
+
1320
+ Returns:
1321
+
1322
+ Example:
1323
+
1324
+ ```python
1325
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1326
+
1327
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1328
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1329
+
1330
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1331
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1332
+
1333
+ >>> # Generate
1334
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1335
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1336
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1337
+ ```"""
1338
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1339
+ output_hidden_states = (
1340
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1341
+ )
1342
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1343
+
1344
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1345
+ outputs = self.model(
1346
+ input_ids=input_ids,
1347
+ attention_mask=attention_mask,
1348
+ position_ids=position_ids,
1349
+ past_key_values=past_key_values,
1350
+ inputs_embeds=inputs_embeds,
1351
+ use_cache=use_cache,
1352
+ output_attentions=output_attentions,
1353
+ output_hidden_states=output_hidden_states,
1354
+ return_dict=return_dict,
1355
+ )
1356
+
1357
+ hidden_states = outputs[0]
1358
+ if self.config.pretraining_tp > 1:
1359
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1360
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1361
+ logits = torch.cat(logits, dim=-1)
1362
+ else:
1363
+ logits = self.lm_head(hidden_states)
1364
+ logits = logits.float()
1365
+
1366
+ loss = None
1367
+ if labels is not None:
1368
+ # Shift so that tokens < n predict n
1369
+ shift_logits = logits[..., :-1, :].contiguous()
1370
+ shift_labels = labels[..., 1:].contiguous()
1371
+ # Flatten the tokens
1372
+ loss_fct = CrossEntropyLoss()
1373
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1374
+ shift_labels = shift_labels.view(-1)
1375
+ # Enable model parallelism
1376
+ shift_labels = shift_labels.to(shift_logits.device)
1377
+ loss = loss_fct(shift_logits, shift_labels)
1378
+
1379
+ if not return_dict:
1380
+ output = (logits,) + outputs[1:]
1381
+ return (loss,) + output if loss is not None else output
1382
+
1383
+ return CausalLMOutputWithPast(
1384
+ loss=loss,
1385
+ logits=logits,
1386
+ past_key_values=outputs.past_key_values,
1387
+ hidden_states=outputs.hidden_states,
1388
+ attentions=outputs.attentions,
1389
+ )
1390
+
1391
+ def prepare_inputs_for_generation(
1392
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1393
+ ):
1394
+ if past_key_values is not None:
1395
+ if isinstance(past_key_values, Cache):
1396
+ cache_length = past_key_values.get_seq_length()
1397
+ past_length = past_key_values.seen_tokens
1398
+ max_cache_length = past_key_values.get_max_length()
1399
+ else:
1400
+ cache_length = past_length = past_key_values[0][0].shape[2]
1401
+ max_cache_length = None
1402
+
1403
+ # Keep only the unprocessed tokens:
1404
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1405
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1406
+ # input)
1407
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1408
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1409
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1410
+ # input_ids based on the past_length.
1411
+ elif past_length < input_ids.shape[1]:
1412
+ input_ids = input_ids[:, past_length:]
1413
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1414
+
1415
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1416
+ if (
1417
+ max_cache_length is not None
1418
+ and attention_mask is not None
1419
+ and cache_length + input_ids.shape[1] > max_cache_length
1420
+ ):
1421
+ attention_mask = attention_mask[:, -max_cache_length:]
1422
+
1423
+ position_ids = kwargs.get("position_ids", None)
1424
+ if attention_mask is not None and position_ids is None:
1425
+ # create position_ids on the fly for batch generation
1426
+ position_ids = attention_mask.long().cumsum(-1) - 1
1427
+ position_ids.masked_fill_(attention_mask == 0, 1)
1428
+ if past_key_values:
1429
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1430
+
1431
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1432
+ if inputs_embeds is not None and past_key_values is None:
1433
+ model_inputs = {"inputs_embeds": inputs_embeds}
1434
+ else:
1435
+ model_inputs = {"input_ids": input_ids}
1436
+
1437
+ model_inputs.update(
1438
+ {
1439
+ "position_ids": position_ids,
1440
+ "past_key_values": past_key_values,
1441
+ "use_cache": kwargs.get("use_cache"),
1442
+ "attention_mask": attention_mask,
1443
+ }
1444
+ )
1445
+ return model_inputs
1446
+
1447
+ @staticmethod
1448
+ def _reorder_cache(past_key_values, beam_idx):
1449
+ reordered_past = ()
1450
+ for layer_past in past_key_values:
1451
+ reordered_past += (
1452
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1453
+ )
1454
+ return reordered_past
1455
+
1456
+
1457
+ @add_start_docstrings(
1458
+ """
1459
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1460
+
1461
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1462
+ (e.g. GPT-2) do.
1463
+
1464
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1465
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1466
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1467
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1468
+ each row of the batch).
1469
+ """,
1470
+ LLAMA_START_DOCSTRING,
1471
+ )
1472
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1473
+ def __init__(self, config):
1474
+ super().__init__(config)
1475
+ self.num_labels = config.num_labels
1476
+ self.model = LlamaModel(config)
1477
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1478
+
1479
+ # Initialize weights and apply final processing
1480
+ self.post_init()
1481
+
1482
+ def get_input_embeddings(self):
1483
+ return self.model.embed_tokens
1484
+
1485
+ def set_input_embeddings(self, value):
1486
+ self.model.embed_tokens = value
1487
+
1488
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1489
+ def forward(
1490
+ self,
1491
+ input_ids: torch.LongTensor = None,
1492
+ attention_mask: Optional[torch.Tensor] = None,
1493
+ position_ids: Optional[torch.LongTensor] = None,
1494
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1495
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1496
+ labels: Optional[torch.LongTensor] = None,
1497
+ use_cache: Optional[bool] = None,
1498
+ output_attentions: Optional[bool] = None,
1499
+ output_hidden_states: Optional[bool] = None,
1500
+ return_dict: Optional[bool] = None,
1501
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1502
+ r"""
1503
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1504
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1505
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1506
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1507
+ """
1508
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1509
+
1510
+ transformer_outputs = self.model(
1511
+ input_ids,
1512
+ attention_mask=attention_mask,
1513
+ position_ids=position_ids,
1514
+ past_key_values=past_key_values,
1515
+ inputs_embeds=inputs_embeds,
1516
+ use_cache=use_cache,
1517
+ output_attentions=output_attentions,
1518
+ output_hidden_states=output_hidden_states,
1519
+ return_dict=return_dict,
1520
+ )
1521
+ hidden_states = transformer_outputs[0]
1522
+ logits = self.score(hidden_states)
1523
+
1524
+ if input_ids is not None:
1525
+ batch_size = input_ids.shape[0]
1526
+ else:
1527
+ batch_size = inputs_embeds.shape[0]
1528
+
1529
+ if self.config.pad_token_id is None and batch_size != 1:
1530
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1531
+ if self.config.pad_token_id is None:
1532
+ sequence_lengths = -1
1533
+ else:
1534
+ if input_ids is not None:
1535
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1536
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1537
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1538
+ sequence_lengths = sequence_lengths.to(logits.device)
1539
+ else:
1540
+ sequence_lengths = -1
1541
+
1542
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1543
+
1544
+ loss = None
1545
+ if labels is not None:
1546
+ labels = labels.to(logits.device)
1547
+ if self.config.problem_type is None:
1548
+ if self.num_labels == 1:
1549
+ self.config.problem_type = "regression"
1550
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1551
+ self.config.problem_type = "single_label_classification"
1552
+ else:
1553
+ self.config.problem_type = "multi_label_classification"
1554
+
1555
+ if self.config.problem_type == "regression":
1556
+ loss_fct = MSELoss()
1557
+ if self.num_labels == 1:
1558
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1559
+ else:
1560
+ loss = loss_fct(pooled_logits, labels)
1561
+ elif self.config.problem_type == "single_label_classification":
1562
+ loss_fct = CrossEntropyLoss()
1563
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1564
+ elif self.config.problem_type == "multi_label_classification":
1565
+ loss_fct = BCEWithLogitsLoss()
1566
+ loss = loss_fct(pooled_logits, labels)
1567
+ if not return_dict:
1568
+ output = (pooled_logits,) + transformer_outputs[1:]
1569
+ return ((loss,) + output) if loss is not None else output
1570
+
1571
+ return SequenceClassifierOutputWithPast(
1572
+ loss=loss,
1573
+ logits=pooled_logits,
1574
+ past_key_values=transformer_outputs.past_key_values,
1575
+ hidden_states=transformer_outputs.hidden_states,
1576
+ attentions=transformer_outputs.attentions,
1577
+ )