Guanzheng commited on
Commit
1dc5479
1 Parent(s): 74fc64f

Upload 3 files

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