ThingsAI commited on
Commit
68f0523
·
verified ·
1 Parent(s): bb32337

Upload 7 files

Browse files
Files changed (3) hide show
  1. config.json +10 -15
  2. configuration_quark.py +37 -0
  3. modelling_quark.py +204 -0
config.json CHANGED
@@ -1,8 +1,10 @@
1
  {
2
  "model_type": "quark",
3
- "architectures": [
4
- "QuarkForCausalLM"
5
- ],
 
 
6
  "vocab_size": 65537,
7
  "d_model": 576,
8
  "n_heads": 9,
@@ -12,22 +14,15 @@
12
  "head_dim": 64,
13
  "max_seq_len": 2048,
14
  "rope_theta": 10000.0,
15
- "rms_eps": 1e-05,
16
  "qkv_bias": true,
17
  "dropout": 0.0,
18
  "torch_dtype": "bfloat16",
19
  "sft_dataset": "MBZUAI/Bactrian-X (it+en)",
20
  "sft_steps": 4000,
21
- "sft_loss": 1.8805,
22
- "base_pretrain": "step_0030000 (15.7B tokens bilingual IT+EN)",
23
  "tokenizer": "ThingAI/QuarkTokenizer",
24
- "languages": [
25
- "it",
26
- "en"
27
- ],
28
- "special_tokens": [
29
- "<|user|>",
30
- "<|assistant|>",
31
- "<|end|>"
32
- ]
33
  }
 
1
  {
2
  "model_type": "quark",
3
+ "architectures": ["QuarkForCausalLM"],
4
+ "auto_map": {
5
+ "AutoConfig": "configuration_quark.QuarkConfig",
6
+ "AutoModelForCausalLM": "modeling_quark.QuarkForCausalLM"
7
+ },
8
  "vocab_size": 65537,
9
  "d_model": 576,
10
  "n_heads": 9,
 
14
  "head_dim": 64,
15
  "max_seq_len": 2048,
16
  "rope_theta": 10000.0,
17
+ "rms_eps": 1e-5,
18
  "qkv_bias": true,
19
  "dropout": 0.0,
20
  "torch_dtype": "bfloat16",
21
  "sft_dataset": "MBZUAI/Bactrian-X (it+en)",
22
  "sft_steps": 4000,
23
+ "sft_loss": 1.9,
24
+ "base_pretrain": "15.7B tokens bilingual IT+EN",
25
  "tokenizer": "ThingAI/QuarkTokenizer",
26
+ "languages": ["it", "en"],
27
+ "special_tokens": ["<|user|>", "<|assistant|>", "<|end|>"]
 
 
 
 
 
 
 
28
  }
configuration_quark.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quark model configuration for HuggingFace Transformers."""
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class QuarkConfig(PretrainedConfig):
7
+ model_type = "quark"
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=65537,
12
+ d_model=576,
13
+ n_heads=9,
14
+ n_kv_heads=3,
15
+ n_layers=30,
16
+ d_ff=1536,
17
+ head_dim=64,
18
+ max_seq_len=2048,
19
+ rope_theta=10000.0,
20
+ rms_eps=1e-5,
21
+ qkv_bias=True,
22
+ dropout=0.0,
23
+ **kwargs,
24
+ ):
25
+ self.vocab_size = vocab_size
26
+ self.d_model = d_model
27
+ self.n_heads = n_heads
28
+ self.n_kv_heads = n_kv_heads
29
+ self.n_layers = n_layers
30
+ self.d_ff = d_ff
31
+ self.head_dim = head_dim
32
+ self.max_seq_len = max_seq_len
33
+ self.rope_theta = rope_theta
34
+ self.rms_eps = rms_eps
35
+ self.qkv_bias = qkv_bias
36
+ self.dropout = dropout
37
+ super().__init__(**kwargs)
modelling_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, Tuple
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 = nn.Linear(config.d_model, config.n_heads * config.head_dim, bias=config.qkv_bias)
78
+ self.k = nn.Linear(config.d_model, config.n_kv_heads * config.head_dim, bias=config.qkv_bias)
79
+ self.v = nn.Linear(config.d_model, config.n_kv_heads * config.head_dim, bias=config.qkv_bias)
80
+ self.o = 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(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
86
+ k = self.k(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
87
+ v = self.v(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(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.g = nn.Linear(config.d_model, config.d_ff, bias=False)
106
+ self.u = nn.Linear(config.d_model, config.d_ff, bias=False)
107
+ self.d = nn.Linear(config.d_ff, config.d_model, bias=False)
108
+
109
+ def forward(self, x):
110
+ return self.d(F.silu(self.g(x)) * self.u(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.n1 = QuarkRMSNorm(config.d_model, config.rms_eps)
119
+ self.attn = QuarkAttention(config)
120
+ self.n2 = QuarkRMSNorm(config.d_model, config.rms_eps)
121
+ self.ffn = QuarkFFN(config)
122
+
123
+ def forward(self, x):
124
+ x = x + self.attn(self.n1(x))
125
+ x = x + self.ffn(self.n2(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}