Guanzheng commited on
Commit
481b512
1 Parent(s): 72fe262
Files changed (3) hide show
  1. clex_layer.py +138 -0
  2. configuration_clex.py +148 -0
  3. modeling_llama.py +974 -0
clex_layer.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchdiffeq import odeint
4
+
5
+
6
+
7
+ import math
8
+
9
+ class ODELinear(nn.Module):
10
+ def __init__(
11
+ self,
12
+ dim: int,
13
+ factor,
14
+ **kwargs
15
+ ):
16
+ super().__init__()
17
+ self.ode_up_proj = nn.Parameter(torch.empty(dim//2, factor*dim).to(torch.float32))
18
+ self.ode_down_proj = nn.Parameter(torch.empty(factor*dim, dim//2).to(torch.float32))
19
+ self.dim = dim
20
+ self.act = torch.nn.SiLU()
21
+ self.reset_parameters()
22
+
23
+ def reset_parameters(self):
24
+ nn.init.kaiming_uniform_(self.ode_up_proj, a=math.sqrt(5))
25
+ nn.init.zeros_(self.ode_down_proj)
26
+
27
+ def get_time_embedding(self, t, base=10000, device='cuda', dtype=torch.float32):
28
+ if t < 1:
29
+ alpha = 1
30
+ else:
31
+ alpha = 2*t-1
32
+ ntk_base = base * alpha ** (self.dim / (self.dim-2))
33
+ ntk_inv_freq = 1.0 / (ntk_base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
34
+ index = torch.arange(0, self.dim, 2, dtype=torch.float32).to(device)
35
+ delta_ntk_freq = -2*index/(self.dim-2) * 1 / (base ** (index/self.dim) * (alpha ** (index/(self.dim-2) + 1)))
36
+ return delta_ntk_freq.to(device, dtype=dtype), ntk_inv_freq.to(device, dtype=dtype)
37
+
38
+ def forward(self, t, x: torch.Tensor):
39
+ delta_time, time = self.get_time_embedding(t, device=x.device, dtype=x.dtype)
40
+ x = x + torch.log(time)
41
+ time_embed = delta_time / time
42
+ delta_inv_freq = self.act(x @ self.ode_up_proj.float()) @ self.ode_down_proj.float() + time_embed
43
+ return delta_inv_freq
44
+
45
+
46
+
47
+ class LlamaCLEXScalingRotaryEmbedding(nn.Module):
48
+
49
+ def __init__(self, dim, max_position_embeddings=2048, rope_scaling=None, base=10000, device=None) -> None:
50
+ super().__init__()
51
+
52
+ self.max_t = rope_scaling["max_factor"]
53
+ self.dim = dim
54
+ self.max_position_embeddings = max_position_embeddings
55
+ self.base = base
56
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
57
+ self.register_buffer("inv_freq", inv_freq)
58
+
59
+ self.proj_func = ODELinear(dim, rope_scaling["param_factor"])
60
+ self.rope_cached = None
61
+ self.max_t_cached = 0
62
+ self.freq_cached = None
63
+ self.time_dt = 0.01
64
+ self.ode_args = {
65
+ "method": "rk4",
66
+ "options": {"step_size": self.time_dt},
67
+ }
68
+
69
+ def sample_random_times(self, max_t, device):
70
+ return torch.randint(2, max_t, (1,), dtype = torch.long, device=device)
71
+
72
+ def get_random_position_ids(self, n=2048, max=8192):
73
+ positions = torch.randperm(max)[:n].sort().values
74
+ # positions = positions.to(device=device)
75
+ return positions
76
+
77
+
78
+ def get_continuous_freq(self, time_grid, ex_positions, device):
79
+ solution = odeint(
80
+ self.proj_func, torch.log(self.inv_freq.to(device, dtype=torch.float32)), time_grid, **self.ode_args
81
+ )
82
+ if time_grid.size(0) == 2:
83
+ training
84
+ scale_inv_freq = torch.exp(solution[1])
85
+ # print(time_grid[1].tolist(), torch.sum(scale_inv_freq).tolist(), torch.sum(self.proj_func.ode_down_proj).tolist())
86
+ freqs = torch.outer(ex_positions.float().squeeze(), scale_inv_freq)
87
+ else:
88
+ scale_inv_freq = torch.exp(solution)
89
+ freqs = torch.einsum('i, kl -> kil', ex_positions, scale_inv_freq)
90
+ embed = torch.cat((freqs,freqs), dim=-1)
91
+ return embed
92
+
93
+
94
+
95
+ def forward(self, device, dtype, seq_len, do_train=False):
96
+ device = self.proj_func.ode_up_proj.device
97
+ scale_factor = seq_len // self.max_position_embeddings
98
+ if do_train:
99
+ t_val = self.sample_random_times(self.max_t+1, device)[0]
100
+ import math
101
+ sampled_position_ids = self.get_random_position_ids(n=seq_len-2, max=seq_len*t_val-2).float()
102
+ ex_positions = torch.cat([
103
+ torch.tensor([0]),
104
+ (sampled_position_ids + 1) / scale_factor,
105
+ torch.tensor([seq_len*t_val//scale_factor-1])]
106
+ ).to(device, dtype=torch.float32)
107
+ else:
108
+ t_val = scale_factor if seq_len%self.max_position_embeddings == 0.0 else scale_factor + 1
109
+ t_val = t_val if t_val <= self.max_t else self.max_t
110
+ ex_positions = torch.arange(0, self.max_position_embeddings * t_val, dtype=torch.float32).to(device)
111
+
112
+
113
+
114
+ if t_val == 1.0:
115
+ scale_inv_freq = self.inv_freq.to(device)
116
+ freqs = torch.outer(ex_positions.float().squeeze(), scale_inv_freq)
117
+ embed = torch.cat((freqs,freqs), dim=-1)
118
+ cos, sin = embed.cos()[None, None, :, :], embed.sin()[None, None, :, :]
119
+ elif do_train:
120
+ time_grid = torch.tensor([1.0, t_val]).float().to(device)
121
+ embed = self.get_continuous_freq(time_grid, ex_positions, device)
122
+ cos, sin = embed.cos()[None, None, :, :], embed.sin()[None, None, :, :]
123
+ else:
124
+ if t_val > self.max_t_cached:
125
+ time_grid = torch.arange(1.0, self.max_t + 1.0, dtype=torch.float32).to(device)
126
+ if self.freq_cached is None:
127
+ self.freq_cached = self.get_continuous_freq(time_grid, ex_positions, device)
128
+ embed = self.freq_cached[int(t_val)-1.0]
129
+ self.rope_cached = torch.cat((embed.cos()[None, None, None, :, :], embed.sin()[None, None, None, :, :]), dim=0)
130
+ self.max_t_cached = t_val
131
+ cos, sin = self.rope_cached
132
+
133
+ return torch.cat(
134
+ (cos[None, :, :, :seq_len, ...].to(dtype=dtype),
135
+ sin[None, :, :, :seq_len, ...].to(dtype=dtype)),
136
+ dim=0
137
+ )
138
+
configuration_clex.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ r"""
34
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
35
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
36
+ defaults will yield a similar configuration to that of the LLaMA-7B.
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 32000):
44
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
45
+ `inputs_ids` passed when calling [`LlamaModel`]
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 11008):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 32):
51
+ Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads (`int`, *optional*, defaults to 32):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ num_key_value_heads (`int`, *optional*):
55
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
56
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
57
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
58
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
59
+ by meanpooling all the original heads within that group. For more details checkout [this
60
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
61
+ `num_attention_heads`.
62
+ pretraining_tp (`int`, *optional*, defaults to `1`):
63
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
64
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
65
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
66
+ issue](https://github.com/pytorch/pytorch/issues/76232).
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
70
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
71
+ just in case (e.g., 512 or 1024 or 2048).
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_scaling (`Dict`, *optional*):
82
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling
83
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
84
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
85
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
86
+ these scaling strategies behave:
87
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
88
+ experimental feature, subject to breaking API changes in future versions.
89
+
90
+ Example:
91
+
92
+ ```python
93
+ >>> from transformers import LlamaModel, LlamaConfig
94
+
95
+ >>> # Initializing a LLaMA llama-7b style configuration
96
+ >>> configuration = LlamaConfig()
97
+
98
+ >>> # Initializing a model from the llama-7b style configuration
99
+ >>> model = LlamaModel(configuration)
100
+
101
+ >>> # Accessing the model configuration
102
+ >>> configuration = model.config
103
+ ```"""
104
+ model_type = "llama"
105
+ keys_to_ignore_at_inference = ["past_key_values"]
106
+
107
+ def __init__(
108
+ self,
109
+ rope_scaling=None,
110
+ use_flashattn=True,
111
+ log_scale=True,
112
+ **kwargs,
113
+ ):
114
+ super().__init__(
115
+ **kwargs,
116
+ )
117
+ self.use_flashattn = use_flashattn
118
+ self.log_scale = log_scale
119
+ self.rope_theta = 10000
120
+ self.max_position_embeddings = 4096
121
+ self.data_length = 4096
122
+ self.rope_scaling = rope_scaling
123
+ self._rope_scaling_validation()
124
+
125
+
126
+ def _rope_scaling_validation(self):
127
+ """
128
+ Validate the `rope_scaling` configuration.
129
+ """
130
+ if self.rope_scaling is None:
131
+ return
132
+
133
+ # if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
134
+ # raise ValueError(
135
+ # "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
136
+ # f"got {self.rope_scaling}"
137
+ # )
138
+ rope_scaling_type = self.rope_scaling.get("type", None)
139
+ rope_scaling_max_factor = self.rope_scaling.get("max_factor", None)
140
+ rope_scaling_param_factor = self.rope_scaling.get("param_factor", None)
141
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", "clex"]:
142
+ raise ValueError(
143
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
144
+ )
145
+ # if rope_scaling_max_factor is None or not isinstance(rope_scaling_max_factor, float) or rope_scaling_max_factor <= 1.0:
146
+ # raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_max_factor}")
147
+ # if rope_scaling_param_factor is None or not isinstance(rope_scaling_param_factor, float) or rope_scaling_param_factor <= 1.0:
148
+ # raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_param_factor}")
modeling_llama.py ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from .configuration_clex import CLEXLlamaConfig
34
+ from .clex_layer import LlamaCLEXScalingRotaryEmbedding
35
+
36
+
37
+ from einops import rearrange
38
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func, flash_attn_qkvpacked_func, flash_attn_with_kvcache
39
+ # from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
40
+ from flash_attn.bert_padding import unpad_input, pad_input
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ _CONFIG_FOR_DOC = "CLEXLlamaConfig"
46
+
47
+
48
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
49
+ def _make_causal_mask(
50
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
51
+ ):
52
+ """
53
+ Make causal mask used for bi-directional self-attention.
54
+ """
55
+ bsz, tgt_len = input_ids_shape
56
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
57
+ mask_cond = torch.arange(mask.size(-1), device=device)
58
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
59
+ mask = mask.to(dtype)
60
+
61
+ if past_key_values_length > 0:
62
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
63
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
64
+
65
+
66
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
67
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
68
+ """
69
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
70
+ """
71
+ bsz, src_len = mask.size()
72
+ tgt_len = tgt_len if tgt_len is not None else src_len
73
+
74
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
75
+
76
+ inverted_mask = 1.0 - expanded_mask
77
+
78
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
79
+
80
+
81
+ class LlamaRMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ LlamaRMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
92
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
93
+
94
+ # convert into half-precision if necessary
95
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
96
+ hidden_states = hidden_states.to(self.weight.dtype)
97
+
98
+ return self.weight * hidden_states
99
+
100
+
101
+ class LlamaRotaryEmbedding(torch.nn.Module):
102
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
103
+ super().__init__()
104
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
105
+ self.register_buffer("inv_freq", inv_freq)
106
+
107
+ # Build here to make `torch.jit.trace` work.
108
+ self.max_seq_len_cached = max_position_embeddings
109
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
110
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
111
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
112
+ emb = torch.cat((freqs, freqs), dim=-1)
113
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
114
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
115
+
116
+ def forward(self, x, seq_len=None):
117
+ # x: [bs, num_attention_heads, seq_len, head_size]
118
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
119
+ if seq_len > self.max_seq_len_cached:
120
+ self.max_seq_len_cached = seq_len
121
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
122
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
123
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
124
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
125
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
126
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
127
+ return (
128
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
129
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
130
+ )
131
+
132
+
133
+ def rotate_half(x):
134
+ """Rotates half the hidden dims of the input."""
135
+ x1 = x[..., : x.shape[-1] // 2]
136
+ x2 = x[..., x.shape[-1] // 2 :]
137
+ return torch.cat((-x2, x1), dim=-1)
138
+
139
+
140
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
141
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
142
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
143
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
144
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
145
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
146
+ q_embed = (q * cos) + (rotate_half(q) * sin)
147
+ k_embed = (k * cos) + (rotate_half(k) * sin)
148
+ return q_embed, k_embed
149
+
150
+
151
+ class LlamaMLP(nn.Module):
152
+ def __init__(
153
+ self,
154
+ hidden_size: int,
155
+ intermediate_size: int,
156
+ hidden_act: str,
157
+ ):
158
+ super().__init__()
159
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
160
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
161
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
162
+ self.act_fn = ACT2FN[hidden_act]
163
+
164
+ def forward(self, x):
165
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
166
+
167
+
168
+ class LlamaAttention(nn.Module):
169
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
170
+
171
+ def __init__(self, config: CLEXLlamaConfig):
172
+ super().__init__()
173
+ self.config = config
174
+ self.hidden_size = config.hidden_size
175
+ self.num_heads = config.num_attention_heads
176
+ self.head_dim = self.hidden_size // self.num_heads
177
+ self.max_position_embeddings = config.max_position_embeddings
178
+ self.log_scale = config.log_scale
179
+ if (self.head_dim * self.num_heads) != self.hidden_size:
180
+ raise ValueError(
181
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
182
+ f" and `num_heads`: {self.num_heads})."
183
+ )
184
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
185
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
186
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
187
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
188
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
189
+
190
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
191
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
192
+
193
+ def flash_attn_forward(
194
+ self,
195
+ qkv: torch.Tensor,
196
+ key_padding_mask: Optional[torch.Tensor] = None,
197
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
198
+ """Input shape: Batch x Time x Channel
199
+
200
+ attention_mask: [bsz, q_len]
201
+ """
202
+
203
+ bsz, q_len, *_ = qkv.size()
204
+
205
+ if key_padding_mask is None:
206
+ # qkv = rearrange(qkv, "b s ... -> (b s) ...")
207
+ max_s = q_len
208
+ cu_q_lens = torch.arange(
209
+ 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
210
+ )
211
+ output = flash_attn_qkvpacked_func(
212
+ qkv, 0.0, softmax_scale=None, causal=True
213
+ )
214
+ else:
215
+ nheads = qkv.shape[-2]
216
+ x = rearrange(qkv, "b s three h d -> b s (three h d)")
217
+ x_unpad, indices, cu_q_lens, max_s = unpad_input(x, key_padding_mask)
218
+ x_unpad = rearrange(
219
+ x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads
220
+ )
221
+ output_unpad = flash_attn_varlen_qkvpacked_func(
222
+ x_unpad, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
223
+ )
224
+ output = rearrange(
225
+ pad_input(
226
+ rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, bsz, q_len
227
+ ),
228
+ "b s (h d) -> b s h d",
229
+ h=nheads,
230
+ )
231
+ return self.o_proj(rearrange(output, "b s h d -> b s (h d)"))
232
+
233
+ def forward(
234
+ self,
235
+ hidden_states: torch.Tensor,
236
+ attention_mask: Optional[torch.Tensor] = None,
237
+ position_ids: Optional[torch.LongTensor] = None,
238
+ pack_cos_sin = None,
239
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
240
+ output_attentions: bool = False,
241
+ use_cache: bool = False,
242
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
243
+ bsz, q_len, _ = hidden_states.size()
244
+
245
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
246
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
247
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
248
+
249
+ kv_seq_len = key_states.shape[-2]
250
+ if past_key_value is not None:
251
+ kv_seq_len += past_key_value[0].shape[-2]
252
+ # [bsz, nh, t, hd]
253
+
254
+ if past_key_value is not None:
255
+ kv_seq_len += past_key_value[0].shape[-2]
256
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
257
+
258
+ if pack_cos_sin is not None:
259
+ cos, sin = pack_cos_sin
260
+ else:
261
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
262
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
263
+
264
+ if past_key_value is not None:
265
+ # reuse k, v, self_attention
266
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
267
+
268
+ past_key_value = (key_states, value_states) if use_cache else None
269
+
270
+
271
+ if self.log_scale:
272
+ log_n = torch.log(torch.tensor(kv_seq_len*1.0)).to(query_states.device, dtype=query_states.dtype) / \
273
+ torch.log(torch.tensor(self.config.max_position_embeddings)).to(query_states.device, dtype=query_states.dtype)
274
+ query_states = query_states * log_n
275
+ if query_states.shape[-2] == 1 or query_states.shape[-2] != key_states.shape[-2] or not self.config.use_flashattn:
276
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
277
+
278
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
279
+ raise ValueError(
280
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
281
+ f" {attn_weights.size()}"
282
+ )
283
+
284
+ if attention_mask is not None:
285
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
286
+ raise ValueError(
287
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
288
+ )
289
+ attn_weights = attn_weights + attention_mask
290
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
291
+
292
+ # upcast attention to fp32
293
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
294
+ attn_output = torch.matmul(attn_weights, value_states)
295
+
296
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
297
+ raise ValueError(
298
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
299
+ f" {attn_output.size()}"
300
+ )
301
+
302
+ attn_output = attn_output.transpose(1, 2)
303
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
304
+
305
+ attn_output = self.o_proj(attn_output)
306
+
307
+ if not output_attentions:
308
+ attn_weights = None
309
+
310
+ return attn_output, attn_weights, past_key_value
311
+ elif past_key_value is not None:
312
+ output = flash_attn_with_kvcache(
313
+ query_states.transpose(1, 2),
314
+ key_states.transpose(1, 2),
315
+ value_states.transpose(1, 2),
316
+ cache_seqlens=kv_seq_len,
317
+ causal=True,
318
+ )
319
+ attn_output = self.o_proj(rearrange(output, "b s h d -> b s (h d)"))
320
+ else:
321
+ qkv = torch.stack(
322
+ [query_states, key_states, value_states], dim=2
323
+ ) # [bsz, nh, 3, q_len, hd]
324
+ qkv = qkv.transpose(1, 3) # [bsz, q_len, 3, nh, hd]
325
+ attn_output = self.flash_attn_forward(qkv)
326
+ return attn_output, None, past_key_value
327
+
328
+
329
+ class LlamaDecoderLayer(nn.Module):
330
+ def __init__(self, config: CLEXLlamaConfig):
331
+ super().__init__()
332
+ self.hidden_size = config.hidden_size
333
+ self.self_attn = LlamaAttention(config=config)
334
+ self.mlp = LlamaMLP(
335
+ hidden_size=self.hidden_size,
336
+ intermediate_size=config.intermediate_size,
337
+ hidden_act=config.hidden_act,
338
+ )
339
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
340
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
341
+
342
+ def forward(
343
+ self,
344
+ hidden_states: torch.Tensor,
345
+ attention_mask: Optional[torch.Tensor] = None,
346
+ position_ids: Optional[torch.LongTensor] = None,
347
+ pack_cos_sin=None,
348
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
349
+ output_attentions: Optional[bool] = False,
350
+ use_cache: Optional[bool] = False,
351
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
352
+ """
353
+ Args:
354
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
355
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
356
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
357
+ output_attentions (`bool`, *optional*):
358
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
359
+ returned tensors for more detail.
360
+ use_cache (`bool`, *optional*):
361
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
362
+ (see `past_key_values`).
363
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
364
+ """
365
+
366
+ residual = hidden_states
367
+
368
+ hidden_states = self.input_layernorm(hidden_states)
369
+
370
+ # Self Attention
371
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
372
+ hidden_states=hidden_states,
373
+ attention_mask=attention_mask,
374
+ position_ids=position_ids,
375
+ pack_cos_sin=pack_cos_sin,
376
+ past_key_value=past_key_value,
377
+ output_attentions=output_attentions,
378
+ use_cache=use_cache,
379
+ )
380
+ hidden_states = residual + hidden_states
381
+
382
+ # Fully Connected
383
+ residual = hidden_states
384
+ hidden_states = self.post_attention_layernorm(hidden_states)
385
+ hidden_states = self.mlp(hidden_states)
386
+ hidden_states = residual + hidden_states
387
+
388
+ outputs = (hidden_states,)
389
+
390
+ if output_attentions:
391
+ outputs += (self_attn_weights,)
392
+
393
+ if use_cache:
394
+ outputs += (present_key_value,)
395
+
396
+ return outputs
397
+
398
+
399
+ LLAMA_START_DOCSTRING = r"""
400
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
401
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
402
+ etc.)
403
+
404
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
405
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
406
+ and behavior.
407
+
408
+ Parameters:
409
+ config ([`CLEXLlamaConfig`]):
410
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
411
+ load the weights associated with the model, only the configuration. Check out the
412
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
413
+ """
414
+
415
+
416
+ @add_start_docstrings(
417
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
418
+ LLAMA_START_DOCSTRING,
419
+ )
420
+ class LlamaPreTrainedModel(PreTrainedModel):
421
+ config_class = CLEXLlamaConfig
422
+ base_model_prefix = "model"
423
+ supports_gradient_checkpointing = True
424
+ _no_split_modules = ["LlamaDecoderLayer"]
425
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
426
+ _keep_in_fp32_modules = ["model.clex_layer.proj_func.ode_up_proj", "model.clex_layer.proj_func.ode_down_proj", "model.clex_layer.inv_freq"]
427
+
428
+ def _init_weights(self, module):
429
+ std = self.config.initializer_range
430
+ if isinstance(module, nn.Linear):
431
+ module.weight.data.normal_(mean=0.0, std=std)
432
+ if module.bias is not None:
433
+ module.bias.data.zero_()
434
+ elif isinstance(module, nn.Embedding):
435
+ module.weight.data.normal_(mean=0.0, std=std)
436
+ if module.padding_idx is not None:
437
+ module.weight.data[module.padding_idx].zero_()
438
+
439
+ def _set_gradient_checkpointing(self, module, value=False):
440
+ if isinstance(module, LlamaModel):
441
+ module.gradient_checkpointing = value
442
+
443
+
444
+ LLAMA_INPUTS_DOCSTRING = r"""
445
+ Args:
446
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
447
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
448
+ it.
449
+
450
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
451
+ [`PreTrainedTokenizer.__call__`] for details.
452
+
453
+ [What are input IDs?](../glossary#input-ids)
454
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
455
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
456
+
457
+ - 1 for tokens that are **not masked**,
458
+ - 0 for tokens that are **masked**.
459
+
460
+ [What are attention masks?](../glossary#attention-mask)
461
+
462
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
463
+ [`PreTrainedTokenizer.__call__`] for details.
464
+
465
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
466
+ `past_key_values`).
467
+
468
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
469
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
470
+ information on the default strategy.
471
+
472
+ - 1 indicates the head is **not masked**,
473
+ - 0 indicates the head is **masked**.
474
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
475
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
476
+ config.n_positions - 1]`.
477
+
478
+ [What are position IDs?](../glossary#position-ids)
479
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
480
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
481
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
482
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
483
+
484
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
485
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
486
+
487
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
488
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
489
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
490
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
491
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
492
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
493
+ model's internal embedding lookup matrix.
494
+ use_cache (`bool`, *optional*):
495
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
496
+ `past_key_values`).
497
+ output_attentions (`bool`, *optional*):
498
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
499
+ tensors for more detail.
500
+ output_hidden_states (`bool`, *optional*):
501
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
502
+ more detail.
503
+ return_dict (`bool`, *optional*):
504
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
505
+ """
506
+
507
+ from torchdiffeq import odeint
508
+ from CLEX.clex_layer import ODELinear
509
+ @add_start_docstrings(
510
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
511
+ LLAMA_START_DOCSTRING,
512
+ )
513
+ class LlamaModel(LlamaPreTrainedModel):
514
+ """
515
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
516
+
517
+ Args:
518
+ config: CLEXLlamaConfig
519
+ """
520
+
521
+ def __init__(self, config: CLEXLlamaConfig):
522
+ super().__init__(config)
523
+ self.padding_idx = config.pad_token_id
524
+ self.vocab_size = config.vocab_size
525
+
526
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
527
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
528
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
529
+ head_dim = config.hidden_size // config.num_attention_heads
530
+ if config.rope_scaling["type"] == "clex":
531
+ self.clex_layer = LlamaCLEXScalingRotaryEmbedding(head_dim, config.max_position_embeddings, config.rope_scaling)
532
+ self.gradient_checkpointing = False
533
+ # Initialize weights and apply final processing
534
+ self.post_init()
535
+
536
+
537
+ def get_input_embeddings(self):
538
+ return self.embed_tokens
539
+
540
+ def set_input_embeddings(self, value):
541
+ self.embed_tokens = value
542
+
543
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
544
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
545
+ # create causal mask
546
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
547
+ combined_attention_mask = None
548
+ if input_shape[-1] > 1:
549
+ combined_attention_mask = _make_causal_mask(
550
+ input_shape,
551
+ inputs_embeds.dtype,
552
+ device=inputs_embeds.device,
553
+ past_key_values_length=past_key_values_length,
554
+ )
555
+
556
+ if attention_mask is not None:
557
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
558
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
559
+ inputs_embeds.device
560
+ )
561
+ combined_attention_mask = (
562
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
563
+ )
564
+
565
+ return combined_attention_mask
566
+
567
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
568
+ def forward(
569
+ self,
570
+ input_ids: torch.LongTensor = None,
571
+ attention_mask: Optional[torch.Tensor] = None,
572
+ position_ids: Optional[torch.LongTensor] = None,
573
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
574
+ inputs_embeds: Optional[torch.FloatTensor] = None,
575
+ use_cache: Optional[bool] = None,
576
+ output_attentions: Optional[bool] = None,
577
+ output_hidden_states: Optional[bool] = None,
578
+ return_dict: Optional[bool] = None,
579
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
580
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
581
+ output_hidden_states = (
582
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
583
+ )
584
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
585
+
586
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
587
+
588
+ # retrieve input_ids and inputs_embeds
589
+ if input_ids is not None and inputs_embeds is not None:
590
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
591
+ elif input_ids is not None:
592
+ batch_size, seq_length = input_ids.shape
593
+ elif inputs_embeds is not None:
594
+ batch_size, seq_length, _ = inputs_embeds.shape
595
+ else:
596
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
597
+
598
+ seq_length_with_past = seq_length
599
+ past_key_values_length = 0
600
+
601
+ if past_key_values is not None:
602
+ past_key_values_length = past_key_values[0][0].shape[2]
603
+ seq_length_with_past = seq_length_with_past + past_key_values_length
604
+
605
+ if position_ids is None:
606
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
607
+ position_ids = torch.arange(
608
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
609
+ )
610
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
611
+ else:
612
+ position_ids = position_ids.view(-1, seq_length).long()
613
+
614
+ if inputs_embeds is None:
615
+ inputs_embeds = self.embed_tokens(input_ids)
616
+ # embed positions
617
+ if attention_mask is None:
618
+ attention_mask = torch.ones(
619
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
620
+ )
621
+ attention_mask = self._prepare_decoder_attention_mask(
622
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
623
+ )
624
+
625
+ hidden_states = inputs_embeds
626
+
627
+ if self.gradient_checkpointing and self.training:
628
+ if use_cache:
629
+ logger.warning_once(
630
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
631
+ )
632
+ use_cache = False
633
+
634
+ # decoder layers
635
+ all_hidden_states = () if output_hidden_states else None
636
+ all_self_attns = () if output_attentions else None
637
+ next_decoder_cache = () if use_cache else None
638
+
639
+ pack_cos_sin = None
640
+ if self.config.rope_scaling["type"] == "clex":
641
+ pack_cos_sin = self.clex_layer(inputs_embeds.device, inputs_embeds.dtype, seq_length_with_past, self.training)
642
+
643
+ for idx, decoder_layer in enumerate(self.layers):
644
+ if output_hidden_states:
645
+ all_hidden_states += (hidden_states,)
646
+
647
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
648
+
649
+ if self.gradient_checkpointing and self.training:
650
+
651
+ def create_custom_forward(module):
652
+ def custom_forward(*inputs):
653
+ # None for past_key_value
654
+ return module(*inputs, output_attentions, None)
655
+
656
+ return custom_forward
657
+
658
+ layer_outputs = torch.utils.checkpoint.checkpoint(
659
+ create_custom_forward(decoder_layer),
660
+ hidden_states,
661
+ attention_mask,
662
+ position_ids,
663
+ pack_cos_sin,
664
+ None,
665
+ )
666
+ else:
667
+ layer_outputs = decoder_layer(
668
+ hidden_states,
669
+ attention_mask=attention_mask,
670
+ position_ids=position_ids,
671
+ pack_cos_sin=pack_cos_sin,
672
+ past_key_value=past_key_value,
673
+ output_attentions=output_attentions,
674
+ use_cache=use_cache,
675
+ )
676
+
677
+ hidden_states = layer_outputs[0]
678
+
679
+ if use_cache:
680
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
681
+
682
+ if output_attentions:
683
+ all_self_attns += (layer_outputs[1],)
684
+
685
+ hidden_states = self.norm(hidden_states)
686
+
687
+ # add hidden states from the last decoder layer
688
+ if output_hidden_states:
689
+ all_hidden_states += (hidden_states,)
690
+
691
+ next_cache = next_decoder_cache if use_cache else None
692
+ if not return_dict:
693
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
694
+ return BaseModelOutputWithPast(
695
+ last_hidden_state=hidden_states,
696
+ past_key_values=next_cache,
697
+ hidden_states=all_hidden_states,
698
+ attentions=all_self_attns,
699
+ )
700
+
701
+
702
+ class LlamaForCausalLM(LlamaPreTrainedModel):
703
+ def __init__(self, config):
704
+ super().__init__(config)
705
+ self.model = LlamaModel(config)
706
+
707
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
708
+
709
+ # Initialize weights and apply final processing
710
+ self.post_init()
711
+
712
+ def get_input_embeddings(self):
713
+ return self.model.embed_tokens
714
+
715
+ def set_input_embeddings(self, value):
716
+ self.model.embed_tokens = value
717
+
718
+ def get_output_embeddings(self):
719
+ return self.lm_head
720
+
721
+ def set_output_embeddings(self, new_embeddings):
722
+ self.lm_head = new_embeddings
723
+
724
+ def set_decoder(self, decoder):
725
+ self.model = decoder
726
+
727
+ def get_decoder(self):
728
+ return self.model
729
+
730
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
731
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
732
+ def forward(
733
+ self,
734
+ input_ids: torch.LongTensor = None,
735
+ attention_mask: Optional[torch.Tensor] = None,
736
+ position_ids: Optional[torch.LongTensor] = None,
737
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
738
+ inputs_embeds: Optional[torch.FloatTensor] = None,
739
+ labels: Optional[torch.LongTensor] = None,
740
+ use_cache: Optional[bool] = None,
741
+ output_attentions: Optional[bool] = None,
742
+ output_hidden_states: Optional[bool] = None,
743
+ return_dict: Optional[bool] = None,
744
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
745
+ r"""
746
+ Args:
747
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
748
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
749
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
750
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
751
+
752
+ Returns:
753
+
754
+ Example:
755
+
756
+ ```python
757
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
758
+
759
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
760
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
761
+
762
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
763
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
764
+
765
+ >>> # Generate
766
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
767
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
768
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
769
+ ```"""
770
+
771
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
772
+ output_hidden_states = (
773
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
774
+ )
775
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
776
+
777
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
778
+ outputs = self.model(
779
+ input_ids=input_ids,
780
+ attention_mask=attention_mask,
781
+ position_ids=position_ids,
782
+ past_key_values=past_key_values,
783
+ inputs_embeds=inputs_embeds,
784
+ use_cache=use_cache,
785
+ output_attentions=output_attentions,
786
+ output_hidden_states=output_hidden_states,
787
+ return_dict=return_dict,
788
+ )
789
+
790
+ hidden_states = outputs[0]
791
+ logits = self.lm_head(hidden_states)
792
+
793
+ loss = None
794
+ if labels is not None:
795
+ # Shift so that tokens < n predict n
796
+ shift_logits = logits[..., :-1, :].contiguous()
797
+ shift_labels = labels[..., 1:].contiguous()
798
+ # Flatten the tokens
799
+ loss_fct = CrossEntropyLoss()
800
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
801
+ shift_labels = shift_labels.view(-1)
802
+ # Enable model parallelism
803
+ shift_labels = shift_labels.to(shift_logits.device)
804
+ loss = loss_fct(shift_logits, shift_labels)
805
+
806
+ if not return_dict:
807
+ output = (logits,) + outputs[1:]
808
+ return (loss,) + output if loss is not None else output
809
+ return CausalLMOutputWithPast(
810
+ loss=loss,
811
+ logits=logits,
812
+ past_key_values=outputs.past_key_values,
813
+ hidden_states=outputs.hidden_states,
814
+ attentions=outputs.attentions,
815
+ )
816
+
817
+ def prepare_inputs_for_generation(
818
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
819
+ ):
820
+ if past_key_values:
821
+ input_ids = input_ids[:, -1:]
822
+
823
+ position_ids = kwargs.get("position_ids", None)
824
+ if attention_mask is not None and position_ids is None:
825
+ # create position_ids on the fly for batch generation
826
+ position_ids = attention_mask.long().cumsum(-1) - 1
827
+ position_ids.masked_fill_(attention_mask == 0, 1)
828
+ if past_key_values:
829
+ position_ids = position_ids[:, -1].unsqueeze(-1)
830
+
831
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
832
+ if inputs_embeds is not None and past_key_values is None:
833
+ model_inputs = {"inputs_embeds": inputs_embeds}
834
+ else:
835
+ model_inputs = {"input_ids": input_ids}
836
+
837
+ model_inputs.update(
838
+ {
839
+ "position_ids": position_ids,
840
+ "past_key_values": past_key_values,
841
+ "use_cache": kwargs.get("use_cache"),
842
+ "attention_mask": attention_mask,
843
+ }
844
+ )
845
+ return model_inputs
846
+
847
+ @staticmethod
848
+ def _reorder_cache(past_key_values, beam_idx):
849
+ reordered_past = ()
850
+ for layer_past in past_key_values:
851
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
852
+ return reordered_past
853
+
854
+
855
+ @add_start_docstrings(
856
+ """
857
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
858
+
859
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
860
+ (e.g. GPT-2) do.
861
+
862
+ Since it does classification on the last token, it requires to know the position of the last token. If a
863
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
864
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
865
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
866
+ each row of the batch).
867
+ """,
868
+ LLAMA_START_DOCSTRING,
869
+ )
870
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
871
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
872
+
873
+ def __init__(self, config):
874
+ super().__init__(config)
875
+ self.num_labels = config.num_labels
876
+ self.model = LlamaModel(config)
877
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
878
+
879
+ # Initialize weights and apply final processing
880
+ self.post_init()
881
+
882
+ def get_input_embeddings(self):
883
+ return self.model.embed_tokens
884
+
885
+ def set_input_embeddings(self, value):
886
+ self.model.embed_tokens = value
887
+
888
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
889
+ def forward(
890
+ self,
891
+ input_ids: torch.LongTensor = None,
892
+ attention_mask: Optional[torch.Tensor] = None,
893
+ position_ids: Optional[torch.LongTensor] = None,
894
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
895
+ inputs_embeds: Optional[torch.FloatTensor] = None,
896
+ labels: Optional[torch.LongTensor] = None,
897
+ use_cache: Optional[bool] = None,
898
+ output_attentions: Optional[bool] = None,
899
+ output_hidden_states: Optional[bool] = None,
900
+ return_dict: Optional[bool] = None,
901
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
902
+ r"""
903
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
904
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
905
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
906
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
907
+ """
908
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
909
+
910
+ transformer_outputs = self.model(
911
+ input_ids,
912
+ attention_mask=attention_mask,
913
+ position_ids=position_ids,
914
+ past_key_values=past_key_values,
915
+ inputs_embeds=inputs_embeds,
916
+ use_cache=use_cache,
917
+ output_attentions=output_attentions,
918
+ output_hidden_states=output_hidden_states,
919
+ return_dict=return_dict,
920
+ )
921
+ hidden_states = transformer_outputs[0]
922
+ logits = self.score(hidden_states)
923
+
924
+ if input_ids is not None:
925
+ batch_size = input_ids.shape[0]
926
+ else:
927
+ batch_size = inputs_embeds.shape[0]
928
+
929
+ if self.config.pad_token_id is None and batch_size != 1:
930
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
931
+ if self.config.pad_token_id is None:
932
+ sequence_lengths = -1
933
+ else:
934
+ if input_ids is not None:
935
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
936
+ else:
937
+ sequence_lengths = -1
938
+
939
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
940
+
941
+ loss = None
942
+ if labels is not None:
943
+ labels = labels.to(logits.device)
944
+ if self.config.problem_type is None:
945
+ if self.num_labels == 1:
946
+ self.config.problem_type = "regression"
947
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
948
+ self.config.problem_type = "single_label_classification"
949
+ else:
950
+ self.config.problem_type = "multi_label_classification"
951
+
952
+ if self.config.problem_type == "regression":
953
+ loss_fct = MSELoss()
954
+ if self.num_labels == 1:
955
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
956
+ else:
957
+ loss = loss_fct(pooled_logits, labels)
958
+ elif self.config.problem_type == "single_label_classification":
959
+ loss_fct = CrossEntropyLoss()
960
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
961
+ elif self.config.problem_type == "multi_label_classification":
962
+ loss_fct = BCEWithLogitsLoss()
963
+ loss = loss_fct(pooled_logits, labels)
964
+ if not return_dict:
965
+ output = (pooled_logits,) + transformer_outputs[1:]
966
+ return ((loss,) + output) if loss is not None else output
967
+
968
+ return SequenceClassifierOutputWithPast(
969
+ loss=loss,
970
+ logits=pooled_logits,
971
+ past_key_values=transformer_outputs.past_key_values,
972
+ hidden_states=transformer_outputs.hidden_states,
973
+ attentions=transformer_outputs.attentions,
974
+ )