Text Generation
Transformers
Safetensors
English
Italian
quark
causal-lm
small-language-model
gqa
rope
swiglu
bash
code
custom_code
Instructions to use ThingAI/ARK-72M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ThingAI/ARK-72M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="ThingAI/ARK-72M", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("ThingAI/ARK-72M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use ThingAI/ARK-72M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "ThingAI/ARK-72M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ThingAI/ARK-72M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/ThingAI/ARK-72M
- SGLang
How to use ThingAI/ARK-72M with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "ThingAI/ARK-72M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ThingAI/ARK-72M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "ThingAI/ARK-72M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ThingAI/ARK-72M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use ThingAI/ARK-72M with Docker Model Runner:
docker model run hf.co/ThingAI/ARK-72M
fix: copia esatta architettura da train.py, RoPE senza cast dtype
Browse files- modeling_quark.py +31 -61
modeling_quark.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Quark language model —
|
| 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, :]
|
| 50 |
-
sin = self.sin_cache[:, :, :T, :]
|
| 51 |
-
|
|
|
|
|
|
|
| 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)
|
| 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 |
-
|
| 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 |
-
|
| 152 |
-
|
| 153 |
-
def
|
| 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 |
-
|
| 164 |
-
|
| 165 |
-
|
| 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
|
| 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
|
| 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 |
-
|
| 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
|
| 202 |
-
|
| 203 |
-
|
| 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 |
-
|
| 210 |
-
sorted_p =
|
| 211 |
-
|
| 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)].
|
| 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
|