ThingsAI commited on
Commit
5c0671e
·
verified ·
1 Parent(s): 3c77b79

fix: copia esatta architettura da train.py, RoPE senza cast dtype

Browse files
Files changed (1) hide show
  1. modeling_quark.py +31 -61
modeling_quark.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- Quark language model — compatibile con AutoModelForCausalLM HuggingFace.
3
  """
4
  import math
5
  import torch
@@ -7,7 +7,6 @@ import torch.nn as nn
7
  import torch.nn.functional as F
8
  from transformers import PreTrainedModel
9
  from transformers.modeling_outputs import CausalLMOutputWithPast
10
-
11
  from .configuration_quark import QuarkConfig
12
 
13
 
@@ -25,6 +24,7 @@ class RMSNorm(nn.Module):
25
  class RotaryEmbedding(nn.Module):
26
  def __init__(self, head_dim, max_seq_len, theta=10_000.0):
27
  super().__init__()
 
28
  inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
29
  self.register_buffer("inv_freq", inv_freq, persistent=False)
30
  self._build_cache(max_seq_len)
@@ -46,19 +46,21 @@ class RotaryEmbedding(nn.Module):
46
  T = q.size(2)
47
  if T > self._max:
48
  self._build_cache(T)
49
- cos = self.cos_cache[:, :, :T, :].to(dtype=q.dtype)
50
- sin = self.sin_cache[:, :, :T, :].to(dtype=q.dtype)
51
- return q * cos + self._rotate_half(q) * sin, k * cos + self._rotate_half(k) * sin
 
 
52
 
53
 
54
  class GroupedQueryAttention(nn.Module):
55
  def __init__(self, cfg):
56
  super().__init__()
 
57
  self.n_heads = cfg.n_heads
58
  self.n_kv_heads = cfg.n_kv_heads
59
  self.n_groups = cfg.n_heads // cfg.n_kv_heads
60
  self.head_dim = cfg.head_dim
61
-
62
  self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * cfg.head_dim, bias=cfg.qkv_bias)
63
  self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=cfg.qkv_bias)
64
  self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=cfg.qkv_bias)
@@ -75,10 +77,6 @@ class GroupedQueryAttention(nn.Module):
75
  if self.n_groups > 1:
76
  k = k.repeat_interleave(self.n_groups, dim=1)
77
  v = v.repeat_interleave(self.n_groups, dim=1)
78
- # Forza dtype uniforme prima di SDPA
79
- dtype = q.dtype
80
- k = k.to(dtype)
81
- v = v.to(dtype)
82
  out = F.scaled_dot_product_attention(
83
  q, k, v, attn_mask=None,
84
  dropout_p=self.drop if self.training else 0.0,
@@ -108,7 +106,7 @@ class TransformerBlock(nn.Module):
108
  self.ffn = SwiGLUFFN(cfg)
109
 
110
  def forward(self, x, **kwargs):
111
- x = x + self.attn(self.norm_attn(x), **kwargs)
112
  x = x + self.ffn(self.norm_ffn(x))
113
  return x
114
 
@@ -116,6 +114,7 @@ class TransformerBlock(nn.Module):
116
  class QuarkPreTrainedModel(PreTrainedModel):
117
  config_class = QuarkConfig
118
  base_model_prefix = "model"
 
119
  supports_gradient_checkpointing = False
120
 
121
  def _init_weights(self, module):
@@ -129,62 +128,38 @@ class QuarkPreTrainedModel(PreTrainedModel):
129
 
130
 
131
  class QuarkForCausalLM(QuarkPreTrainedModel):
132
- # lm_head è tied con embed_tokens — non è missing, è intenzionale
133
  _keys_to_ignore_on_load_missing = ["lm_head.weight"]
134
- """
135
- Quark autoregressive language model.
136
- Compatibile con AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True)
137
- """
138
- def __init__(self, config: QuarkConfig):
139
  super().__init__(config)
140
  self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
141
  self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
142
  self.norm = RMSNorm(config.d_model, config.rms_eps)
143
  self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
144
-
145
- if config.tie_word_embeddings:
146
- self.lm_head.weight = self.embed_tokens.weight
147
-
148
  self.post_init()
149
 
150
- def get_input_embeddings(self):
151
- return self.embed_tokens
152
-
153
- def set_input_embeddings(self, value):
154
- self.embed_tokens = value
155
-
156
- def get_output_embeddings(self):
157
- return self.lm_head
158
-
159
- def set_output_embeddings(self, value):
160
- self.lm_head = value
161
 
162
  def tie_weights(self, **kwargs):
163
- """HF chiama questo metodo dopo il caricamento dei pesi."""
164
- if self.config.tie_word_embeddings:
165
- self.lm_head.weight = self.embed_tokens.weight
166
-
167
- def forward(
168
- self,
169
- input_ids = None,
170
- attention_mask = None,
171
- labels = None,
172
- **kwargs,
173
- ):
174
  x = self.embed_tokens(input_ids)
175
  for layer in self.layers:
176
- x = layer(x, attention_mask=attention_mask)
177
  x = self.norm(x)
178
  logits = self.lm_head(x)
179
-
180
- loss = None
181
  if labels is not None:
182
  loss = F.cross_entropy(
183
- logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size),
184
  labels[:, 1:].contiguous().view(-1),
185
  ignore_index=-100,
186
  )
187
-
188
  return CausalLMOutputWithPast(loss=loss, logits=logits)
189
 
190
  @torch.no_grad()
@@ -194,27 +169,22 @@ class QuarkForCausalLM(QuarkPreTrainedModel):
194
  for _ in range(max_new_tokens):
195
  out = self(ctx[:, -self.config.max_seq_len:])
196
  logits = out.logits[0, -1, :].float()
197
- # Greedy se temperature=0 o logits degeneri
198
- if temperature <= 0 or torch.isnan(logits).any() or torch.isinf(logits).any():
199
  token = logits.argmax().view(1, 1)
200
  else:
201
- logits = logits / temperature
202
- # Stabilizza prima del softmax
203
- logits = logits - logits.max()
204
- probs = F.softmax(logits, dim=-1)
205
- probs = torch.clamp(probs, min=0.0)
206
- # Top-p nucleus
207
  sorted_p, sorted_i = torch.sort(probs, descending=True)
208
  cum_p = torch.cumsum(sorted_p, dim=-1)
209
- remove = (cum_p - sorted_p) > top_p
210
- sorted_p = sorted_p.clone()
211
- sorted_p[remove] = 0.0
212
- total = sorted_p.sum()
213
  if total <= 0:
214
  token = sorted_i[0].view(1, 1)
215
  else:
216
  sorted_p /= total
217
- token = sorted_i[torch.multinomial(sorted_p, 1)].unsqueeze(0).unsqueeze(0)
218
  ctx = torch.cat([ctx, token], dim=1)
219
  if eos_token_id is not None and token.item() == eos_token_id:
220
  break
 
1
  """
2
+ Quark language model — copia esatta dell'architettura di training.
3
  """
4
  import math
5
  import torch
 
7
  import torch.nn.functional as F
8
  from transformers import PreTrainedModel
9
  from transformers.modeling_outputs import CausalLMOutputWithPast
 
10
  from .configuration_quark import QuarkConfig
11
 
12
 
 
24
  class RotaryEmbedding(nn.Module):
25
  def __init__(self, head_dim, max_seq_len, theta=10_000.0):
26
  super().__init__()
27
+ assert head_dim % 2 == 0
28
  inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
29
  self.register_buffer("inv_freq", inv_freq, persistent=False)
30
  self._build_cache(max_seq_len)
 
46
  T = q.size(2)
47
  if T > self._max:
48
  self._build_cache(T)
49
+ cos = self.cos_cache[:, :, :T, :]
50
+ sin = self.sin_cache[:, :, :T, :]
51
+ q = q * cos + self._rotate_half(q) * sin
52
+ k = k * cos + self._rotate_half(k) * sin
53
+ return q, k
54
 
55
 
56
  class GroupedQueryAttention(nn.Module):
57
  def __init__(self, cfg):
58
  super().__init__()
59
+ assert cfg.n_heads % cfg.n_kv_heads == 0
60
  self.n_heads = cfg.n_heads
61
  self.n_kv_heads = cfg.n_kv_heads
62
  self.n_groups = cfg.n_heads // cfg.n_kv_heads
63
  self.head_dim = cfg.head_dim
 
64
  self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * cfg.head_dim, bias=cfg.qkv_bias)
65
  self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=cfg.qkv_bias)
66
  self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=cfg.qkv_bias)
 
77
  if self.n_groups > 1:
78
  k = k.repeat_interleave(self.n_groups, dim=1)
79
  v = v.repeat_interleave(self.n_groups, dim=1)
 
 
 
 
80
  out = F.scaled_dot_product_attention(
81
  q, k, v, attn_mask=None,
82
  dropout_p=self.drop if self.training else 0.0,
 
106
  self.ffn = SwiGLUFFN(cfg)
107
 
108
  def forward(self, x, **kwargs):
109
+ x = x + self.attn(self.norm_attn(x))
110
  x = x + self.ffn(self.norm_ffn(x))
111
  return x
112
 
 
114
  class QuarkPreTrainedModel(PreTrainedModel):
115
  config_class = QuarkConfig
116
  base_model_prefix = "model"
117
+ _keys_to_ignore_on_load_missing = ["lm_head.weight"]
118
  supports_gradient_checkpointing = False
119
 
120
  def _init_weights(self, module):
 
128
 
129
 
130
  class QuarkForCausalLM(QuarkPreTrainedModel):
 
131
  _keys_to_ignore_on_load_missing = ["lm_head.weight"]
132
+
133
+ def __init__(self, config):
 
 
 
134
  super().__init__(config)
135
  self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
136
  self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
137
  self.norm = RMSNorm(config.d_model, config.rms_eps)
138
  self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
139
+ self.lm_head.weight = self.embed_tokens.weight
 
 
 
140
  self.post_init()
141
 
142
+ def get_input_embeddings(self): return self.embed_tokens
143
+ def set_input_embeddings(self, v): self.embed_tokens = v
144
+ def get_output_embeddings(self): return self.lm_head
145
+ def set_output_embeddings(self, v): self.lm_head = v
 
 
 
 
 
 
 
146
 
147
  def tie_weights(self, **kwargs):
148
+ self.lm_head.weight = self.embed_tokens.weight
149
+
150
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
 
 
 
 
 
 
 
 
151
  x = self.embed_tokens(input_ids)
152
  for layer in self.layers:
153
+ x = layer(x)
154
  x = self.norm(x)
155
  logits = self.lm_head(x)
156
+ loss = None
 
157
  if labels is not None:
158
  loss = F.cross_entropy(
159
+ logits[:, :-1].contiguous().view(-1, self.config.vocab_size),
160
  labels[:, 1:].contiguous().view(-1),
161
  ignore_index=-100,
162
  )
 
163
  return CausalLMOutputWithPast(loss=loss, logits=logits)
164
 
165
  @torch.no_grad()
 
169
  for _ in range(max_new_tokens):
170
  out = self(ctx[:, -self.config.max_seq_len:])
171
  logits = out.logits[0, -1, :].float()
172
+ if temperature <= 0:
 
173
  token = logits.argmax().view(1, 1)
174
  else:
175
+ logits -= logits.max()
176
+ logits /= temperature
177
+ probs = F.softmax(logits, dim=-1)
 
 
 
178
  sorted_p, sorted_i = torch.sort(probs, descending=True)
179
  cum_p = torch.cumsum(sorted_p, dim=-1)
180
+ mask = (cum_p - sorted_p) > top_p
181
+ sorted_p[mask] = 0.0
182
+ total = sorted_p.sum()
 
183
  if total <= 0:
184
  token = sorted_i[0].view(1, 1)
185
  else:
186
  sorted_p /= total
187
+ token = sorted_i[torch.multinomial(sorted_p, 1)].view(1, 1)
188
  ctx = torch.cat([ctx, token], dim=1)
189
  if eos_token_id is not None and token.item() == eos_token_id:
190
  break