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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SID-GPT v2 - LLaMA-style transformer for SID register prediction.
|
| 3 |
+
|
| 4 |
+
258-token vocabulary (0-255 byte values, 256=SEP, 257=FRAME).
|
| 5 |
+
Predicts next SID register token given sequence of previous tokens.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Optional, Tuple
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class ModelConfig:
|
| 19 |
+
n_embd: int = 512
|
| 20 |
+
n_layer: int = 8
|
| 21 |
+
n_head: int = 8
|
| 22 |
+
n_kv_head: int = 2
|
| 23 |
+
intermediate_size: int = 1408
|
| 24 |
+
block_size: int = 4096
|
| 25 |
+
vocab_size: int = 258
|
| 26 |
+
rope_theta: float = 10000.0
|
| 27 |
+
bias: bool = False
|
| 28 |
+
dropout: float = 0.0
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def small() -> "ModelConfig":
|
| 32 |
+
return ModelConfig(
|
| 33 |
+
n_embd=512,
|
| 34 |
+
n_layer=8,
|
| 35 |
+
n_head=8,
|
| 36 |
+
n_kv_head=2,
|
| 37 |
+
intermediate_size=1408,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def large() -> "ModelConfig":
|
| 42 |
+
return ModelConfig(
|
| 43 |
+
n_embd=1024,
|
| 44 |
+
n_layer=24,
|
| 45 |
+
n_head=16,
|
| 46 |
+
n_kv_head=4,
|
| 47 |
+
intermediate_size=2816,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class RMSNorm(nn.Module):
|
| 52 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.eps = eps
|
| 55 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 56 |
+
|
| 57 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 58 |
+
# Norm in float32 for stability
|
| 59 |
+
norm_x = x.float()
|
| 60 |
+
norm_x = norm_x * torch.rsqrt(
|
| 61 |
+
norm_x.pow(2).mean(-1, keepdim=True) + self.eps
|
| 62 |
+
)
|
| 63 |
+
return (norm_x * self.weight).to(x.dtype)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def precompute_rope_freqs(
|
| 67 |
+
dim: int,
|
| 68 |
+
max_seq_len: int,
|
| 69 |
+
theta: float = 10000.0,
|
| 70 |
+
device: Optional[torch.device] = None,
|
| 71 |
+
) -> torch.Tensor:
|
| 72 |
+
"""
|
| 73 |
+
Precompute complex-valued RoPE frequency table.
|
| 74 |
+
|
| 75 |
+
For each position p and frequency index i:
|
| 76 |
+
freq_i = 1 / (theta^(2i/dim))
|
| 77 |
+
rope[p, i] = exp(j * p * freq_i)
|
| 78 |
+
|
| 79 |
+
Returns complex tensor of shape (max_seq_len, dim//2).
|
| 80 |
+
"""
|
| 81 |
+
freqs = 1.0 / (
|
| 82 |
+
theta
|
| 83 |
+
** (torch.arange(0, dim, 2, device=device).float() / dim)
|
| 84 |
+
)
|
| 85 |
+
t = torch.arange(max_seq_len, device=device).float()
|
| 86 |
+
freqs = torch.outer(t, freqs)
|
| 87 |
+
return torch.polar(torch.ones_like(freqs), freqs)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def apply_rope(
|
| 91 |
+
xq: torch.Tensor,
|
| 92 |
+
xk: torch.Tensor,
|
| 93 |
+
freqs: torch.Tensor,
|
| 94 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 95 |
+
"""
|
| 96 |
+
Apply rotary embeddings to Q and K via complex multiplication.
|
| 97 |
+
|
| 98 |
+
Reshapes last dim of Q/K into pairs -> complex,
|
| 99 |
+
multiplies by precomputed freqs, converts back to real.
|
| 100 |
+
"""
|
| 101 |
+
xq_c = torch.view_as_complex(
|
| 102 |
+
xq.float().reshape(*xq.shape[:-1], -1, 2)
|
| 103 |
+
)
|
| 104 |
+
xk_c = torch.view_as_complex(
|
| 105 |
+
xk.float().reshape(*xk.shape[:-1], -1, 2)
|
| 106 |
+
)
|
| 107 |
+
# xq_c/xk_c: (B, heads, T, head_dim//2)
|
| 108 |
+
# freqs: (T, head_dim//2) -> (1, 1, T, head_dim//2)
|
| 109 |
+
freqs = freqs.unsqueeze(0).unsqueeze(1)
|
| 110 |
+
xq_out = torch.view_as_real(xq_c * freqs).flatten(-2)
|
| 111 |
+
xk_out = torch.view_as_real(xk_c * freqs).flatten(-2)
|
| 112 |
+
return xq_out.to(xq.dtype), xk_out.to(xk.dtype)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class GQAAttention(nn.Module):
|
| 116 |
+
"""
|
| 117 |
+
Grouped-Query Attention: fewer KV heads than Q heads.
|
| 118 |
+
Group size = n_head / n_kv_head. KV heads are expanded
|
| 119 |
+
via repeat_interleave to match Q head count.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
def __init__(self, config: ModelConfig):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.n_head = config.n_head
|
| 125 |
+
self.n_kv_head = config.n_kv_head
|
| 126 |
+
self.head_dim = config.n_embd // config.n_head
|
| 127 |
+
self.n_rep = config.n_head // config.n_kv_head
|
| 128 |
+
self.block_size = config.block_size
|
| 129 |
+
|
| 130 |
+
self.q_proj = nn.Linear(
|
| 131 |
+
config.n_embd,
|
| 132 |
+
config.n_head * self.head_dim,
|
| 133 |
+
bias=config.bias,
|
| 134 |
+
)
|
| 135 |
+
self.k_proj = nn.Linear(
|
| 136 |
+
config.n_embd,
|
| 137 |
+
config.n_kv_head * self.head_dim,
|
| 138 |
+
bias=config.bias,
|
| 139 |
+
)
|
| 140 |
+
self.v_proj = nn.Linear(
|
| 141 |
+
config.n_embd,
|
| 142 |
+
config.n_kv_head * self.head_dim,
|
| 143 |
+
bias=config.bias,
|
| 144 |
+
)
|
| 145 |
+
self.o_proj = nn.Linear(
|
| 146 |
+
config.n_embd,
|
| 147 |
+
config.n_embd,
|
| 148 |
+
bias=config.bias,
|
| 149 |
+
)
|
| 150 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 151 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 152 |
+
|
| 153 |
+
# KV cache buffers (populated during inference)
|
| 154 |
+
self.cache_k: Optional[torch.Tensor] = None
|
| 155 |
+
self.cache_v: Optional[torch.Tensor] = None
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self,
|
| 159 |
+
x: torch.Tensor,
|
| 160 |
+
freqs: torch.Tensor,
|
| 161 |
+
start_pos: Optional[int] = None,
|
| 162 |
+
) -> torch.Tensor:
|
| 163 |
+
B, T, _ = x.shape
|
| 164 |
+
|
| 165 |
+
q = self.q_proj(x)
|
| 166 |
+
k = self.k_proj(x)
|
| 167 |
+
v = self.v_proj(x)
|
| 168 |
+
|
| 169 |
+
q = q.view(B, T, self.n_head, self.head_dim)
|
| 170 |
+
k = k.view(B, T, self.n_kv_head, self.head_dim)
|
| 171 |
+
v = v.view(B, T, self.n_kv_head, self.head_dim)
|
| 172 |
+
|
| 173 |
+
# Transpose to (B, heads, T, head_dim)
|
| 174 |
+
q = q.transpose(1, 2)
|
| 175 |
+
k = k.transpose(1, 2)
|
| 176 |
+
v = v.transpose(1, 2)
|
| 177 |
+
|
| 178 |
+
# Apply RoPE to Q and K
|
| 179 |
+
q, k = apply_rope(q, k, freqs)
|
| 180 |
+
|
| 181 |
+
if start_pos is not None:
|
| 182 |
+
# Inference with KV-cache
|
| 183 |
+
if self.cache_k is None or start_pos == 0:
|
| 184 |
+
self.cache_k = torch.zeros(
|
| 185 |
+
B, self.n_kv_head, self.block_size,
|
| 186 |
+
self.head_dim,
|
| 187 |
+
device=x.device, dtype=x.dtype,
|
| 188 |
+
)
|
| 189 |
+
self.cache_v = torch.zeros_like(self.cache_k)
|
| 190 |
+
|
| 191 |
+
end_pos = start_pos + T
|
| 192 |
+
self.cache_k[:, :, start_pos:end_pos, :] = k
|
| 193 |
+
self.cache_v[:, :, start_pos:end_pos, :] = v
|
| 194 |
+
|
| 195 |
+
k = self.cache_k[:, :, :end_pos, :]
|
| 196 |
+
v = self.cache_v[:, :, :end_pos, :]
|
| 197 |
+
|
| 198 |
+
# Expand KV heads to match Q heads
|
| 199 |
+
if self.n_rep > 1:
|
| 200 |
+
k = k.repeat_interleave(self.n_rep, dim=1)
|
| 201 |
+
v = v.repeat_interleave(self.n_rep, dim=1)
|
| 202 |
+
|
| 203 |
+
is_causal = start_pos is None or start_pos == 0
|
| 204 |
+
if start_pos is not None and start_pos > 0:
|
| 205 |
+
# Single-token decode: no causal mask needed
|
| 206 |
+
# (attending to all cached positions)
|
| 207 |
+
is_causal = False
|
| 208 |
+
|
| 209 |
+
y = F.scaled_dot_product_attention(
|
| 210 |
+
q, k, v,
|
| 211 |
+
dropout_p=(
|
| 212 |
+
self.attn_dropout.p if self.training else 0.0
|
| 213 |
+
),
|
| 214 |
+
is_causal=is_causal,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
y = y.transpose(1, 2).contiguous().view(B, T, -1)
|
| 218 |
+
return self.resid_dropout(self.o_proj(y))
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class SwiGLUFFN(nn.Module):
|
| 222 |
+
"""
|
| 223 |
+
SwiGLU feed-forward: down(silu(gate(x)) * up(x))
|
| 224 |
+
Three projections, no bias.
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
def __init__(self, config: ModelConfig):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.gate_proj = nn.Linear(
|
| 230 |
+
config.n_embd,
|
| 231 |
+
config.intermediate_size,
|
| 232 |
+
bias=config.bias,
|
| 233 |
+
)
|
| 234 |
+
self.up_proj = nn.Linear(
|
| 235 |
+
config.n_embd,
|
| 236 |
+
config.intermediate_size,
|
| 237 |
+
bias=config.bias,
|
| 238 |
+
)
|
| 239 |
+
self.down_proj = nn.Linear(
|
| 240 |
+
config.intermediate_size,
|
| 241 |
+
config.n_embd,
|
| 242 |
+
bias=config.bias,
|
| 243 |
+
)
|
| 244 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 245 |
+
|
| 246 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 247 |
+
return self.dropout(
|
| 248 |
+
self.down_proj(
|
| 249 |
+
F.silu(self.gate_proj(x)) * self.up_proj(x)
|
| 250 |
+
)
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class TransformerBlock(nn.Module):
|
| 255 |
+
"""Pre-norm residual: x + attn(norm(x)), h + ffn(norm(h))"""
|
| 256 |
+
|
| 257 |
+
def __init__(self, config: ModelConfig):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.attn_norm = RMSNorm(config.n_embd)
|
| 260 |
+
self.attn = GQAAttention(config)
|
| 261 |
+
self.ffn_norm = RMSNorm(config.n_embd)
|
| 262 |
+
self.ffn = SwiGLUFFN(config)
|
| 263 |
+
|
| 264 |
+
def forward(
|
| 265 |
+
self,
|
| 266 |
+
x: torch.Tensor,
|
| 267 |
+
freqs: torch.Tensor,
|
| 268 |
+
start_pos: Optional[int] = None,
|
| 269 |
+
) -> torch.Tensor:
|
| 270 |
+
h = x + self.attn(self.attn_norm(x), freqs, start_pos)
|
| 271 |
+
return h + self.ffn(self.ffn_norm(h))
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class Transformer(nn.Module):
|
| 275 |
+
def __init__(self, config: ModelConfig):
|
| 276 |
+
super().__init__()
|
| 277 |
+
self.config = config
|
| 278 |
+
|
| 279 |
+
self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
|
| 280 |
+
self.drop = nn.Dropout(config.dropout)
|
| 281 |
+
self.blocks = nn.ModuleList(
|
| 282 |
+
[TransformerBlock(config) for _ in range(config.n_layer)]
|
| 283 |
+
)
|
| 284 |
+
self.norm = RMSNorm(config.n_embd)
|
| 285 |
+
self.lm_head = nn.Linear(
|
| 286 |
+
config.n_embd, config.vocab_size, bias=False
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Weight tying
|
| 290 |
+
self.lm_head.weight = self.tok_emb.weight
|
| 291 |
+
|
| 292 |
+
# Precompute RoPE frequencies
|
| 293 |
+
head_dim = config.n_embd // config.n_head
|
| 294 |
+
self.register_buffer(
|
| 295 |
+
"rope_freqs",
|
| 296 |
+
precompute_rope_freqs(
|
| 297 |
+
head_dim, config.block_size, config.rope_theta
|
| 298 |
+
),
|
| 299 |
+
persistent=False,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
self.apply(self._init_weights)
|
| 303 |
+
# Scale residual projections
|
| 304 |
+
res_scale = 1.0 / math.sqrt(2 * config.n_layer)
|
| 305 |
+
for block in self.blocks:
|
| 306 |
+
block.attn.o_proj.weight.data *= res_scale
|
| 307 |
+
block.ffn.down_proj.weight.data *= res_scale
|
| 308 |
+
|
| 309 |
+
def _init_weights(self, module: nn.Module):
|
| 310 |
+
if isinstance(module, nn.Linear):
|
| 311 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 312 |
+
if module.bias is not None:
|
| 313 |
+
torch.nn.init.zeros_(module.bias)
|
| 314 |
+
elif isinstance(module, nn.Embedding):
|
| 315 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 316 |
+
|
| 317 |
+
def forward(
|
| 318 |
+
self,
|
| 319 |
+
idx: torch.Tensor,
|
| 320 |
+
targets: Optional[torch.Tensor] = None,
|
| 321 |
+
start_pos: Optional[int] = None,
|
| 322 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 323 |
+
B, T = idx.shape
|
| 324 |
+
assert T <= self.config.block_size, (
|
| 325 |
+
f"Sequence length {T} exceeds block_size "
|
| 326 |
+
f"{self.config.block_size}"
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
x = self.drop(self.tok_emb(idx))
|
| 330 |
+
|
| 331 |
+
if start_pos is not None:
|
| 332 |
+
freqs = self.rope_freqs[start_pos : start_pos + T]
|
| 333 |
+
else:
|
| 334 |
+
freqs = self.rope_freqs[:T]
|
| 335 |
+
|
| 336 |
+
for block in self.blocks:
|
| 337 |
+
x = block(x, freqs, start_pos)
|
| 338 |
+
|
| 339 |
+
x = self.norm(x)
|
| 340 |
+
logits = self.lm_head(x)
|
| 341 |
+
|
| 342 |
+
loss = None
|
| 343 |
+
if targets is not None:
|
| 344 |
+
loss = F.cross_entropy(
|
| 345 |
+
logits.view(-1, logits.size(-1)),
|
| 346 |
+
targets.view(-1),
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
return logits, loss
|
| 350 |
+
|
| 351 |
+
def count_params(self) -> int:
|
| 352 |
+
# Subtract lm_head since it's tied
|
| 353 |
+
n = sum(p.numel() for p in self.parameters())
|
| 354 |
+
n -= self.lm_head.weight.numel()
|
| 355 |
+
return n
|
sample.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SID-GPT v2 generation with KV-cache.
|
| 3 |
+
|
| 4 |
+
Generates SID register sequences token-by-token,
|
| 5 |
+
outputs uint16 LE binary playable by sidgpt-play.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
import struct
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
os.environ["TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL"] = "1"
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from model import ModelConfig, Transformer
|
| 19 |
+
|
| 20 |
+
TOKEN_SEP = 256
|
| 21 |
+
TOKEN_FRAME = 257
|
| 22 |
+
TOKENS_PER_FRAME = 26
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_checkpoint(path, device):
|
| 26 |
+
ckpt = torch.load(
|
| 27 |
+
path, map_location=device, weights_only=False
|
| 28 |
+
)
|
| 29 |
+
config = ckpt["config"]
|
| 30 |
+
model = Transformer(config).to(device)
|
| 31 |
+
model.load_state_dict(ckpt["model"])
|
| 32 |
+
model.eval()
|
| 33 |
+
return model, config
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_prompt(seed_file, num_seed_frames, device):
|
| 37 |
+
"""
|
| 38 |
+
Build prompt tensor. Unconditional = one SEP frame.
|
| 39 |
+
Style-seeded = SEP frame + N frames from a .bin file.
|
| 40 |
+
"""
|
| 41 |
+
prompt = [TOKEN_SEP] * TOKENS_PER_FRAME
|
| 42 |
+
|
| 43 |
+
if seed_file is not None:
|
| 44 |
+
raw = np.fromfile(seed_file, dtype=np.uint16)
|
| 45 |
+
tokens = raw.tolist()
|
| 46 |
+
|
| 47 |
+
# Find first data frame after initial SEP frames
|
| 48 |
+
pos = 0
|
| 49 |
+
while pos < len(tokens):
|
| 50 |
+
if tokens[pos] != TOKEN_SEP:
|
| 51 |
+
break
|
| 52 |
+
pos += 1
|
| 53 |
+
|
| 54 |
+
frames_added = 0
|
| 55 |
+
while pos < len(tokens) and frames_added < num_seed_frames:
|
| 56 |
+
if tokens[pos] == TOKEN_SEP:
|
| 57 |
+
pos += TOKENS_PER_FRAME
|
| 58 |
+
continue
|
| 59 |
+
if tokens[pos] == TOKEN_FRAME:
|
| 60 |
+
end = pos + TOKENS_PER_FRAME
|
| 61 |
+
if end <= len(tokens):
|
| 62 |
+
prompt.extend(tokens[pos:end])
|
| 63 |
+
frames_added += 1
|
| 64 |
+
pos = end
|
| 65 |
+
else:
|
| 66 |
+
pos += 1
|
| 67 |
+
|
| 68 |
+
print(f"[SEED] {frames_added} frames from {seed_file}")
|
| 69 |
+
|
| 70 |
+
return torch.tensor([prompt], dtype=torch.long, device=device)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _reset_kv_cache(model):
|
| 74 |
+
for block in model.blocks:
|
| 75 |
+
block.attn.cache_k = None
|
| 76 |
+
block.attn.cache_v = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _sample_token(next_logits, temperature, top_k):
|
| 80 |
+
"""Sample one token from logits with temp + top-k."""
|
| 81 |
+
if temperature <= 0:
|
| 82 |
+
return torch.argmax(next_logits, dim=-1, keepdim=True)
|
| 83 |
+
|
| 84 |
+
scaled = next_logits / temperature
|
| 85 |
+
if top_k > 0 and top_k < scaled.shape[-1]:
|
| 86 |
+
v, _ = torch.topk(scaled, top_k)
|
| 87 |
+
threshold = v[:, -1].unsqueeze(-1)
|
| 88 |
+
scaled = scaled.masked_fill(
|
| 89 |
+
scaled < threshold, float("-inf")
|
| 90 |
+
)
|
| 91 |
+
probs = torch.softmax(scaled, dim=-1)
|
| 92 |
+
return torch.multinomial(probs, num_samples=1)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def generate(
|
| 97 |
+
model,
|
| 98 |
+
prompt,
|
| 99 |
+
num_tokens,
|
| 100 |
+
temperature=1.0,
|
| 101 |
+
top_k=50,
|
| 102 |
+
device="cpu",
|
| 103 |
+
):
|
| 104 |
+
"""
|
| 105 |
+
Autoregressive generation with KV-cache and sliding
|
| 106 |
+
window. When the cache fills up (cur_pos == block_size),
|
| 107 |
+
keeps the last 75% of tokens (frame-aligned), resets
|
| 108 |
+
the cache, re-prefills, and continues. RoPE encodes
|
| 109 |
+
relative positions so resetting absolute pos is safe.
|
| 110 |
+
"""
|
| 111 |
+
block_size = model.config.block_size
|
| 112 |
+
keep_ratio = 0.75
|
| 113 |
+
keep_len = int(block_size * keep_ratio)
|
| 114 |
+
keep_len = (keep_len // TOKENS_PER_FRAME) * TOKENS_PER_FRAME
|
| 115 |
+
|
| 116 |
+
prompt_list = prompt[0].tolist()
|
| 117 |
+
all_tokens = list(prompt_list)
|
| 118 |
+
|
| 119 |
+
if len(prompt_list) > block_size:
|
| 120 |
+
print(
|
| 121 |
+
f"[WARN] Prompt ({len(prompt_list)}) exceeds "
|
| 122 |
+
f"block_size ({block_size}), truncating"
|
| 123 |
+
)
|
| 124 |
+
prompt_list = prompt_list[-block_size:]
|
| 125 |
+
all_tokens = list(prompt_list)
|
| 126 |
+
|
| 127 |
+
# Prefill
|
| 128 |
+
inp = torch.tensor(
|
| 129 |
+
[prompt_list], dtype=torch.long, device=device
|
| 130 |
+
)
|
| 131 |
+
logits, _ = model(inp, start_pos=0)
|
| 132 |
+
next_logits = logits[:, -1, :]
|
| 133 |
+
cur_pos = len(prompt_list)
|
| 134 |
+
slide_count = 0
|
| 135 |
+
|
| 136 |
+
generated = []
|
| 137 |
+
for i in range(num_tokens):
|
| 138 |
+
# Sliding window: reset cache when full
|
| 139 |
+
if cur_pos >= block_size:
|
| 140 |
+
slide_count += 1
|
| 141 |
+
window = all_tokens[-keep_len:]
|
| 142 |
+
_reset_kv_cache(model)
|
| 143 |
+
inp = torch.tensor(
|
| 144 |
+
[window], dtype=torch.long, device=device
|
| 145 |
+
)
|
| 146 |
+
logits, _ = model(inp, start_pos=0)
|
| 147 |
+
next_logits = logits[:, -1, :]
|
| 148 |
+
cur_pos = keep_len
|
| 149 |
+
print(
|
| 150 |
+
f"[SLIDE] #{slide_count} at token {i}, "
|
| 151 |
+
f"kept {keep_len} tokens, "
|
| 152 |
+
f"generated {len(generated)} so far"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
idx = _sample_token(next_logits, temperature, top_k)
|
| 156 |
+
tok = idx.item()
|
| 157 |
+
generated.append(tok)
|
| 158 |
+
all_tokens.append(tok)
|
| 159 |
+
|
| 160 |
+
# Decode step with KV-cache
|
| 161 |
+
logits, _ = model(idx, start_pos=cur_pos)
|
| 162 |
+
next_logits = logits[:, -1, :]
|
| 163 |
+
cur_pos += 1
|
| 164 |
+
|
| 165 |
+
return generated
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def write_output(tokens, output_path):
|
| 169 |
+
"""Write uint16 LE binary, directly playable by sidgpt-play."""
|
| 170 |
+
data = struct.pack(f"<{len(tokens)}H", *tokens)
|
| 171 |
+
if output_path == "-":
|
| 172 |
+
sys.stdout.buffer.write(data)
|
| 173 |
+
else:
|
| 174 |
+
with open(output_path, "wb") as f:
|
| 175 |
+
f.write(data)
|
| 176 |
+
print(f"[OUT] Wrote {len(tokens)} tokens to {output_path}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def main():
|
| 180 |
+
parser = argparse.ArgumentParser(
|
| 181 |
+
description="SID-GPT v2 generation"
|
| 182 |
+
)
|
| 183 |
+
parser.add_argument(
|
| 184 |
+
"--checkpoint", type=str, required=True,
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument("--num-frames", type=int, default=500)
|
| 187 |
+
parser.add_argument("--temperature", type=float, default=0.9)
|
| 188 |
+
parser.add_argument("--top-k", type=int, default=50)
|
| 189 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--output", type=str, default="generated.bin"
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument("--device", type=str, default="auto")
|
| 194 |
+
parser.add_argument("--seed-file", type=str, default=None)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--seed-frames", type=int, default=10,
|
| 197 |
+
help="Number of frames to use from seed file",
|
| 198 |
+
)
|
| 199 |
+
args = parser.parse_args()
|
| 200 |
+
|
| 201 |
+
if args.device == "auto":
|
| 202 |
+
if torch.cuda.is_available():
|
| 203 |
+
device = "cuda"
|
| 204 |
+
elif (
|
| 205 |
+
hasattr(torch.backends, "mps")
|
| 206 |
+
and torch.backends.mps.is_available()
|
| 207 |
+
):
|
| 208 |
+
device = "mps"
|
| 209 |
+
else:
|
| 210 |
+
device = "cpu"
|
| 211 |
+
else:
|
| 212 |
+
device = args.device
|
| 213 |
+
|
| 214 |
+
if args.seed is not None:
|
| 215 |
+
torch.manual_seed(args.seed)
|
| 216 |
+
|
| 217 |
+
print(f"[INIT] Device: {device}")
|
| 218 |
+
|
| 219 |
+
model, config = load_checkpoint(args.checkpoint, device)
|
| 220 |
+
print(
|
| 221 |
+
f"[MODEL] {config.n_layer}L/{config.n_head}H/"
|
| 222 |
+
f"{config.n_embd}D, "
|
| 223 |
+
f"{model.count_params():,} params"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
prompt = build_prompt(args.seed_file, args.seed_frames, device)
|
| 227 |
+
prompt_tokens = prompt.shape[1]
|
| 228 |
+
num_tokens = args.num_frames * TOKENS_PER_FRAME
|
| 229 |
+
print(
|
| 230 |
+
f"[GEN] Prompt: {prompt_tokens} tokens, "
|
| 231 |
+
f"generating {num_tokens} tokens "
|
| 232 |
+
f"({args.num_frames} frames)"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
generated = generate(
|
| 236 |
+
model,
|
| 237 |
+
prompt,
|
| 238 |
+
num_tokens,
|
| 239 |
+
temperature=args.temperature,
|
| 240 |
+
top_k=args.top_k,
|
| 241 |
+
device=device,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
all_tokens = prompt[0].tolist() + generated
|
| 245 |
+
write_output(all_tokens, args.output)
|
| 246 |
+
|
| 247 |
+
# Stats
|
| 248 |
+
n_sep = sum(1 for t in all_tokens if t == TOKEN_SEP)
|
| 249 |
+
n_frame = sum(1 for t in all_tokens if t == TOKEN_FRAME)
|
| 250 |
+
n_data = sum(1 for t in all_tokens if t < 256)
|
| 251 |
+
print(
|
| 252 |
+
f"[STATS] Total: {len(all_tokens)} tokens "
|
| 253 |
+
f"(SEP={n_sep}, FRAME={n_frame}, data={n_data})"
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
main()
|
train.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SID-GPT v2 training script.
|
| 3 |
+
|
| 4 |
+
nanoGPT-style training loop with frame-aligned batch sampling,
|
| 5 |
+
cosine LR schedule, gradient accumulation, and AMP support.
|
| 6 |
+
Supports single-GPU and multi-GPU (DDP via torchrun).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import struct
|
| 13 |
+
import time
|
| 14 |
+
from contextlib import nullcontext
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.distributed as dist
|
| 19 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 20 |
+
|
| 21 |
+
from model import ModelConfig, Transformer
|
| 22 |
+
|
| 23 |
+
TOKEN_SEP = 256
|
| 24 |
+
TOKEN_FRAME = 257
|
| 25 |
+
TOKENS_PER_FRAME = 26
|
| 26 |
+
BYTES_PER_FRAME = 25
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def setup_ddp():
|
| 30 |
+
"""
|
| 31 |
+
Auto-detect DDP: torchrun sets RANK/LOCAL_RANK env vars.
|
| 32 |
+
Returns (rank, local_rank, world_size, is_ddp).
|
| 33 |
+
Without torchrun, returns (0, 0, 1, False).
|
| 34 |
+
"""
|
| 35 |
+
if "RANK" not in os.environ:
|
| 36 |
+
return 0, 0, 1, False
|
| 37 |
+
rank = int(os.environ["RANK"])
|
| 38 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 39 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 40 |
+
torch.cuda.set_device(local_rank)
|
| 41 |
+
dist.init_process_group(backend="nccl")
|
| 42 |
+
return rank, local_rank, world_size, True
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_device(requested: str) -> str:
|
| 46 |
+
if requested != "auto":
|
| 47 |
+
return requested
|
| 48 |
+
if torch.cuda.is_available():
|
| 49 |
+
return "cuda"
|
| 50 |
+
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 51 |
+
return "mps"
|
| 52 |
+
return "cpu"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_dtype(requested: str, device: str) -> torch.dtype:
|
| 56 |
+
if requested == "bfloat16":
|
| 57 |
+
if device == "cuda" and torch.cuda.is_bf16_supported():
|
| 58 |
+
return torch.bfloat16
|
| 59 |
+
print("[WARN] bfloat16 not supported, falling back to float16")
|
| 60 |
+
return torch.float16
|
| 61 |
+
if requested == "float16":
|
| 62 |
+
return torch.float16
|
| 63 |
+
return torch.float32
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_data(path: str, device: str) -> torch.Tensor:
|
| 67 |
+
raw = np.fromfile(path, dtype=np.uint16)
|
| 68 |
+
print(f"[DATA] Loaded {len(raw)} tokens from {path}")
|
| 69 |
+
return torch.from_numpy(raw.astype(np.int64)).to(device)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def generate_synth_data(device: str) -> torch.Tensor:
|
| 73 |
+
"""
|
| 74 |
+
Generate synthetic training data: ~20 short songs with
|
| 75 |
+
deterministic patterns (ascending frequencies, simple ADSR)
|
| 76 |
+
for end-to-end pipeline testing without HVSC data.
|
| 77 |
+
"""
|
| 78 |
+
tokens = []
|
| 79 |
+
rng = np.random.RandomState(42)
|
| 80 |
+
|
| 81 |
+
for song_idx in range(20):
|
| 82 |
+
# SEP frame
|
| 83 |
+
tokens.extend([TOKEN_SEP] * TOKENS_PER_FRAME)
|
| 84 |
+
|
| 85 |
+
num_frames = 80 + song_idx * 5
|
| 86 |
+
base_freq = 1000 + song_idx * 200
|
| 87 |
+
|
| 88 |
+
for f in range(num_frames):
|
| 89 |
+
tokens.append(TOKEN_FRAME)
|
| 90 |
+
regs = [0] * BYTES_PER_FRAME
|
| 91 |
+
|
| 92 |
+
# Voice 1: ascending frequency
|
| 93 |
+
freq = (base_freq + f * 50) & 0xFFFF
|
| 94 |
+
regs[0] = freq & 0xFF
|
| 95 |
+
regs[1] = (freq >> 8) & 0xFF
|
| 96 |
+
# Pulse width
|
| 97 |
+
regs[2] = 0x00
|
| 98 |
+
regs[3] = 0x08
|
| 99 |
+
# Control: gate on, triangle
|
| 100 |
+
regs[4] = 0x11 if f < num_frames - 5 else 0x10
|
| 101 |
+
# ADSR
|
| 102 |
+
regs[5] = 0x09
|
| 103 |
+
regs[6] = 0x00
|
| 104 |
+
|
| 105 |
+
# Voice 2: harmony (offset frequency)
|
| 106 |
+
freq2 = (base_freq + f * 37 + 500) & 0xFFFF
|
| 107 |
+
regs[7] = freq2 & 0xFF
|
| 108 |
+
regs[8] = (freq2 >> 8) & 0xFF
|
| 109 |
+
regs[9] = 0x00
|
| 110 |
+
regs[10] = 0x08
|
| 111 |
+
regs[11] = 0x21 if f % 16 < 12 else 0x20
|
| 112 |
+
regs[12] = 0x0A
|
| 113 |
+
regs[13] = 0x00
|
| 114 |
+
|
| 115 |
+
# Voice 3: bass (slow frequency)
|
| 116 |
+
freq3 = (base_freq // 2 + f * 10) & 0xFFFF
|
| 117 |
+
regs[14] = freq3 & 0xFF
|
| 118 |
+
regs[15] = (freq3 >> 8) & 0xFF
|
| 119 |
+
regs[16] = 0x00
|
| 120 |
+
regs[17] = 0x04
|
| 121 |
+
regs[18] = 0x41 if f % 32 < 24 else 0x40
|
| 122 |
+
regs[19] = 0x0C
|
| 123 |
+
regs[20] = 0x00
|
| 124 |
+
|
| 125 |
+
# Filter + volume
|
| 126 |
+
regs[21] = 0x00
|
| 127 |
+
regs[22] = rng.randint(0, 8)
|
| 128 |
+
regs[23] = 0x00
|
| 129 |
+
regs[24] = 0x0F
|
| 130 |
+
|
| 131 |
+
tokens.extend(regs)
|
| 132 |
+
|
| 133 |
+
data = np.array(tokens, dtype=np.uint16)
|
| 134 |
+
print(f"[SYNTH] Generated {len(data)} tokens ({20} songs)")
|
| 135 |
+
return torch.from_numpy(data.astype(np.int64)).to(device)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def split_data(data, block_size):
|
| 139 |
+
"""Split at frame-aligned boundary (multiple of 26)."""
|
| 140 |
+
n = len(data)
|
| 141 |
+
split_tok = int(n * 0.95)
|
| 142 |
+
# Align to frame boundary
|
| 143 |
+
split_tok = (split_tok // TOKENS_PER_FRAME) * TOKENS_PER_FRAME
|
| 144 |
+
return data[:split_tok], data[split_tok:]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_batch(data, block_size, batch_size, device):
|
| 148 |
+
"""
|
| 149 |
+
Frame-aligned batch sampling. Offsets are multiples of 26
|
| 150 |
+
so sequences always start on frame boundaries.
|
| 151 |
+
"""
|
| 152 |
+
max_start = (len(data) - block_size - 1) // TOKENS_PER_FRAME
|
| 153 |
+
if max_start < 1:
|
| 154 |
+
max_start = 1
|
| 155 |
+
offsets = torch.randint(max_start, (batch_size,)) * TOKENS_PER_FRAME
|
| 156 |
+
x = torch.stack([data[o : o + block_size] for o in offsets])
|
| 157 |
+
y = torch.stack(
|
| 158 |
+
[data[o + 1 : o + 1 + block_size] for o in offsets]
|
| 159 |
+
)
|
| 160 |
+
return x.to(device), y.to(device)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@torch.no_grad()
|
| 164 |
+
def estimate_loss(
|
| 165 |
+
model, train_data, val_data, config, args, device,
|
| 166 |
+
):
|
| 167 |
+
model.eval()
|
| 168 |
+
out = {}
|
| 169 |
+
for name, data in [("train", train_data), ("val", val_data)]:
|
| 170 |
+
losses = []
|
| 171 |
+
for _ in range(args.eval_iters):
|
| 172 |
+
x, y = get_batch(
|
| 173 |
+
data, config.block_size,
|
| 174 |
+
args.batch_size, device,
|
| 175 |
+
)
|
| 176 |
+
with torch.amp.autocast(
|
| 177 |
+
device_type=device.split(":")[0],
|
| 178 |
+
dtype=args.amp_dtype,
|
| 179 |
+
):
|
| 180 |
+
_, loss = model(x, y)
|
| 181 |
+
losses.append(loss.item())
|
| 182 |
+
out[name] = sum(losses) / len(losses)
|
| 183 |
+
model.train()
|
| 184 |
+
return out
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_lr(step, args):
|
| 188 |
+
"""
|
| 189 |
+
Cosine LR schedule with linear warmup.
|
| 190 |
+
Decays from lr to min_lr over max_steps.
|
| 191 |
+
"""
|
| 192 |
+
if step < args.warmup:
|
| 193 |
+
return args.lr * (step + 1) / args.warmup
|
| 194 |
+
if step >= args.max_steps:
|
| 195 |
+
return args.min_lr
|
| 196 |
+
progress = (step - args.warmup) / (args.max_steps - args.warmup)
|
| 197 |
+
coeff = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 198 |
+
return args.min_lr + coeff * (args.lr - args.min_lr)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def configure_optimizer(model, args, device):
|
| 202 |
+
# Separate params: decay 2D+ params, no decay for 1D (norms, biases)
|
| 203 |
+
decay_params = []
|
| 204 |
+
no_decay_params = []
|
| 205 |
+
for name, p in model.named_parameters():
|
| 206 |
+
if not p.requires_grad:
|
| 207 |
+
continue
|
| 208 |
+
if p.dim() >= 2:
|
| 209 |
+
decay_params.append(p)
|
| 210 |
+
else:
|
| 211 |
+
no_decay_params.append(p)
|
| 212 |
+
|
| 213 |
+
groups = [
|
| 214 |
+
{"params": decay_params, "weight_decay": args.weight_decay},
|
| 215 |
+
{"params": no_decay_params, "weight_decay": 0.0},
|
| 216 |
+
]
|
| 217 |
+
|
| 218 |
+
use_fused = device.startswith("cuda")
|
| 219 |
+
optimizer = torch.optim.AdamW(
|
| 220 |
+
groups,
|
| 221 |
+
lr=args.lr,
|
| 222 |
+
betas=(args.beta1, args.beta2),
|
| 223 |
+
fused=use_fused,
|
| 224 |
+
)
|
| 225 |
+
return optimizer
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def save_checkpoint(model, optimizer, config, step, path):
|
| 229 |
+
torch.save(
|
| 230 |
+
{
|
| 231 |
+
"model": model.state_dict(),
|
| 232 |
+
"optimizer": optimizer.state_dict(),
|
| 233 |
+
"config": config,
|
| 234 |
+
"step": step,
|
| 235 |
+
},
|
| 236 |
+
path,
|
| 237 |
+
)
|
| 238 |
+
print(f"[CKPT] Saved {path}")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def main():
|
| 242 |
+
parser = argparse.ArgumentParser(
|
| 243 |
+
description="SID-GPT v2 training"
|
| 244 |
+
)
|
| 245 |
+
parser.add_argument("--data", type=str, default=None)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--config", type=str, default="small",
|
| 248 |
+
choices=["small", "large"],
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 251 |
+
parser.add_argument("--grad-accum", type=int, default=4)
|
| 252 |
+
parser.add_argument("--max-steps", type=int, default=5000)
|
| 253 |
+
parser.add_argument("--lr", type=float, default=3e-4)
|
| 254 |
+
parser.add_argument("--min-lr", type=float, default=3e-5)
|
| 255 |
+
parser.add_argument("--warmup", type=int, default=200)
|
| 256 |
+
parser.add_argument("--weight-decay", type=float, default=0.1)
|
| 257 |
+
parser.add_argument("--beta1", type=float, default=0.9)
|
| 258 |
+
parser.add_argument("--beta2", type=float, default=0.95)
|
| 259 |
+
parser.add_argument("--eval-interval", type=int, default=250)
|
| 260 |
+
parser.add_argument("--eval-iters", type=int, default=50)
|
| 261 |
+
parser.add_argument("--log-interval", type=int, default=10)
|
| 262 |
+
parser.add_argument(
|
| 263 |
+
"--out-dir", type=str, default="training/checkpoints"
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument("--device", type=str, default="auto")
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
"--dtype", type=str, default="bfloat16",
|
| 268 |
+
choices=["bfloat16", "float16", "float32"],
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument("--compile", action="store_true")
|
| 271 |
+
parser.add_argument("--seed", type=int, default=1337)
|
| 272 |
+
parser.add_argument("--synth", action="store_true")
|
| 273 |
+
parser.add_argument("--resume", type=str, default=None)
|
| 274 |
+
args = parser.parse_args()
|
| 275 |
+
|
| 276 |
+
if not args.synth and args.data is None and args.resume is None:
|
| 277 |
+
parser.error("--data or --synth or --resume required")
|
| 278 |
+
|
| 279 |
+
# Enable experimental Flash Attention on ROCm
|
| 280 |
+
os.environ["TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL"] = "1"
|
| 281 |
+
|
| 282 |
+
# DDP setup (auto-detect torchrun)
|
| 283 |
+
rank, local_rank, world_size, is_ddp = setup_ddp()
|
| 284 |
+
is_master = rank == 0
|
| 285 |
+
|
| 286 |
+
if is_ddp:
|
| 287 |
+
device = f"cuda:{local_rank}"
|
| 288 |
+
device_type = "cuda"
|
| 289 |
+
else:
|
| 290 |
+
device = get_device(args.device)
|
| 291 |
+
device_type = device.split(":")[0]
|
| 292 |
+
|
| 293 |
+
torch.manual_seed(args.seed + rank)
|
| 294 |
+
args.amp_dtype = get_dtype(args.dtype, device)
|
| 295 |
+
|
| 296 |
+
if is_master:
|
| 297 |
+
if is_ddp:
|
| 298 |
+
print(
|
| 299 |
+
f"[INIT] DDP: {world_size} GPUs, "
|
| 300 |
+
f"dtype: {args.amp_dtype}"
|
| 301 |
+
)
|
| 302 |
+
else:
|
| 303 |
+
print(
|
| 304 |
+
f"[INIT] Device: {device}, "
|
| 305 |
+
f"dtype: {args.amp_dtype}"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
# Model config
|
| 309 |
+
if args.config == "large":
|
| 310 |
+
config = ModelConfig.large()
|
| 311 |
+
else:
|
| 312 |
+
config = ModelConfig.small()
|
| 313 |
+
|
| 314 |
+
start_step = 0
|
| 315 |
+
|
| 316 |
+
if args.resume:
|
| 317 |
+
if is_master:
|
| 318 |
+
print(f"[RESUME] Loading checkpoint {args.resume}")
|
| 319 |
+
ckpt = torch.load(
|
| 320 |
+
args.resume, map_location=device,
|
| 321 |
+
weights_only=False,
|
| 322 |
+
)
|
| 323 |
+
config = ckpt["config"]
|
| 324 |
+
model = Transformer(config).to(device)
|
| 325 |
+
model.load_state_dict(ckpt["model"])
|
| 326 |
+
start_step = ckpt["step"]
|
| 327 |
+
if is_master:
|
| 328 |
+
print(f"[RESUME] Resuming from step {start_step}")
|
| 329 |
+
else:
|
| 330 |
+
model = Transformer(config).to(device)
|
| 331 |
+
|
| 332 |
+
if is_master:
|
| 333 |
+
print(
|
| 334 |
+
f"[MODEL] {args.config}: "
|
| 335 |
+
f"{model.count_params():,} params, "
|
| 336 |
+
f"{config.n_layer}L/{config.n_head}H/"
|
| 337 |
+
f"{config.n_embd}D"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
if args.compile and device_type == "cuda":
|
| 341 |
+
if is_master:
|
| 342 |
+
print("[COMPILE] torch.compile enabled")
|
| 343 |
+
model = torch.compile(model)
|
| 344 |
+
|
| 345 |
+
# Wrap in DDP after compile
|
| 346 |
+
if is_ddp:
|
| 347 |
+
model = DDP(model, device_ids=[local_rank])
|
| 348 |
+
raw_model = model.module if is_ddp else model
|
| 349 |
+
|
| 350 |
+
# Data
|
| 351 |
+
if args.synth:
|
| 352 |
+
data = generate_synth_data(device)
|
| 353 |
+
else:
|
| 354 |
+
data = load_data(args.data, device)
|
| 355 |
+
|
| 356 |
+
train_data, val_data = split_data(data, config.block_size)
|
| 357 |
+
if is_master:
|
| 358 |
+
print(
|
| 359 |
+
f"[DATA] Train: {len(train_data):,} tokens, "
|
| 360 |
+
f"Val: {len(val_data):,} tokens"
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
# Optimizer (on raw model params)
|
| 364 |
+
optimizer = configure_optimizer(raw_model, args, device)
|
| 365 |
+
|
| 366 |
+
if args.resume and "optimizer" in ckpt:
|
| 367 |
+
optimizer.load_state_dict(ckpt["optimizer"])
|
| 368 |
+
|
| 369 |
+
# GradScaler only for float16
|
| 370 |
+
use_scaler = args.amp_dtype == torch.float16
|
| 371 |
+
scaler = torch.amp.GradScaler(enabled=use_scaler)
|
| 372 |
+
|
| 373 |
+
if is_master:
|
| 374 |
+
os.makedirs(args.out_dir, exist_ok=True)
|
| 375 |
+
|
| 376 |
+
# Training loop
|
| 377 |
+
model.train()
|
| 378 |
+
t0 = time.time()
|
| 379 |
+
|
| 380 |
+
for step in range(start_step, args.max_steps):
|
| 381 |
+
lr = get_lr(step, args)
|
| 382 |
+
for pg in optimizer.param_groups:
|
| 383 |
+
pg["lr"] = lr
|
| 384 |
+
|
| 385 |
+
# Eval (rank 0 only)
|
| 386 |
+
if (
|
| 387 |
+
step % args.eval_interval == 0
|
| 388 |
+
and step > 0
|
| 389 |
+
and is_master
|
| 390 |
+
):
|
| 391 |
+
losses = estimate_loss(
|
| 392 |
+
model, train_data, val_data,
|
| 393 |
+
config, args, device,
|
| 394 |
+
)
|
| 395 |
+
print(
|
| 396 |
+
f"[EVAL] step {step}: "
|
| 397 |
+
f"train={losses['train']:.4f}, "
|
| 398 |
+
f"val={losses['val']:.4f}"
|
| 399 |
+
)
|
| 400 |
+
save_checkpoint(
|
| 401 |
+
raw_model, optimizer, config, step,
|
| 402 |
+
os.path.join(
|
| 403 |
+
args.out_dir, f"ckpt_{step}.pt"
|
| 404 |
+
),
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# Gradient accumulation
|
| 408 |
+
optimizer.zero_grad(set_to_none=True)
|
| 409 |
+
accum_loss = 0.0
|
| 410 |
+
|
| 411 |
+
for micro in range(args.grad_accum):
|
| 412 |
+
x, y = get_batch(
|
| 413 |
+
train_data, config.block_size,
|
| 414 |
+
args.batch_size, device,
|
| 415 |
+
)
|
| 416 |
+
with torch.amp.autocast(
|
| 417 |
+
device_type=device_type, dtype=args.amp_dtype
|
| 418 |
+
):
|
| 419 |
+
_, loss = model(x, y)
|
| 420 |
+
loss = loss / args.grad_accum
|
| 421 |
+
|
| 422 |
+
accum_loss += loss.item()
|
| 423 |
+
scaler.scale(loss).backward()
|
| 424 |
+
|
| 425 |
+
scaler.unscale_(optimizer)
|
| 426 |
+
torch.nn.utils.clip_grad_norm_(
|
| 427 |
+
model.parameters(), 1.0
|
| 428 |
+
)
|
| 429 |
+
scaler.step(optimizer)
|
| 430 |
+
scaler.update()
|
| 431 |
+
|
| 432 |
+
# Logging (rank 0 only)
|
| 433 |
+
if step % args.log_interval == 0 and is_master:
|
| 434 |
+
dt = time.time() - t0
|
| 435 |
+
t0 = time.time()
|
| 436 |
+
if dt > 0 and step > start_step:
|
| 437 |
+
ms_per_step = (
|
| 438 |
+
dt / args.log_interval * 1000
|
| 439 |
+
)
|
| 440 |
+
tps = (
|
| 441 |
+
args.batch_size * args.grad_accum
|
| 442 |
+
* config.block_size
|
| 443 |
+
* args.log_interval
|
| 444 |
+
* world_size / dt
|
| 445 |
+
)
|
| 446 |
+
else:
|
| 447 |
+
ms_per_step = 0
|
| 448 |
+
tps = 0
|
| 449 |
+
print(
|
| 450 |
+
f"[TRAIN] step {step:5d} | "
|
| 451 |
+
f"loss {accum_loss:.4f} | "
|
| 452 |
+
f"lr {lr:.2e} | "
|
| 453 |
+
f"{ms_per_step:.0f}ms/step | "
|
| 454 |
+
f"{dt:.2f}s/{args.log_interval}steps | "
|
| 455 |
+
f"{tps/1e6:.2f}M tok/s"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
# Final save (rank 0 only)
|
| 459 |
+
if is_master:
|
| 460 |
+
save_checkpoint(
|
| 461 |
+
raw_model, optimizer, config, args.max_steps,
|
| 462 |
+
os.path.join(
|
| 463 |
+
args.out_dir, f"ckpt_{args.max_steps}.pt"
|
| 464 |
+
),
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
losses = estimate_loss(
|
| 468 |
+
model, train_data, val_data,
|
| 469 |
+
config, args, device,
|
| 470 |
+
)
|
| 471 |
+
print(
|
| 472 |
+
f"[DONE] Final: train={losses['train']:.4f}, "
|
| 473 |
+
f"val={losses['val']:.4f}"
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
if is_ddp:
|
| 477 |
+
dist.destroy_process_group()
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
if __name__ == "__main__":
|
| 481 |
+
main()
|