ThingsAI commited on
Commit
8c9cdca
·
verified ·
1 Parent(s): 5d079d6

Upload modeling_quark.py

Browse files
Files changed (1) hide show
  1. modeling_quark.py +204 -0
modeling_quark.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Quark model implementation for HuggingFace Transformers.
3
+
4
+ Usage:
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer
6
+
7
+ model = AutoModelForCausalLM.from_pretrained("ThingAI/Quark-135m-v0.2", trust_remote_code=True)
8
+ tokenizer = AutoTokenizer.from_pretrained("ThingAI/Quark-135m-v0.2")
9
+
10
+ inputs = tokenizer("Ciao, come stai?", return_tensors="pt")
11
+ outputs = model.generate(**inputs, max_new_tokens=100, temperature=0.7, do_sample=True)
12
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
13
+ """
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from typing import Optional
19
+ from transformers import PreTrainedModel
20
+ from transformers.modeling_outputs import CausalLMOutputWithPast
21
+ from .configuration_quark import QuarkConfig
22
+
23
+
24
+ class QuarkRMSNorm(nn.Module):
25
+ def __init__(self, dim: int, eps: float = 1e-5):
26
+ super().__init__()
27
+ self.eps = eps
28
+ self.scale = nn.Parameter(torch.ones(dim))
29
+
30
+ def forward(self, x):
31
+ rms = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
32
+ return (x.float() * rms).to(x.dtype) * self.scale
33
+
34
+
35
+ class QuarkRotaryEmbedding(nn.Module):
36
+ def __init__(self, head_dim: int, max_seq_len: int, theta: float = 10000.0):
37
+ super().__init__()
38
+ assert head_dim % 2 == 0
39
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
40
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
41
+ self._build_cache(max_seq_len)
42
+
43
+ def _build_cache(self, seq_len: int):
44
+ t = torch.arange(seq_len, device=self.inv_freq.device).float()
45
+ freqs = torch.outer(t, self.inv_freq)
46
+ emb = torch.cat([freqs, freqs], dim=-1)
47
+ self.register_buffer("cos_cache", emb.cos()[None, None], persistent=False)
48
+ self.register_buffer("sin_cache", emb.sin()[None, None], persistent=False)
49
+ self._max_cached = seq_len
50
+
51
+ @staticmethod
52
+ def _rotate_half(x):
53
+ x1, x2 = x.chunk(2, dim=-1)
54
+ return torch.cat([-x2, x1], dim=-1)
55
+
56
+ def forward(self, q, k):
57
+ T = q.size(2)
58
+ if T > self._max_cached:
59
+ self._build_cache(T)
60
+ cos = self.cos_cache[:, :, :T, :]
61
+ sin = self.sin_cache[:, :, :T, :]
62
+ q = q * cos + self._rotate_half(q) * sin
63
+ k = k * cos + self._rotate_half(k) * sin
64
+ return q, k
65
+
66
+
67
+ class QuarkAttention(nn.Module):
68
+ """Grouped Query Attention (GQA)."""
69
+
70
+ def __init__(self, config: QuarkConfig):
71
+ super().__init__()
72
+ self.n_heads = config.n_heads
73
+ self.n_kv_heads = config.n_kv_heads
74
+ self.n_groups = config.n_heads // config.n_kv_heads
75
+ self.head_dim = config.head_dim
76
+
77
+ self.q_proj = nn.Linear(config.d_model, config.n_heads * config.head_dim, bias=config.qkv_bias)
78
+ self.k_proj = nn.Linear(config.d_model, config.n_kv_heads * config.head_dim, bias=config.qkv_bias)
79
+ self.v_proj = nn.Linear(config.d_model, config.n_kv_heads * config.head_dim, bias=config.qkv_bias)
80
+ self.o_proj = nn.Linear(config.n_heads * config.head_dim, config.d_model, bias=False)
81
+ self.rope = QuarkRotaryEmbedding(config.head_dim, config.max_seq_len, config.rope_theta)
82
+
83
+ def forward(self, x):
84
+ B, T, _ = x.shape
85
+ q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
86
+ k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
87
+ v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
88
+
89
+ q, k = self.rope(q, k)
90
+
91
+ if self.n_groups > 1:
92
+ k = k.repeat_interleave(self.n_groups, dim=1)
93
+ v = v.repeat_interleave(self.n_groups, dim=1)
94
+
95
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
96
+ out = out.transpose(1, 2).contiguous().view(B, T, self.n_heads * self.head_dim)
97
+ return self.o_proj(out)
98
+
99
+
100
+ class QuarkFFN(nn.Module):
101
+ """SwiGLU Feed-Forward Network."""
102
+
103
+ def __init__(self, config: QuarkConfig):
104
+ super().__init__()
105
+ self.gate_proj = nn.Linear(config.d_model, config.d_ff, bias=False)
106
+ self.up_proj = nn.Linear(config.d_model, config.d_ff, bias=False)
107
+ self.down_proj = nn.Linear(config.d_ff, config.d_model, bias=False)
108
+
109
+ def forward(self, x):
110
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
111
+
112
+
113
+ class QuarkBlock(nn.Module):
114
+ """Transformer block with pre-norm."""
115
+
116
+ def __init__(self, config: QuarkConfig):
117
+ super().__init__()
118
+ self.norm_attn = QuarkRMSNorm(config.d_model, config.rms_eps)
119
+ self.attn = QuarkAttention(config)
120
+ self.norm_ffn = QuarkRMSNorm(config.d_model, config.rms_eps)
121
+ self.ffn = QuarkFFN(config)
122
+
123
+ def forward(self, x):
124
+ x = x + self.attn(self.norm_attn(x))
125
+ x = x + self.ffn(self.norm_ffn(x))
126
+ return x
127
+
128
+
129
+ class QuarkPreTrainedModel(PreTrainedModel):
130
+ config_class = QuarkConfig
131
+ base_model_prefix = "model"
132
+ supports_gradient_checkpointing = False
133
+
134
+ def _init_weights(self, module):
135
+ std = 0.02
136
+ if isinstance(module, nn.Linear):
137
+ module.weight.data.normal_(mean=0.0, std=std)
138
+ if module.bias is not None:
139
+ module.bias.data.zero_()
140
+ elif isinstance(module, nn.Embedding):
141
+ module.weight.data.normal_(mean=0.0, std=std)
142
+
143
+
144
+ class QuarkForCausalLM(QuarkPreTrainedModel):
145
+ """Quark model for causal language modeling."""
146
+
147
+ def __init__(self, config: QuarkConfig):
148
+ super().__init__(config)
149
+ self.config = config
150
+
151
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
152
+ self.layers = nn.ModuleList([QuarkBlock(config) for _ in range(config.n_layers)])
153
+ self.norm = QuarkRMSNorm(config.d_model, config.rms_eps)
154
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
155
+
156
+ # Weight tying
157
+ self.lm_head.weight = self.embed_tokens.weight
158
+
159
+ self.post_init()
160
+
161
+ def get_input_embeddings(self):
162
+ return self.embed_tokens
163
+
164
+ def set_input_embeddings(self, value):
165
+ self.embed_tokens = value
166
+
167
+ def get_output_embeddings(self):
168
+ return self.lm_head
169
+
170
+ def set_output_embeddings(self, new_embeddings):
171
+ self.lm_head = new_embeddings
172
+
173
+ def forward(
174
+ self,
175
+ input_ids: torch.LongTensor,
176
+ attention_mask: Optional[torch.Tensor] = None,
177
+ labels: Optional[torch.LongTensor] = None,
178
+ **kwargs,
179
+ ) -> CausalLMOutputWithPast:
180
+ h = self.embed_tokens(input_ids)
181
+
182
+ for layer in self.layers:
183
+ h = layer(h)
184
+
185
+ h = self.norm(h)
186
+ logits = self.lm_head(h)
187
+
188
+ loss = None
189
+ if labels is not None:
190
+ shift_logits = logits[..., :-1, :].contiguous()
191
+ shift_labels = labels[..., 1:].contiguous()
192
+ loss = F.cross_entropy(
193
+ shift_logits.view(-1, self.config.vocab_size),
194
+ shift_labels.view(-1),
195
+ ignore_index=-100,
196
+ )
197
+
198
+ return CausalLMOutputWithPast(
199
+ loss=loss,
200
+ logits=logits,
201
+ )
202
+
203
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
204
+ return {"input_ids": input_ids}