Spaces:
Running
on
Zero
Running
on
Zero
Updated model architecture
Browse files- llama_diffusion_model.py +173 -58
llama_diffusion_model.py
CHANGED
@@ -1,73 +1,172 @@
|
|
1 |
-
import torch
|
2 |
import torch.nn as nn
|
3 |
-
import
|
|
|
4 |
from torch.amp import autocast
|
5 |
-
from transformers import AutoModelForCausalLM, PreTrainedModel, PretrainedConfig
|
6 |
from peft import LoraConfig, get_peft_model
|
|
|
|
|
7 |
import os
|
8 |
|
|
|
|
|
9 |
hf_token = os.getenv("HF_TOKEN")
|
10 |
|
11 |
-
class BidirectionalLlamaAttention(
|
12 |
-
def __init__(self, original_layer, masking='unidirectional'):
|
13 |
-
super().__init__()
|
14 |
-
self.original = original_layer
|
15 |
self.masking = masking
|
16 |
|
17 |
-
|
18 |
-
self.
|
19 |
-
self.
|
20 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
self.layer_idx = original_layer.layer_idx
|
27 |
-
self.scaling = original_layer.scaling
|
28 |
|
29 |
-
|
30 |
-
bsz, seq_len, _ = hidden_states.size()
|
31 |
|
32 |
-
query_states = self._split_heads(self.q_proj(hidden_states))
|
33 |
-
key_states = self._split_heads(self.k_proj(hidden_states))
|
34 |
-
value_states = self._split_heads(self.v_proj(hidden_states))
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
cos, sin = position_embeddings
|
37 |
-
query_states, key_states = self.
|
38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
if self.masking == 'bidirectional':
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
attn_weights = F.softmax(attn_weights, dim=-1)
|
47 |
-
attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
48 |
|
49 |
-
attn_output
|
50 |
-
attn_output = self._merge_heads(attn_output)
|
51 |
-
return self.o_proj(attn_output), attn_weights
|
52 |
|
53 |
-
def _split_heads(self, x):
|
54 |
-
return x.view(x.size(0), x.size(1), self.num_heads, self.head_dim).transpose(1, 2)
|
55 |
|
56 |
-
def
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
k_rot = (k * cos) + (self._rotate_half(k) * sin)
|
64 |
-
return q_rot, k_rot
|
65 |
-
|
66 |
-
def _rotate_half(self, x):
|
67 |
-
x1 = x[..., : x.shape[-1] // 2]
|
68 |
-
x2 = x[..., x.shape[-1] // 2 :]
|
69 |
-
return torch.cat((-x2, x1), dim=-1)
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
class CustomTransformerConfig(PretrainedConfig):
|
73 |
def __init__(self, vocab_size=128256, hidden_size=4096, num_layers=32, num_heads=32, prediction_chunk=256, dropout=0, max_position_embeddings=4096, **kwargs):
|
@@ -79,7 +178,7 @@ class CustomTransformerConfig(PretrainedConfig):
|
|
79 |
self.dropout = dropout
|
80 |
self.prediction_chunk = prediction_chunk
|
81 |
self.max_position_embeddings = max_position_embeddings
|
82 |
-
|
83 |
|
84 |
class CustomTransformerModel(PreTrainedModel):
|
85 |
config_class = CustomTransformerConfig
|
@@ -87,12 +186,15 @@ class CustomTransformerModel(PreTrainedModel):
|
|
87 |
def __init__(self, config):
|
88 |
super().__init__(config)
|
89 |
|
90 |
-
|
|
|
|
|
91 |
self.llama.resize_token_embeddings(config.vocab_size)
|
92 |
|
93 |
for i, layer in enumerate(self.llama.model.layers):
|
94 |
layer.self_attn = BidirectionalLlamaAttention(layer.self_attn, masking='bidirectional')
|
95 |
|
|
|
96 |
for param in self.llama.parameters():
|
97 |
param.requires_grad = False
|
98 |
|
@@ -103,27 +205,40 @@ class CustomTransformerModel(PreTrainedModel):
|
|
103 |
r=256,
|
104 |
lora_alpha=256,
|
105 |
lora_dropout=0.0,
|
106 |
-
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
|
107 |
bias="none",
|
108 |
task_type=None
|
109 |
)
|
110 |
|
111 |
self.llama = get_peft_model(self.llama, lora_config)
|
|
|
112 |
self.llama = self.llama.to(torch.float16)
|
113 |
|
114 |
def forward(self, input_ids, labels=None, **kwargs):
|
115 |
batch_size, seq_length = input_ids.shape
|
116 |
-
assert seq_length == self.
|
|
|
|
|
|
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
logits = outputs.logits[
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
-
loss = None
|
123 |
if labels is not None:
|
124 |
-
|
|
|
|
|
|
|
|
|
125 |
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
126 |
|
|
|
127 |
return {"loss": loss, "logits": logits} if loss is not None else {"logits": logits}
|
128 |
|
129 |
|
|
|
|
|
1 |
import torch.nn as nn
|
2 |
+
from transformers import AutoModelForCausalLM, PreTrainedModel, PretrainedConfig
|
3 |
+
from transformers.models.llama.modeling_llama import LlamaAttention
|
4 |
from torch.amp import autocast
|
|
|
5 |
from peft import LoraConfig, get_peft_model
|
6 |
+
from typing import Optional, Tuple
|
7 |
+
import torch
|
8 |
import os
|
9 |
|
10 |
+
|
11 |
+
|
12 |
hf_token = os.getenv("HF_TOKEN")
|
13 |
|
14 |
+
class BidirectionalLlamaAttention(LlamaAttention):
|
15 |
+
def __init__(self, original_layer, masking = 'unidirectional'):
|
16 |
+
super().__init__(original_layer.config, layer_idx=original_layer.layer_idx)
|
|
|
17 |
self.masking = masking
|
18 |
|
19 |
+
# Copy weights from original layer
|
20 |
+
self.q_proj.weight = original_layer.q_proj.weight
|
21 |
+
self.k_proj.weight = original_layer.k_proj.weight
|
22 |
+
self.v_proj.weight = original_layer.v_proj.weight
|
23 |
+
self.o_proj.weight = original_layer.o_proj.weight
|
24 |
+
|
25 |
+
def repeat_kv(self, hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
26 |
+
"""
|
27 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
28 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
29 |
+
"""
|
30 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
31 |
+
if n_rep == 1:
|
32 |
+
return hidden_states
|
33 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
34 |
+
|
35 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
36 |
+
|
37 |
+
def eager_attention_forward(self,
|
38 |
+
module: nn.Module,
|
39 |
+
query: torch.Tensor,
|
40 |
+
key: torch.Tensor,
|
41 |
+
value: torch.Tensor,
|
42 |
+
attention_mask: Optional[torch.Tensor],
|
43 |
+
scaling: float,
|
44 |
+
dropout: float = 0.0,
|
45 |
+
**kwargs,
|
46 |
+
):
|
47 |
+
key_states = self.repeat_kv(key, module.num_key_value_groups)
|
48 |
+
value_states = self.repeat_kv(value, module.num_key_value_groups)
|
49 |
+
|
50 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
51 |
+
if attention_mask is not None:
|
52 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
53 |
+
attn_weights = attn_weights + causal_mask
|
54 |
+
|
55 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1).to(query.dtype)
|
56 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
57 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
58 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
59 |
+
|
60 |
+
return attn_output, attn_weights
|
61 |
|
62 |
+
def rotate_half(self, x):
|
63 |
+
"""Rotates half the hidden dims of the input."""
|
64 |
+
x1 = x[..., : x.shape[-1] // 2]
|
65 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
|
|
|
|
66 |
|
67 |
+
return torch.cat((-x2, x1), dim=-1)
|
|
|
68 |
|
|
|
|
|
|
|
69 |
|
70 |
+
def apply_rotary_pos_emb(self, q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
71 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
72 |
+
|
73 |
+
Args:
|
74 |
+
q (`torch.Tensor`): The query tensor.
|
75 |
+
k (`torch.Tensor`): The key tensor.
|
76 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
77 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
78 |
+
position_ids (`torch.Tensor`, *optional*):
|
79 |
+
Deprecated and unused.
|
80 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
81 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
82 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
83 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
84 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
85 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
86 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
87 |
+
Returns:
|
88 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
89 |
+
"""
|
90 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
91 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
92 |
+
q_embed = (q * cos) + (self.rotate_half(q) * sin)
|
93 |
+
k_embed = (k * cos) + (self.rotate_half(k) * sin)
|
94 |
+
|
95 |
+
return q_embed, k_embed
|
96 |
+
|
97 |
+
def forward(
|
98 |
+
self,
|
99 |
+
hidden_states: torch.Tensor,
|
100 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
101 |
+
attention_mask: Optional[torch.Tensor],
|
102 |
+
past_key_value: Optional[torch.Tensor] = None,
|
103 |
+
cache_position: Optional[torch.LongTensor] = None,
|
104 |
+
**kwargs,
|
105 |
+
):
|
106 |
+
input_shape = hidden_states.shape[:-1]
|
107 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
108 |
+
|
109 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
110 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
111 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
112 |
+
|
113 |
+
# Apply rotary embeddings
|
114 |
cos, sin = position_embeddings
|
115 |
+
query_states, key_states = self.apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
116 |
|
117 |
+
if past_key_value is not None:
|
118 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
119 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
120 |
+
|
121 |
+
# 🔄 **Modify the Attention Mask**
|
122 |
+
seq_len = hidden_states.shape[1]
|
123 |
+
batch_size = hidden_states.shape[0]
|
124 |
if self.masking == 'bidirectional':
|
125 |
+
base_mask = torch.ones((seq_len, seq_len), device=hidden_states.device, dtype=torch.bool)
|
126 |
+
attn_mask = base_mask.unsqueeze(0).unsqueeze(1).expand(batch_size, 1, seq_len, seq_len).clone() # ✅ Copy for each batch
|
127 |
+
elif self.masking == 'bidirectional_masked':
|
128 |
+
base_mask = torch.ones((seq_len, seq_len), device=hidden_states.device, dtype=torch.bool)
|
129 |
+
base_mask[:, 1:].fill_diagonal_(False) # ✅ Apply diagonal masking only in 2D
|
130 |
+
attn_mask = base_mask.unsqueeze(0).unsqueeze(1).expand(batch_size, 1, seq_len, seq_len).clone() # ✅ Copy for each batch
|
131 |
+
else: # unidirectional
|
132 |
+
# 🚀 Standard autoregressive (causal) mask
|
133 |
+
attn_mask = torch.tril(torch.ones(seq_len, seq_len, device=hidden_states.device, dtype=torch.bool))
|
134 |
+
attn_mask = base_mask.unsqueeze(0).unsqueeze(1).expand(batch_size, 1, seq_len, seq_len).clone() # ✅ Copy for each batch
|
135 |
+
|
136 |
+
|
137 |
+
# Call the default attention function
|
138 |
+
attn_output, attn_weights = self.eager_attention_forward(
|
139 |
+
self,
|
140 |
+
query_states,
|
141 |
+
key_states,
|
142 |
+
value_states,
|
143 |
+
attn_mask, # ✅ Custom mask is applied here
|
144 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
145 |
+
scaling=self.scaling,
|
146 |
+
**kwargs,
|
147 |
+
)
|
148 |
|
149 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
150 |
+
attn_output = self.o_proj(attn_output)
|
|
|
|
|
151 |
|
152 |
+
return attn_output, attn_weights
|
|
|
|
|
153 |
|
|
|
|
|
154 |
|
155 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
156 |
+
"""
|
157 |
+
Splits hidden_size dim into attn_head_size and num_heads
|
158 |
+
"""
|
159 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
160 |
+
tensor = tensor.view(*new_shape)
|
161 |
+
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
|
163 |
+
def _merge_heads(self, tensor, num_heads, attn_head_size):
|
164 |
+
"""
|
165 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden_size
|
166 |
+
"""
|
167 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
168 |
+
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
|
169 |
+
return tensor.view(new_shape)
|
170 |
|
171 |
class CustomTransformerConfig(PretrainedConfig):
|
172 |
def __init__(self, vocab_size=128256, hidden_size=4096, num_layers=32, num_heads=32, prediction_chunk=256, dropout=0, max_position_embeddings=4096, **kwargs):
|
|
|
178 |
self.dropout = dropout
|
179 |
self.prediction_chunk = prediction_chunk
|
180 |
self.max_position_embeddings = max_position_embeddings
|
181 |
+
self.input_size = prediction_chunk
|
182 |
|
183 |
class CustomTransformerModel(PreTrainedModel):
|
184 |
config_class = CustomTransformerConfig
|
|
|
186 |
def __init__(self, config):
|
187 |
super().__init__(config)
|
188 |
|
189 |
+
# Load pre-trained Llama model (excluding its original lm_head)
|
190 |
+
self.llama = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-3B", torch_dtype=torch.float16, device_map="auto", token = hf_token)
|
191 |
+
|
192 |
self.llama.resize_token_embeddings(config.vocab_size)
|
193 |
|
194 |
for i, layer in enumerate(self.llama.model.layers):
|
195 |
layer.self_attn = BidirectionalLlamaAttention(layer.self_attn, masking='bidirectional')
|
196 |
|
197 |
+
# Freeze Llama to retain pre-trained knowledge
|
198 |
for param in self.llama.parameters():
|
199 |
param.requires_grad = False
|
200 |
|
|
|
205 |
r=256,
|
206 |
lora_alpha=256,
|
207 |
lora_dropout=0.0,
|
208 |
+
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], # Llama-3 uses these attention modules
|
209 |
bias="none",
|
210 |
task_type=None
|
211 |
)
|
212 |
|
213 |
self.llama = get_peft_model(self.llama, lora_config)
|
214 |
+
self.llama.print_trainable_parameters() # Print number of trainable parameters
|
215 |
self.llama = self.llama.to(torch.float16)
|
216 |
|
217 |
def forward(self, input_ids, labels=None, **kwargs):
|
218 |
batch_size, seq_length = input_ids.shape
|
219 |
+
assert seq_length == self.input_size, f"Expected input length input_size, got {seq_length}"
|
220 |
+
|
221 |
+
with autocast("cuda", dtype=torch.float16): # ✅ Correct future-proof usage
|
222 |
+
|
223 |
|
224 |
+
outputs = self.llama(input_ids, output_hidden_states=True, **kwargs)
|
225 |
+
|
226 |
+
logits = outputs.logits[:,:,:self.config.vocab_size]
|
227 |
+
|
228 |
+
# Reshape logits to (batch, input_size, vocab_size)
|
229 |
+
logits = logits.view(batch_size, self.config.prediction_chunk, self.config.vocab_size)
|
230 |
+
|
231 |
+
loss = None
|
232 |
|
|
|
233 |
if labels is not None:
|
234 |
+
assert labels.shape == (batch_size, self.input_size), f"Labels shape mismatch: expected (batch, input_size), got {labels.shape}"
|
235 |
+
|
236 |
+
# Compute loss
|
237 |
+
loss_fct = torch.nn.CrossEntropyLoss()
|
238 |
+
|
239 |
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
240 |
|
241 |
+
|
242 |
return {"loss": loss, "logits": logits} if loss is not None else {"logits": logits}
|
243 |
|
244 |
|