Martins Kronis commited on
Commit
a66e9c6
·
1 Parent(s): 0a98506

add YaRN patch for transformers 4x

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