parsakaveh commited on
Commit
5afdf73
·
verified ·
1 Parent(s): 0641624

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_nestedllama.py +243 -0
  2. modeling_nestedllama.py +1029 -0
configuration_nestedllama.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """NestedLlama model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class NestedLlamaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`NestedLlamaModel`]. It is used to instantiate an NestedLlama
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 NestedLlama-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 NestedLlama model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`NestedLlamaModel`]
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. NestedLlama 1 supports up to 2048 tokens,
60
+ NestedLlama 2 up to 4096, CodeNestedLlama 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
+ 'NestedLlama3'], 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 'NestedLlama3'. 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 'NestedLlama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'NestedLlama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
+ attention_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+ head_dim (`int`, *optional*):
127
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
128
+
129
+ ```python
130
+ >>> from transformers import NestedLlamaModel, NestedLlamaConfig
131
+
132
+ >>> # Initializing a NestedLlama NestedLlama-7b style configuration
133
+ >>> configuration = NestedLlamaConfig()
134
+
135
+ >>> # Initializing a model from the NestedLlama-7b style configuration
136
+ >>> model = NestedLlamaModel(configuration)
137
+
138
+ >>> # Accessing the model configuration
139
+ >>> configuration = model.config
140
+ ```"""
141
+
142
+ model_type = "nested_llama"
143
+ keys_to_ignore_at_inference = ["past_key_values"]
144
+ # Default tensor parallel plan for base model `NestedLlamaModel`
145
+ base_model_tp_plan = {
146
+ "layers.*.self_attn.q_proj": "colwise",
147
+ "layers.*.self_attn.k_proj": "colwise",
148
+ "layers.*.self_attn.v_proj": "colwise",
149
+ "layers.*.self_attn.o_proj": "rowwise",
150
+ "layers.*.mlp.gate_proj": "colwise",
151
+ "layers.*.mlp.up_proj": "colwise",
152
+ "layers.*.mlp.down_proj": "rowwise",
153
+ }
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_size=32000,
158
+ hidden_size=4096,
159
+ intermediate_size=11008,
160
+ num_hidden_layers=32,
161
+ num_attention_heads=32,
162
+ num_key_value_heads=None,
163
+ hidden_act="silu",
164
+ max_position_embeddings=2048,
165
+ initializer_range=0.02,
166
+ rms_norm_eps=1e-6,
167
+ use_cache=True,
168
+ pad_token_id=None,
169
+ bos_token_id=1,
170
+ eos_token_id=2,
171
+ pretraining_tp=1,
172
+ tie_word_embeddings=False,
173
+ rope_theta=10000.0,
174
+ rope_scaling=None,
175
+ attention_bias=False,
176
+ attention_dropout=0.0,
177
+ mlp_bias=False,
178
+ head_dim=None,
179
+ tie_exit_lm_head=None,
180
+ output_exit_layers=None,
181
+ output_full_model=True,
182
+ exit_layer_indices=None,
183
+ exit_decoder_layer=False,
184
+ exit_mlp=False,
185
+ exit_attention=False,
186
+ **kwargs,
187
+ ):
188
+ self.vocab_size = vocab_size
189
+ self.max_position_embeddings = max_position_embeddings
190
+ self.hidden_size = hidden_size
191
+ self.intermediate_size = intermediate_size
192
+ self.num_hidden_layers = num_hidden_layers
193
+ self.num_attention_heads = num_attention_heads
194
+
195
+ # for backward compatibility
196
+ if num_key_value_heads is None:
197
+ num_key_value_heads = num_attention_heads
198
+
199
+ self.num_key_value_heads = num_key_value_heads
200
+ self.hidden_act = hidden_act
201
+ self.initializer_range = initializer_range
202
+ self.rms_norm_eps = rms_norm_eps
203
+ self.pretraining_tp = pretraining_tp
204
+ self.use_cache = use_cache
205
+ self.rope_theta = rope_theta
206
+ self.rope_scaling = rope_scaling
207
+ self.attention_bias = attention_bias
208
+ self.attention_dropout = attention_dropout
209
+ self.mlp_bias = mlp_bias
210
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
211
+ # Validate the correctness of rotary position embeddings parameters
212
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
213
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
214
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
215
+ rope_config_validation(self)
216
+
217
+ self.tie_exit_lm_head = tie_exit_lm_head
218
+ self.exit_layer_indices = exit_layer_indices
219
+ self.exit_decoder_layer = exit_decoder_layer
220
+ self.output_full_model = output_full_model
221
+ self.output_exit_layers = output_exit_layers
222
+ self.exit_mlp = exit_mlp
223
+ self.exit_attention = exit_attention
224
+
225
+ super().__init__(
226
+ pad_token_id=pad_token_id,
227
+ bos_token_id=bos_token_id,
228
+ eos_token_id=eos_token_id,
229
+ tie_word_embeddings=tie_word_embeddings,
230
+ **kwargs,
231
+ )
232
+
233
+ self.tie_exit_lm_head = self.tie_exit_lm_head if self.tie_exit_lm_head is not None else self.tie_word_embeddings
234
+ if isinstance(self.output_exit_layers, int):
235
+ self.output_exit_layers = [self.output_exit_layers]
236
+ if self.output_exit_layers is not None:
237
+ for self.output_exit_layer in self.output_exit_layers:
238
+ assert self.output_exit_layer in self.exit_layer_indices, (
239
+ f"output_exit_layers {output_exit_layers} should be in the exit_layer_indices: {exit_layer_indices}"
240
+ )
241
+
242
+
243
+ __all__ = ["NestedLlamaConfig"]
modeling_nestedllama.py ADDED
@@ -0,0 +1,1029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Callable, List, Optional, Tuple, Union
21
+ from dataclasses import dataclass
22
+ from transformers.utils import ModelOutput
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from transformers.processing_utils import Unpack
43
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
44
+ from transformers.utils import (
45
+ LossKwargs,
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_nestedllama import NestedLlamaConfig
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CHECKPOINT_FOR_DOC = "meta-NestedLlama/NestedLlama-2-7b-hf"
58
+ _CONFIG_FOR_DOC = "NestedLlamaConfig"
59
+
60
+
61
+ class NestedLlamaRMSNorm(nn.Module):
62
+ def __init__(self, hidden_size, eps=1e-6):
63
+ """
64
+ NestedLlamaRMSNorm is equivalent to T5LayerNorm
65
+ """
66
+ super().__init__()
67
+ self.weight = nn.Parameter(torch.ones(hidden_size))
68
+ self.variance_epsilon = eps
69
+
70
+ def forward(self, hidden_states):
71
+ input_dtype = hidden_states.dtype
72
+ hidden_states = hidden_states.to(torch.float32)
73
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
74
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
75
+ return self.weight * hidden_states.to(input_dtype)
76
+
77
+ def extra_repr(self):
78
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
79
+
80
+
81
+ ALL_LAYERNORM_LAYERS.append(NestedLlamaRMSNorm)
82
+
83
+
84
+ class NestedLlamaRotaryEmbedding(nn.Module):
85
+ def __init__(
86
+ self,
87
+ config: NestedLlamaConfig,
88
+ device=None,
89
+ ):
90
+ super().__init__()
91
+ self.rope_kwargs = {}
92
+ # BC: "rope_type" was originally "type"
93
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
94
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
95
+ else:
96
+ self.rope_type = "default"
97
+ self.max_seq_len_cached = config.max_position_embeddings
98
+ self.original_max_seq_len = config.max_position_embeddings
99
+
100
+ self.config = config
101
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
102
+
103
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
104
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
105
+ self.original_inv_freq = self.inv_freq
106
+
107
+ def _dynamic_frequency_update(self, position_ids, device):
108
+ """
109
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
110
+ 1 - growing beyond the cached sequence length (allow scaling)
111
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
112
+ """
113
+ seq_len = torch.max(position_ids) + 1
114
+ if seq_len > self.max_seq_len_cached: # growth
115
+ inv_freq, self.attention_scaling = self.rope_init_fn(
116
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
117
+ )
118
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
119
+ self.max_seq_len_cached = seq_len
120
+
121
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
122
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
123
+ self.max_seq_len_cached = self.original_max_seq_len
124
+
125
+ @torch.no_grad()
126
+ def forward(self, x, position_ids):
127
+ if "dynamic" in self.rope_type:
128
+ self._dynamic_frequency_update(position_ids, device=x.device)
129
+
130
+ # Core RoPE block
131
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
132
+ position_ids_expanded = position_ids[:, None, :].float()
133
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
134
+ device_type = x.device.type
135
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
136
+ with torch.autocast(device_type=device_type, enabled=False):
137
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
138
+ emb = torch.cat((freqs, freqs), dim=-1)
139
+ cos = emb.cos()
140
+ sin = emb.sin()
141
+
142
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
143
+ cos = cos * self.attention_scaling
144
+ sin = sin * self.attention_scaling
145
+
146
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
147
+
148
+
149
+ def rotate_half(x):
150
+ """Rotates half the hidden dims of the input."""
151
+ x1 = x[..., : x.shape[-1] // 2]
152
+ x2 = x[..., x.shape[-1] // 2 :]
153
+ return torch.cat((-x2, x1), dim=-1)
154
+
155
+
156
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
157
+ """Applies Rotary Position Embedding to the query and key tensors.
158
+
159
+ Args:
160
+ q (`torch.Tensor`): The query tensor.
161
+ k (`torch.Tensor`): The key tensor.
162
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
163
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
164
+ position_ids (`torch.Tensor`, *optional*):
165
+ Deprecated and unused.
166
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
167
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
168
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
169
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
170
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
171
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
172
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
173
+ Returns:
174
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
175
+ """
176
+ cos = cos.unsqueeze(unsqueeze_dim)
177
+ sin = sin.unsqueeze(unsqueeze_dim)
178
+ q_embed = (q * cos) + (rotate_half(q) * sin)
179
+ k_embed = (k * cos) + (rotate_half(k) * sin)
180
+ return q_embed, k_embed
181
+
182
+
183
+ class NestedLlamaMLP(nn.Module):
184
+ def __init__(self, config):
185
+ super().__init__()
186
+ self.config = config
187
+ self.hidden_size = config.hidden_size
188
+ self.intermediate_size = config.intermediate_size
189
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
190
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
191
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
192
+ self.act_fn = ACT2FN[config.hidden_act]
193
+
194
+ def forward(self, x):
195
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
196
+ return down_proj
197
+
198
+
199
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
200
+ """
201
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
202
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
203
+ """
204
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
205
+ if n_rep == 1:
206
+ return hidden_states
207
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
208
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
209
+
210
+
211
+ def eager_attention_forward(
212
+ module: nn.Module,
213
+ query: torch.Tensor,
214
+ key: torch.Tensor,
215
+ value: torch.Tensor,
216
+ attention_mask: Optional[torch.Tensor],
217
+ scaling: float,
218
+ dropout: float = 0.0,
219
+ **kwargs,
220
+ ):
221
+ key_states = repeat_kv(key, module.num_key_value_groups)
222
+ value_states = repeat_kv(value, module.num_key_value_groups)
223
+
224
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
225
+ if attention_mask is not None:
226
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
227
+ attn_weights = attn_weights + causal_mask
228
+
229
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
230
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
231
+ attn_output = torch.matmul(attn_weights, value_states)
232
+ attn_output = attn_output.transpose(1, 2).contiguous()
233
+
234
+ return attn_output, attn_weights
235
+
236
+
237
+ class NestedLlamaAttention(nn.Module):
238
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
239
+
240
+ def __init__(self, config: NestedLlamaConfig, layer_idx: int):
241
+ super().__init__()
242
+ self.config = config
243
+ self.layer_idx = layer_idx
244
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
245
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
246
+ self.scaling = self.head_dim**-0.5
247
+ self.attention_dropout = config.attention_dropout
248
+ self.is_causal = True
249
+
250
+ self.q_proj = nn.Linear(
251
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
252
+ )
253
+ self.k_proj = nn.Linear(
254
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
255
+ )
256
+ self.v_proj = nn.Linear(
257
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
258
+ )
259
+ self.o_proj = nn.Linear(
260
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
261
+ )
262
+
263
+ def forward(
264
+ self,
265
+ hidden_states: torch.Tensor,
266
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
267
+ attention_mask: Optional[torch.Tensor],
268
+ past_key_value: Optional[Cache] = None,
269
+ cache_position: Optional[torch.LongTensor] = None,
270
+ **kwargs: Unpack[FlashAttentionKwargs],
271
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
272
+ input_shape = hidden_states.shape[:-1]
273
+ hidden_shape = (*input_shape, -1, self.head_dim)
274
+
275
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
276
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
277
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
278
+
279
+ cos, sin = position_embeddings
280
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
281
+
282
+ if past_key_value is not None:
283
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
284
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
285
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
286
+
287
+ attention_interface: Callable = eager_attention_forward
288
+ if self.config._attn_implementation != "eager":
289
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
290
+ logger.warning_once(
291
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
292
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
293
+ )
294
+ else:
295
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
296
+
297
+ attn_output, attn_weights = attention_interface(
298
+ self,
299
+ query_states,
300
+ key_states,
301
+ value_states,
302
+ attention_mask,
303
+ dropout=0.0 if not self.training else self.attention_dropout,
304
+ scaling=self.scaling,
305
+ **kwargs,
306
+ )
307
+
308
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
309
+ attn_output = self.o_proj(attn_output)
310
+ return attn_output, attn_weights
311
+
312
+
313
+ class NestedLlamaDecoderLayer(nn.Module):
314
+ def __init__(self, config: NestedLlamaConfig, layer_idx: int, has_attention: bool = True, has_mlp: bool = True):
315
+ super().__init__()
316
+ self.has_attention = has_attention
317
+ self.has_mlp = has_mlp
318
+ self.hidden_size = config.hidden_size
319
+
320
+ self.self_attn = NestedLlamaAttention(config=config, layer_idx=layer_idx) if has_attention else None
321
+
322
+ self.mlp = NestedLlamaMLP(config) if has_mlp else None
323
+ self.input_layernorm = NestedLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
324
+ self.post_attention_layernorm = NestedLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) if has_attention else None
325
+
326
+ def forward(
327
+ self,
328
+ hidden_states: torch.Tensor,
329
+ attention_mask: Optional[torch.Tensor] = None,
330
+ position_ids: Optional[torch.LongTensor] = None,
331
+ past_key_value: Optional[Cache] = None,
332
+ output_attentions: Optional[bool] = False,
333
+ use_cache: Optional[bool] = False,
334
+ cache_position: Optional[torch.LongTensor] = None,
335
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
336
+ **kwargs: Unpack[FlashAttentionKwargs],
337
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
338
+ residual = hidden_states
339
+
340
+ hidden_states = self.input_layernorm(hidden_states)
341
+
342
+ # Self Attention
343
+ if self.has_attention:
344
+ hidden_states, self_attn_weights = self.self_attn(
345
+ hidden_states=hidden_states,
346
+ attention_mask=attention_mask,
347
+ position_ids=position_ids,
348
+ past_key_value=past_key_value,
349
+ output_attentions=output_attentions,
350
+ use_cache=use_cache,
351
+ cache_position=cache_position,
352
+ position_embeddings=position_embeddings,
353
+ **kwargs,
354
+ )
355
+ hidden_states = residual + hidden_states
356
+
357
+ # Fully Connected
358
+ residual = hidden_states
359
+ if self.has_attention:
360
+ hidden_states = self.post_attention_layernorm(hidden_states)
361
+ if self.has_mlp:
362
+ hidden_states = self.mlp(hidden_states)
363
+ hidden_states = residual + hidden_states
364
+
365
+ outputs = (hidden_states,)
366
+ if output_attentions:
367
+ outputs += (self_attn_weights,)
368
+
369
+ return outputs
370
+
371
+
372
+ NestedLlama_START_DOCSTRING = r"""
373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
375
+ etc.)
376
+
377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
379
+ and behavior.
380
+
381
+ Parameters:
382
+ config ([`NestedLlamaConfig`]):
383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
384
+ load the weights associated with the model, only the configuration. Check out the
385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
386
+ """
387
+
388
+
389
+ @add_start_docstrings(
390
+ "The bare NestedLlama Model outputting raw hidden-states without any specific head on top.",
391
+ NestedLlama_START_DOCSTRING,
392
+ )
393
+ class NestedLlamaPreTrainedModel(PreTrainedModel):
394
+ config_class = NestedLlamaConfig
395
+ base_model_prefix = "model"
396
+ supports_gradient_checkpointing = True
397
+ _no_split_modules = ["NestedLlamaDecoderLayer"]
398
+ _skip_keys_device_placement = ["past_key_values"]
399
+ _supports_flash_attn_2 = True
400
+ _supports_sdpa = True
401
+ _supports_cache_class = True
402
+ _supports_quantized_cache = True
403
+ _supports_static_cache = True
404
+
405
+ def _init_weights(self, module):
406
+ std = self.config.initializer_range
407
+ if isinstance(module, nn.Linear):
408
+ module.weight.data.normal_(mean=0.0, std=std)
409
+ if module.bias is not None:
410
+ module.bias.data.zero_()
411
+ elif isinstance(module, nn.Embedding):
412
+ module.weight.data.normal_(mean=0.0, std=std)
413
+ if module.padding_idx is not None:
414
+ module.weight.data[module.padding_idx].zero_()
415
+
416
+
417
+ NestedLlama_INPUTS_DOCSTRING = r"""
418
+ Args:
419
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
420
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
421
+ it.
422
+
423
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
424
+ [`PreTrainedTokenizer.__call__`] for details.
425
+
426
+ [What are input IDs?](../glossary#input-ids)
427
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
428
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
429
+
430
+ - 1 for tokens that are **not masked**,
431
+ - 0 for tokens that are **masked**.
432
+
433
+ [What are attention masks?](../glossary#attention-mask)
434
+
435
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
436
+ [`PreTrainedTokenizer.__call__`] for details.
437
+
438
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
439
+ `past_key_values`).
440
+
441
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
442
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
443
+ information on the default strategy.
444
+
445
+ - 1 indicates the head is **not masked**,
446
+ - 0 indicates the head is **masked**.
447
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
448
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
449
+ config.n_positions - 1]`.
450
+
451
+ [What are position IDs?](../glossary#position-ids)
452
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
453
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
454
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
455
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
456
+
457
+ Two formats are allowed:
458
+ - a [`~cache_utils.Cache`] instance, see our
459
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
460
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
461
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
462
+ cache format.
463
+
464
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
465
+ legacy cache format will be returned.
466
+
467
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
468
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
469
+ of shape `(batch_size, sequence_length)`.
470
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
471
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
472
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
473
+ model's internal embedding lookup matrix.
474
+ use_cache (`bool`, *optional*):
475
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
476
+ `past_key_values`).
477
+ output_attentions (`bool`, *optional*):
478
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
479
+ tensors for more detail.
480
+ output_hidden_states (`bool`, *optional*):
481
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
482
+ more detail.
483
+ return_dict (`bool`, *optional*):
484
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
485
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
486
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
487
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
488
+ the complete sequence length.
489
+ """
490
+
491
+
492
+ @dataclass
493
+ class BaseModelOutputWithPast(ModelOutput):
494
+ """
495
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
496
+
497
+ Args:
498
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
499
+ Sequence of hidden-states at the output of the last layer of the model.
500
+
501
+ If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
502
+ hidden_size)` is output.
503
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
504
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
505
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
506
+ `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
507
+ encoder_sequence_length, embed_size_per_head)`.
508
+
509
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
510
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
511
+ input) to speed up sequential decoding.
512
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
513
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
514
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
515
+
516
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
517
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
518
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
519
+ sequence_length)`.
520
+
521
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
522
+ heads.
523
+ """
524
+
525
+ last_hidden_states: Tuple[torch.FloatTensor] = None
526
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
527
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
528
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
529
+
530
+
531
+ @dataclass
532
+ class CausalLMOutputWithPast(ModelOutput):
533
+ """
534
+ Base class for causal language model (or autoregressive) outputs.
535
+
536
+ Args:
537
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
538
+ Language modeling loss (for next-token prediction).
539
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
540
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
541
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
542
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
543
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
544
+
545
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
546
+ `past_key_values` input) to speed up sequential decoding.
547
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
548
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
549
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
550
+
551
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
552
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
553
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
554
+ sequence_length)`.
555
+
556
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
557
+ heads.
558
+ """
559
+
560
+ losses: Optional[torch.FloatTensor] = None
561
+ logits: Tuple[torch.FloatTensor] = None
562
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
563
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
564
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
565
+
566
+
567
+ @add_start_docstrings(
568
+ "The bare NestedLlama Model outputting raw hidden-states without any specific head on top.",
569
+ NestedLlama_START_DOCSTRING,
570
+ )
571
+ class NestedLlamaModel(NestedLlamaPreTrainedModel):
572
+ """
573
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NestedLlamaDecoderLayer`]
574
+
575
+ Args:
576
+ config: NestedLlamaConfig
577
+ """
578
+
579
+ def __init__(self, config: NestedLlamaConfig):
580
+ super().__init__(config)
581
+ self.padding_idx = config.pad_token_id
582
+ self.vocab_size = config.vocab_size
583
+ self.num_forward_layers = config.num_hidden_layers
584
+
585
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
586
+ self.layers = nn.ModuleList(
587
+ [NestedLlamaDecoderLayer(config, layer_idx, True, True) for layer_idx in range(config.num_hidden_layers)]
588
+ )
589
+
590
+ # NESTED
591
+ self.exit_modules = nn.ModuleList([
592
+ nn.ModuleList(
593
+ [module for module in [
594
+ NestedLlamaDecoderLayer(config, config.num_hidden_layers+i, not config.exit_mlp, not config.exit_attention) if config.exit_decoder_layer else None,
595
+ NestedLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps),
596
+ nn.Linear(config.hidden_size, config.vocab_size, bias=False) if not config.tie_exit_lm_head else None,
597
+ ] if module is not None # Filter out None modules
598
+ ]) for i in range(len(config.exit_layer_indices))
599
+ ])
600
+
601
+ if not config.output_full_model and config.output_exit_layers is not None:
602
+ self.num_forward_layers = max(config.output_exit_layers)
603
+
604
+ self.norm = NestedLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
605
+ self.rotary_emb = NestedLlamaRotaryEmbedding(config=config)
606
+ self.gradient_checkpointing = False
607
+
608
+ # Initialize weights and apply final processing
609
+ self.post_init()
610
+
611
+ def get_input_embeddings(self):
612
+ return self.embed_tokens
613
+
614
+ def set_input_embeddings(self, value):
615
+ self.embed_tokens = value
616
+
617
+ @add_start_docstrings_to_model_forward(NestedLlama_INPUTS_DOCSTRING)
618
+ def forward(
619
+ self,
620
+ input_ids: torch.LongTensor = None,
621
+ attention_mask: Optional[torch.Tensor] = None,
622
+ position_ids: Optional[torch.LongTensor] = None,
623
+ past_key_values: Optional[Cache] = None,
624
+ inputs_embeds: Optional[torch.FloatTensor] = None,
625
+ use_cache: Optional[bool] = None,
626
+ output_attentions: Optional[bool] = None,
627
+ output_hidden_states: Optional[bool] = None,
628
+ return_dict: Optional[bool] = None,
629
+ cache_position: Optional[torch.LongTensor] = None,
630
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
631
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
632
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
633
+ output_hidden_states = (
634
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
635
+ )
636
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
637
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
638
+
639
+ if (input_ids is None) ^ (inputs_embeds is not None):
640
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
641
+
642
+ if self.gradient_checkpointing and self.training and use_cache:
643
+ logger.warning_once(
644
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
645
+ )
646
+ use_cache = False
647
+
648
+ if inputs_embeds is None:
649
+ inputs_embeds = self.embed_tokens(input_ids)
650
+
651
+ if use_cache and past_key_values is None:
652
+ past_key_values = DynamicCache()
653
+
654
+ if cache_position is None:
655
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
656
+ cache_position = torch.arange(
657
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
658
+ )
659
+
660
+ if position_ids is None:
661
+ position_ids = cache_position.unsqueeze(0)
662
+
663
+ causal_mask = self._update_causal_mask(
664
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
665
+ )
666
+
667
+ hidden_states = inputs_embeds
668
+
669
+ # create position embeddings to be shared across the decoder layers
670
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
671
+
672
+ # decoder layers
673
+ all_hidden_states = ()
674
+ all_self_attns = () if output_attentions else None
675
+
676
+ for decoder_layer in self.layers[: self.num_forward_layers]:
677
+ all_hidden_states += (hidden_states,)
678
+
679
+ if self.gradient_checkpointing and self.training:
680
+ layer_outputs = self._gradient_checkpointing_func(
681
+ decoder_layer.__call__,
682
+ hidden_states,
683
+ causal_mask,
684
+ position_ids,
685
+ past_key_values,
686
+ output_attentions,
687
+ use_cache,
688
+ cache_position,
689
+ position_embeddings,
690
+ )
691
+ else:
692
+ layer_outputs = decoder_layer(
693
+ hidden_states,
694
+ attention_mask=causal_mask,
695
+ position_ids=position_ids,
696
+ past_key_value=past_key_values,
697
+ output_attentions=output_attentions,
698
+ use_cache=use_cache,
699
+ cache_position=cache_position,
700
+ position_embeddings=position_embeddings,
701
+ **flash_attn_kwargs,
702
+ )
703
+
704
+ hidden_states = layer_outputs[0]
705
+
706
+ if output_attentions:
707
+ all_self_attns += (layer_outputs[1],)
708
+
709
+ if not self.config.output_full_model:
710
+ all_hidden_states += (hidden_states,)
711
+
712
+ last_hidden_states = tuple()
713
+ # NESTED
714
+ if self.config.output_exit_layers is not None:
715
+ for output_exit_layer in self.config.output_exit_layers:
716
+ exit_index = self.config.exit_layer_indices.index(output_exit_layer)
717
+ if self.config.exit_decoder_layer:
718
+ exit_module_hidden_states = self.exit_modules[exit_index][0](
719
+ all_hidden_states[output_exit_layer],
720
+ attention_mask=causal_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_values,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ cache_position=cache_position,
726
+ position_embeddings=position_embeddings,
727
+ **flash_attn_kwargs,
728
+ )[0]
729
+ exit_module_hidden_states = self.exit_modules[exit_index][1](exit_module_hidden_states)
730
+ else:
731
+ exit_module_hidden_states = self.exit_modules[exit_index][0](all_hidden_states[output_exit_layer])
732
+
733
+ last_hidden_states += (exit_module_hidden_states,)
734
+
735
+ if self.config.output_full_model:
736
+ hidden_states = self.norm(hidden_states)
737
+ all_hidden_states += (hidden_states,)
738
+
739
+ if self.config.output_full_model:
740
+ last_hidden_states += (hidden_states,)
741
+
742
+ # # add hidden states from the last decoder layer
743
+ if output_hidden_states:
744
+ all_hidden_states += (hidden_states,)
745
+
746
+ else:
747
+ del all_hidden_states
748
+
749
+ output = BaseModelOutputWithPast(
750
+ last_hidden_states=last_hidden_states,
751
+ past_key_values=past_key_values if use_cache else None,
752
+ hidden_states=all_hidden_states if output_hidden_states else None,
753
+ attentions=all_self_attns,
754
+ )
755
+ return output if return_dict else output.to_tuple()
756
+
757
+ def _update_causal_mask(
758
+ self,
759
+ attention_mask: torch.Tensor,
760
+ input_tensor: torch.Tensor,
761
+ cache_position: torch.Tensor,
762
+ past_key_values: Cache,
763
+ output_attentions: bool,
764
+ ):
765
+ if self.config._attn_implementation == "flash_attention_2":
766
+ if attention_mask is not None and (attention_mask == 0.0).any():
767
+ return attention_mask
768
+ return None
769
+
770
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
771
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
772
+ # to infer the attention mask.
773
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
774
+ using_static_cache = isinstance(past_key_values, StaticCache)
775
+
776
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
777
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
778
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
779
+ attention_mask,
780
+ inputs_embeds=input_tensor,
781
+ past_key_values_length=past_seen_tokens,
782
+ is_training=self.training,
783
+ ):
784
+ return None
785
+
786
+ dtype, device = input_tensor.dtype, input_tensor.device
787
+ sequence_length = input_tensor.shape[1]
788
+ if using_static_cache:
789
+ target_length = past_key_values.get_max_cache_shape()
790
+ else:
791
+ target_length = (
792
+ attention_mask.shape[-1]
793
+ if isinstance(attention_mask, torch.Tensor)
794
+ else past_seen_tokens + sequence_length + 1
795
+ )
796
+
797
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
798
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
799
+ attention_mask,
800
+ sequence_length=sequence_length,
801
+ target_length=target_length,
802
+ dtype=dtype,
803
+ device=device,
804
+ cache_position=cache_position,
805
+ batch_size=input_tensor.shape[0],
806
+ )
807
+
808
+ if (
809
+ self.config._attn_implementation == "sdpa"
810
+ and attention_mask is not None
811
+ and attention_mask.device.type == "cuda"
812
+ and not output_attentions
813
+ ):
814
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
815
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
816
+ # Details: https://github.com/pytorch/pytorch/issues/110213
817
+ min_dtype = torch.finfo(dtype).min
818
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
819
+
820
+ return causal_mask
821
+
822
+ @staticmethod
823
+ def _prepare_4d_causal_attention_mask_with_cache_position(
824
+ attention_mask: torch.Tensor,
825
+ sequence_length: int,
826
+ target_length: int,
827
+ dtype: torch.dtype,
828
+ device: torch.device,
829
+ cache_position: torch.Tensor,
830
+ batch_size: int,
831
+ **kwargs,
832
+ ):
833
+ """
834
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
835
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
836
+
837
+ Args:
838
+ attention_mask (`torch.Tensor`):
839
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
840
+ `(batch_size, 1, query_length, key_value_length)`.
841
+ sequence_length (`int`):
842
+ The sequence length being processed.
843
+ target_length (`int`):
844
+ The target length: when generating with static cache, the mask should be as long as the static cache,
845
+ to account for the 0 padding, the part of the cache that is not filled yet.
846
+ dtype (`torch.dtype`):
847
+ The dtype to use for the 4D attention mask.
848
+ device (`torch.device`):
849
+ The device to plcae the 4D attention mask on.
850
+ cache_position (`torch.Tensor`):
851
+ Indices depicting the position of the input sequence tokens in the sequence.
852
+ batch_size (`torch.Tensor`):
853
+ Batch size.
854
+ """
855
+ if attention_mask is not None and attention_mask.dim() == 4:
856
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
857
+ causal_mask = attention_mask
858
+ else:
859
+ min_dtype = torch.finfo(dtype).min
860
+ causal_mask = torch.full(
861
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
862
+ )
863
+ if sequence_length != 1:
864
+ causal_mask = torch.triu(causal_mask, diagonal=1)
865
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
866
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
867
+ if attention_mask is not None:
868
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
869
+ mask_length = attention_mask.shape[-1]
870
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
871
+ padding_mask = padding_mask == 0
872
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
873
+ padding_mask, min_dtype
874
+ )
875
+
876
+ return causal_mask
877
+
878
+
879
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
880
+
881
+
882
+ class NestedLlamaForCausalLM(NestedLlamaPreTrainedModel, GenerationMixin):
883
+ _tied_weights_keys = ["lm_head.weight"]
884
+ _tp_plan = {"lm_head": "colwise_rep"}
885
+
886
+ def __init__(self, config: NestedLlamaConfig):
887
+ super().__init__(config)
888
+
889
+ self.model = NestedLlamaModel(config)
890
+ self.vocab_size = config.vocab_size
891
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
892
+
893
+ # Initialize weights and apply final processing
894
+ self.post_init()
895
+
896
+ def get_input_embeddings(self):
897
+ return self.model.embed_tokens
898
+
899
+ def set_input_embeddings(self, value):
900
+ self.model.embed_tokens = value
901
+
902
+ def get_output_embeddings(self):
903
+ return self.lm_head
904
+
905
+ def set_output_embeddings(self, new_embeddings):
906
+ self.lm_head = new_embeddings
907
+
908
+ def set_decoder(self, decoder):
909
+ self.model = decoder
910
+
911
+ def get_decoder(self):
912
+ return self.model
913
+
914
+ @add_start_docstrings_to_model_forward(NestedLlama_INPUTS_DOCSTRING)
915
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
916
+ def forward(
917
+ self,
918
+ input_ids: torch.LongTensor = None,
919
+ attention_mask: Optional[torch.Tensor] = None,
920
+ position_ids: Optional[torch.LongTensor] = None,
921
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
922
+ inputs_embeds: Optional[torch.FloatTensor] = None,
923
+ labels: Optional[torch.LongTensor] = None,
924
+ use_cache: Optional[bool] = None,
925
+ output_attentions: Optional[bool] = None,
926
+ output_hidden_states: Optional[bool] = None,
927
+ return_dict: Optional[bool] = None,
928
+ cache_position: Optional[torch.LongTensor] = None,
929
+ num_logits_to_keep: int = 0,
930
+ **kwargs: Unpack[KwargsForCausalLM],
931
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
932
+ r"""
933
+ Args:
934
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
935
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
936
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
937
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
938
+
939
+ num_logits_to_keep (`int`, *optional*):
940
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
941
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
942
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
943
+
944
+ Returns:
945
+
946
+ Example:
947
+
948
+ ```python
949
+ >>> from transformers import AutoTokenizer, NestedLlamaForCausalLM
950
+
951
+ >>> model = NestedLlamaForCausalLM.from_pretrained("meta-NestedLlama/NestedLlama-2-7b-hf")
952
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-NestedLlama/NestedLlama-2-7b-hf")
953
+
954
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
955
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
956
+
957
+ >>> # Generate
958
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
959
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
960
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
961
+ ```"""
962
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
963
+ output_hidden_states = (
964
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
965
+ )
966
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
967
+
968
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
969
+ outputs = self.model(
970
+ input_ids=input_ids,
971
+ attention_mask=attention_mask,
972
+ position_ids=position_ids,
973
+ past_key_values=past_key_values,
974
+ inputs_embeds=inputs_embeds,
975
+ use_cache=use_cache,
976
+ output_attentions=output_attentions,
977
+ output_hidden_states=output_hidden_states,
978
+ return_dict=return_dict,
979
+ cache_position=cache_position,
980
+ **kwargs,
981
+ )
982
+
983
+ last_hidden_states = outputs[0]
984
+
985
+ assert self.config.output_exit_layers is not None or self.config.output_full_model
986
+
987
+ if self.config.output_full_model and self.config.output_exit_layers is not None:
988
+ assert len(last_hidden_states) == len(self.config.output_exit_layers) + 1
989
+ elif self.config.output_full_model and self.config.output_exit_layers is None:
990
+ assert len(last_hidden_states) == 1
991
+ elif self.config.output_exit_layers is not None:
992
+ assert len(last_hidden_states) == len(self.config.output_exit_layers)
993
+
994
+ exit_logtis = tuple()
995
+ if self.config.output_exit_layers is not None:
996
+ for i, output_exit_layer in enumerate(self.config.output_exit_layers):
997
+ hidden_states = last_hidden_states[i]
998
+ if not self.config.tie_exit_lm_head:
999
+ exit_index = self.config.exit_layer_indices.index(output_exit_layer)
1000
+ lm_head = self.model.exit_modules[exit_index][-1]
1001
+ else:
1002
+ lm_head = self.lm_head
1003
+ logits = lm_head(hidden_states)
1004
+ exit_logtis += (logits,)
1005
+
1006
+
1007
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1008
+ if self.config.output_full_model:
1009
+ hidden_states = last_hidden_states[-1]
1010
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1011
+ exit_logtis += (logits,)
1012
+
1013
+ losses = []
1014
+ if labels is not None:
1015
+ for logits in exit_logtis:
1016
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1017
+ losses.append(loss)
1018
+
1019
+ if not return_dict:
1020
+ output = (exit_logtis,) + outputs[1:]
1021
+ return (loss,) + output if loss is not None else output
1022
+
1023
+ return CausalLMOutputWithPast(
1024
+ losses=losses,
1025
+ logits=exit_logtis,
1026
+ past_key_values=outputs.past_key_values,
1027
+ hidden_states=outputs.hidden_states,
1028
+ attentions=outputs.attentions,
1029
+ )