bjoernp commited on
Commit
12fbf06
1 Parent(s): 96c591b

Update configuration_bitllama.py

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