DanielJacob commited on
Commit
cc6e3ee
·
verified ·
1 Parent(s): b8c80cf

Upload SVD_LlamaForCausalLM

Browse files
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "huggingface_repos/llama-7b-hf-svdllm-20",
3
+ "architectures": [
4
+ "SVD_LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "auto_map": {
8
+ "AutoConfig": "config_llama.SVD_LlamaConfig",
9
+ "AutoModelForCausalLM": "modeling_svd_llama.SVD_LlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 11008,
17
+ "max_position_embeddings": 2048,
18
+ "model_type": "llama",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 32,
21
+ "num_key_value_heads": 32,
22
+ "pad_token_id": 0,
23
+ "pretraining_tp": 1,
24
+ "ratio": 0.2,
25
+ "rms_norm_eps": 1e-06,
26
+ "rope_scaling": null,
27
+ "rope_theta": 10000.0,
28
+ "tie_word_embeddings": false,
29
+ "torch_dtype": "float16",
30
+ "transformers_version": "4.35.2",
31
+ "use_cache": true,
32
+ "vocab_size": 32000
33
+ }
config_llama.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
8
+
9
+
10
+ class SVD_LlamaConfig(PretrainedConfig):
11
+ model_type = "llama"
12
+ keys_to_ignore_at_inference = ["past_key_values"]
13
+
14
+ def __init__(
15
+ self,
16
+ vocab_size=32000,
17
+ hidden_size=4096,
18
+ intermediate_size=11008,
19
+ num_hidden_layers=32,
20
+ num_attention_heads=32,
21
+ num_key_value_heads=None,
22
+ hidden_act="silu",
23
+ max_position_embeddings=2048,
24
+ initializer_range=0.02,
25
+ rms_norm_eps=1e-6,
26
+ use_cache=True,
27
+ pad_token_id=None,
28
+ bos_token_id=1,
29
+ eos_token_id=2,
30
+ pretraining_tp=1,
31
+ tie_word_embeddings=False,
32
+ rope_theta=10000.0,
33
+ rope_scaling=None,
34
+ attention_bias=False,
35
+ ratio=1,
36
+ **kwargs,
37
+ ):
38
+ self.vocab_size = vocab_size
39
+ self.max_position_embeddings = max_position_embeddings
40
+ self.hidden_size = hidden_size
41
+ self.intermediate_size = intermediate_size
42
+ self.num_hidden_layers = num_hidden_layers
43
+ self.num_attention_heads = num_attention_heads
44
+
45
+ # for backward compatibility
46
+ if num_key_value_heads is None:
47
+ num_key_value_heads = num_attention_heads
48
+
49
+ self.num_key_value_heads = num_key_value_heads
50
+ self.hidden_act = hidden_act
51
+ self.initializer_range = initializer_range
52
+ self.rms_norm_eps = rms_norm_eps
53
+ self.pretraining_tp = pretraining_tp
54
+ self.use_cache = use_cache
55
+ self.rope_theta = rope_theta
56
+ self.rope_scaling = rope_scaling
57
+ self._rope_scaling_validation()
58
+ self.attention_bias = attention_bias
59
+ self.ratio = ratio
60
+
61
+ super().__init__(
62
+ pad_token_id=pad_token_id,
63
+ bos_token_id=bos_token_id,
64
+ eos_token_id=eos_token_id,
65
+ tie_word_embeddings=tie_word_embeddings,
66
+ **kwargs,
67
+ )
68
+
69
+ def _rope_scaling_validation(self):
70
+ """
71
+ Validate the `rope_scaling` configuration.
72
+ """
73
+ if self.rope_scaling is None:
74
+ return
75
+
76
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
77
+ raise ValueError(
78
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
79
+ f"got {self.rope_scaling}"
80
+ )
81
+ rope_scaling_type = self.rope_scaling.get("type", None)
82
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
83
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
84
+ raise ValueError(
85
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
86
+ )
87
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
88
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.35.2"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb35494fec06b7e79b40de07fe9551618284d667539270ef234c7baaaff600da
3
+ size 3113907664
modeling_svd_llama.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple
3
+
4
+ import torch
5
+ import torch.utils.checkpoint
6
+ from torch import nn
7
+
8
+ from transformers.activations import ACT2FN
9
+ from transformers.utils import logging
10
+ from transformers import LlamaForCausalLM
11
+ from .config_llama import SVD_LlamaConfig
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ _CONFIG_FOR_DOC = "SVD_LlamaConfig"
16
+
17
+ class LlamaRMSNorm(nn.Module):
18
+ def __init__(self, hidden_size, eps=1e-6):
19
+ """
20
+ LlamaRMSNorm is equivalent to T5LayerNorm
21
+ """
22
+ super().__init__()
23
+ self.weight = nn.Parameter(torch.ones(hidden_size))
24
+ self.variance_epsilon = eps
25
+
26
+ def forward(self, hidden_states):
27
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
28
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
29
+
30
+ # convert into half-precision if necessary
31
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
32
+ hidden_states = hidden_states.to(self.weight.dtype)
33
+
34
+ return self.weight * hidden_states
35
+
36
+
37
+ class LlamaRotaryEmbedding(torch.nn.Module):
38
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
39
+ super().__init__()
40
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
41
+ self.register_buffer("inv_freq", inv_freq)
42
+
43
+ # Build here to make `torch.jit.trace` work.
44
+ self.max_seq_len_cached = max_position_embeddings
45
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
46
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
47
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
48
+ emb = torch.cat((freqs, freqs), dim=-1)
49
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
50
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
51
+
52
+ def forward(self, x, seq_len=None):
53
+ # x: [bs, num_attention_heads, seq_len, head_size]
54
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
55
+ if seq_len > self.max_seq_len_cached:
56
+ self.max_seq_len_cached = seq_len
57
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
58
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
59
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
60
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
61
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
62
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
63
+ return (
64
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
65
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
66
+ )
67
+
68
+
69
+ def rotate_half(x):
70
+ """Rotates half the hidden dims of the input."""
71
+ x1 = x[..., : x.shape[-1] // 2]
72
+ x2 = x[..., x.shape[-1] // 2 :]
73
+ return torch.cat((-x2, x1), dim=-1)
74
+
75
+
76
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
77
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
78
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
79
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
80
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
81
+
82
+ q_embed = (q * cos) + (rotate_half(q) * sin)
83
+ k_embed = (k * cos) + (rotate_half(k) * sin)
84
+ return q_embed, k_embed
85
+
86
+
87
+ class SVD_LlamaMLP(nn.Module):
88
+ def __init__(
89
+ self,
90
+ config: SVD_LlamaConfig
91
+ ):
92
+ super().__init__()
93
+ self.ratio = config.ratio
94
+ low_rank = int(config.intermediate_size * config.hidden_size * self.ratio / (config.intermediate_size + config.hidden_size))
95
+ self.gate_u_proj = nn.Linear(low_rank, config.intermediate_size, bias=False)
96
+ self.gate_v_proj = nn.Linear(config.hidden_size, low_rank, bias=False)
97
+
98
+ self.down_u_proj = nn.Linear(low_rank, config.hidden_size, bias=False)
99
+ self.down_v_proj = nn.Linear(config.intermediate_size, low_rank, bias=False)
100
+
101
+ self.up_u_proj = nn.Linear(low_rank, config.intermediate_size, bias=False)
102
+ self.up_v_proj = nn.Linear(config.hidden_size, low_rank, bias=False)
103
+ self.act_fn = ACT2FN[config.hidden_act]
104
+
105
+ def forward(self, x):
106
+ up = self.up_u_proj(self.up_v_proj(x))
107
+ gate = self.gate_u_proj(self.gate_v_proj(x))
108
+ return self.down_u_proj(self.down_v_proj(self.act_fn(gate) * up))
109
+
110
+
111
+ class SVD_LlamaAttention(nn.Module):
112
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
113
+
114
+ def __init__(self, config: SVD_LlamaConfig):
115
+ super().__init__()
116
+ self.config = config
117
+ self.hidden_size = config.hidden_size
118
+ self.num_heads = config.num_attention_heads
119
+ self.head_dim = self.hidden_size // self.num_heads
120
+ self.max_position_embeddings = config.max_position_embeddings
121
+ self.ratio = config.ratio # 1 means no truncate, just keep normal attn
122
+
123
+ if (self.head_dim * self.num_heads) != self.hidden_size:
124
+ raise ValueError(
125
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
126
+ f" and `num_heads`: {self.num_heads})."
127
+ )
128
+ low_rank = int(self.hidden_size * self.ratio/2)
129
+ self.q_u_proj = nn.Linear(low_rank, self.num_heads * self.head_dim, bias=False)
130
+ self.q_v_proj = nn.Linear(self.hidden_size, low_rank, bias=False)
131
+
132
+ self.k_u_proj = nn.Linear(low_rank, self.num_heads * self.head_dim, bias=False)
133
+ self.k_v_proj = nn.Linear(self.hidden_size, low_rank, bias=False)
134
+
135
+ self.v_u_proj = nn.Linear(low_rank, self.num_heads * self.head_dim, bias=False)
136
+ self.v_v_proj = nn.Linear(self.hidden_size, low_rank, bias=False)
137
+
138
+ self.o_u_proj = nn.Linear(low_rank, self.hidden_size, bias=False)
139
+ self.o_v_proj = nn.Linear(self.num_heads * self.head_dim, low_rank, bias=False)
140
+
141
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
142
+
143
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
144
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
145
+
146
+ def forward(
147
+ self,
148
+ hidden_states: torch.Tensor,
149
+ attention_mask: Optional[torch.Tensor] = None,
150
+ position_ids: Optional[torch.LongTensor] = None,
151
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
152
+ output_attentions: bool = False,
153
+ use_cache: bool = False,
154
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
155
+ bsz, q_len, _ = hidden_states.size()
156
+
157
+ query_states = self.q_u_proj(self.q_v_proj(hidden_states)).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
158
+
159
+ key_states = self.k_u_proj(self.k_v_proj(hidden_states)).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
160
+
161
+ value_states = self.v_u_proj(self.v_v_proj(hidden_states)).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
162
+
163
+ kv_seq_len = key_states.shape[-2]
164
+ if past_key_value is not None:
165
+ kv_seq_len += past_key_value[0].shape[-2]
166
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
167
+
168
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
169
+ # [bsz, nh, t, hd]
170
+
171
+ if past_key_value is not None:
172
+ # reuse k, v, self_attention
173
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
174
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
175
+
176
+ past_key_value = (key_states, value_states) if use_cache else None
177
+
178
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
179
+
180
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
181
+ raise ValueError(
182
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
183
+ f" {attn_weights.size()}"
184
+ )
185
+
186
+ if attention_mask is not None:
187
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
188
+ raise ValueError(
189
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
190
+ )
191
+ attn_weights = attn_weights + attention_mask
192
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device))
193
+
194
+ # upcast attention to fp32
195
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
196
+ attn_output = torch.matmul(attn_weights, value_states)
197
+
198
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
199
+ raise ValueError(
200
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
201
+ f" {attn_output.size()}"
202
+ )
203
+
204
+ attn_output = attn_output.transpose(1, 2)
205
+ attn_output = attn_output.reshape(bsz, q_len, -1)
206
+
207
+ attn_output = self.o_u_proj(self.o_v_proj(attn_output))
208
+
209
+ if not output_attentions:
210
+ attn_weights = None
211
+
212
+ return attn_output, attn_weights, past_key_value
213
+
214
+
215
+ class SVD_LlamaForCausalLM(LlamaForCausalLM):
216
+ config_class = SVD_LlamaConfig
217
+ def __init__(self, config: SVD_LlamaConfig):
218
+ super().__init__(config)
219
+ for i in range(len(self.model.layers)):
220
+ self.model.layers[i].mlp = SVD_LlamaMLP(config=config)
221
+ self.model.layers[i].self_attn = SVD_LlamaAttention(config)