JiRackPrecision_72b / JiRackPrecision_72b.py
kgrabko's picture
Update JiRackPrecision_72b.py
7f3a845 verified
Raw History Blame Contribute Delete
21.6 kB
# =============================================================================
# JiRack Precision 72B - model architecture (PyTorch)
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
# All rights reserved. Proprietary JiRack license, see LICENSE.
# 132 layers, hidden 5120, FFN 30720 (SwiGLU), 40 query / 8 key-value heads,
# head dim 128, vocabulary 152,064, RoPE theta 1e6, RMSNorm eps 1e-5.
# PATENT PENDING
# =============================================================================
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
VOCAB_SIZE = 152064
HIDDEN_SIZE = 5120
INTERMEDIATE_SIZE = 30720
NUM_LAYERS = 132
NUM_HEADS = 40
NUM_KV_HEADS = 8
HEAD_DIM = 128
MAX_SEQ_LEN = 16384
ROPE_THETA = 1000000.0
RMS_EPS = 1e-5
ROPE_SCALE_FACTOR = 1.0
INIT_STD = 0.02
ATTN_QKV_BIAS = True
def _detect_sdpa_gqa() -> bool:
try:
q = torch.zeros(1, 2, 1, 8)
kv = torch.zeros(1, 1, 1, 8)
F.scaled_dot_product_attention(q, kv, kv, enable_gqa=True)
return True
except TypeError:
return False
except Exception:
return False
_SDPA_HAS_GQA = _detect_sdpa_gqa()
class JiRackConfig:
def __init__(self):
self.vocab_size = VOCAB_SIZE
self.hidden_size = HIDDEN_SIZE
self.intermediate_size = INTERMEDIATE_SIZE
self.num_hidden_layers = NUM_LAYERS
self.num_attention_heads = NUM_HEADS
self.num_key_value_heads = NUM_KV_HEADS
self.head_dim = HEAD_DIM
self.max_seq_len = MAX_SEQ_LEN
self.rope_theta = ROPE_THETA
self.rms_norm_eps = RMS_EPS
self.rope_scale_factor = ROPE_SCALE_FACTOR
self.init_std = INIT_STD
self.attn_qkv_bias = ATTN_QKV_BIAS
def precompute_freqs_cis(
dim: int,
end: int,
theta: float = ROPE_THETA,
scale_factor: float = ROPE_SCALE_FACTOR,
):
""
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
if scale_factor > 1.0:
freqs = freqs / scale_factor
t = torch.arange(end, dtype=torch.float32)
freqs = torch.outer(t, freqs)
emb = torch.cat((freqs, freqs), dim=-1)
return torch.cos(emb), torch.sin(emb)
def rotate_half(x):
""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2:]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_emb(xq, xk, cos, sin):
""
cos = cos[None, None, :, :]
sin = sin[None, None, :, :]
xq_out = (xq * cos) + (rotate_half(xq) * sin)
xk_out = (xk * cos) + (rotate_half(xk) * sin)
return xq_out, xk_out
class BitLinear(nn.Linear):
""
def __init__(self, in_features, out_features, bias=False):
super().__init__(in_features, out_features, bias=bias)
self.eps = 1e-5
self.register_buffer("lambda_", torch.zeros(()), persistent=True)
self._lam_host = None
def _load_from_state_dict(self, *args, **kwargs):
self._lam_host = None
super()._load_from_state_dict(*args, **kwargs)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not self.training:
lam_host = self._lam_host if self._lam_host is not None else float(self.lambda_)
if lam_host < 1e-6:
return F.linear(x, self.weight, self.bias)
lam = self.lambda_.to(x.dtype)
w = self.weight
gamma = w.float().abs().mean().clamp(min=self.eps).to(w.dtype)
w_quant = torch.clamp(torch.round(w / gamma), -1.0, 1.0) * gamma
w_effective = w + lam * (w_quant - w).detach()
x_scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp(min=self.eps)
x_quant = torch.clamp(torch.round(x * x_scale), -128.0, 127.0) / x_scale
x_effective = x + lam * (x_quant - x).detach()
return F.linear(x_effective, w_effective, self.bias)
class RMSNorm(nn.Module):
def __init__(self, dim, eps=RMS_EPS):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
dtype = x.dtype
x = x.float()
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return (x * self.weight.float()).to(dtype)
class KVCache:
""
def __init__(self, num_layers, max_len, batch_size=1):
self.max_len = int(max_len)
self.batch_size = int(batch_size)
self.k = [None] * num_layers
self.v = [None] * num_layers
self.pos = 0
def update(self, layer_idx, k, v, start, end):
if end > self.max_len:
raise ValueError(f"KV cache full: need {end} positions, max_len={self.max_len}")
if k.shape[0] != self.batch_size:
raise ValueError(f"KV cache built for batch {self.batch_size}, got {k.shape[0]}")
if self.k[layer_idx] is None:
B, H, _, D = k.shape
self.k[layer_idx] = torch.empty(B, H, self.max_len, D, dtype=k.dtype, device=k.device)
self.v[layer_idx] = torch.empty_like(self.k[layer_idx])
self.k[layer_idx][:, :, start:end] = k
self.v[layer_idx][:, :, start:end] = v
return self.k[layer_idx][:, :, :end], self.v[layer_idx][:, :, :end]
def truncate(self, n):
""
if not 0 <= n <= self.pos:
raise ValueError(f"truncate({n}) outside 0..{self.pos}")
self.pos = n
def reset(self):
self.pos = 0
def nbytes(self):
return sum(t.numel() * t.element_size() for t in self.k + self.v if t is not None)
class TransformerBlock(nn.Module):
def __init__(self, config, use_checkpoint=False):
super().__init__()
self.use_checkpoint = use_checkpoint
self.n_heads = config.num_attention_heads
self.n_kv_heads = config.num_key_value_heads
self.head_dim = config.head_dim
self.n_rep = self.n_heads // self.n_kv_heads
self.norm1 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.norm2 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
qkv_bias = config.attn_qkv_bias
self.q_proj = BitLinear(config.hidden_size,
self.n_heads * self.head_dim, bias=qkv_bias)
self.k_proj = BitLinear(config.hidden_size,
self.n_kv_heads * self.head_dim, bias=qkv_bias)
self.v_proj = BitLinear(config.hidden_size,
self.n_kv_heads * self.head_dim, bias=qkv_bias)
self.out_proj = BitLinear(self.n_heads * self.head_dim,
config.hidden_size, bias=False)
self.ffn_w1 = BitLinear(config.hidden_size, config.intermediate_size, bias=False)
self.ffn_w3 = BitLinear(config.hidden_size, config.intermediate_size, bias=False)
self.ffn_w2 = BitLinear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x, freqs_cos, freqs_sin, kv_cache=None, layer_idx=None):
if kv_cache is not None:
return self._forward_impl(x, freqs_cos, freqs_sin, kv_cache, layer_idx)
if self.use_checkpoint and self.training:
return checkpoint(
self._forward_impl, x, freqs_cos, freqs_sin, use_reentrant=False
)
return self._forward_impl(x, freqs_cos, freqs_sin)
def _cached_attention(self, q, k, v, kv_cache, layer_idx):
""
T = q.shape[2]
start = kv_cache.pos
end = start + T
k_all, v_all = kv_cache.update(layer_idx, k, v, start, end)
if T == 1:
mask, causal = None, False
elif start == 0:
mask, causal = None, True
else:
mask = torch.ones(T, end, dtype=torch.bool, device=q.device).tril(diagonal=start)
causal = False
if self.n_rep > 1 and _SDPA_HAS_GQA:
return F.scaled_dot_product_attention(
q, k_all, v_all, attn_mask=mask, is_causal=causal, enable_gqa=True
)
if self.n_rep > 1:
k_all = k_all.repeat_interleave(self.n_rep, dim=1)
v_all = v_all.repeat_interleave(self.n_rep, dim=1)
return F.scaled_dot_product_attention(q, k_all, v_all, attn_mask=mask, is_causal=causal)
def _forward_impl(self, x, freqs_cos, freqs_sin, kv_cache=None, layer_idx=None):
h = self.norm1(x)
B, T, _ = h.shape
q = self.q_proj(h).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(h).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(h).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
q, k = apply_rotary_emb(q, k, freqs_cos, freqs_sin)
if kv_cache is not None:
attn_out = self._cached_attention(q, k, v, kv_cache, layer_idx)
elif self.n_rep > 1 and _SDPA_HAS_GQA:
attn_out = F.scaled_dot_product_attention(
q, k, v, is_causal=True, enable_gqa=True
)
else:
if self.n_rep > 1:
k = k.repeat_interleave(self.n_rep, dim=1)
v = v.repeat_interleave(self.n_rep, dim=1)
attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
attn_out = attn_out.transpose(1, 2).contiguous().view(B, T, -1)
x = x + self.out_proj(attn_out)
m = self.norm2(x)
gate = F.silu(self.ffn_w1(m))
up = self.ffn_w3(m)
x = x + self.ffn_w2(gate * up)
return x
class JiRackTransformer(nn.Module):
def __init__(self, config: JiRackConfig = None, use_checkpoint=False):
super().__init__()
self.config = config if config is not None else JiRackConfig()
self.use_checkpoint = use_checkpoint
self.token_emb = nn.Embedding(self.config.vocab_size, self.config.hidden_size)
self.blocks = nn.ModuleList([
TransformerBlock(self.config, self.use_checkpoint)
for _ in range(self.config.num_hidden_layers)
])
self.ln_f = RMSNorm(self.config.hidden_size, eps=self.config.rms_norm_eps)
self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=False)
cos, sin = precompute_freqs_cis(
dim=self.config.head_dim,
end=self.config.max_seq_len,
theta=self.config.rope_theta,
scale_factor=self.config.rope_scale_factor,
)
self.register_buffer("freqs_cos", cos, persistent=False)
self.register_buffer("freqs_sin", sin, persistent=False)
self._init_weights()
def _init_weights(self):
std = self.config.init_std
resid_std = std / math.sqrt(2 * self.config.num_hidden_layers)
nn.init.normal_(self.token_emb.weight, mean=0.0, std=std)
nn.init.normal_(self.lm_head.weight, mean=0.0, std=std)
for block in self.blocks:
for lin in (block.q_proj, block.k_proj, block.v_proj,
block.ffn_w1, block.ffn_w3):
nn.init.normal_(lin.weight, mean=0.0, std=std)
if lin.bias is not None:
nn.init.zeros_(lin.bias)
for lin in (block.out_proj, block.ffn_w2):
nn.init.normal_(lin.weight, mean=0.0, std=resid_std)
if lin.bias is not None:
nn.init.zeros_(lin.bias)
def set_lambda(self, lambda_value: float):
for module in self.modules():
if isinstance(module, BitLinear):
module.lambda_.fill_(lambda_value)
module._lam_host = float(lambda_value)
def get_lambda(self) -> float:
for module in self.modules():
if isinstance(module, BitLinear):
return float(module.lambda_)
return 0.0
def forward(self, input_ids, kv_cache=None, last_logits_only=False):
seq_len = input_ids.shape[1]
x = self.token_emb(input_ids)
start = 0 if kv_cache is None else kv_cache.pos
if start + seq_len > self.freqs_cos.shape[0]:
raise ValueError(f"positions {start}..{start + seq_len - 1} exceed "
f"max_seq_len={self.freqs_cos.shape[0]}")
cos = self.freqs_cos[start:start + seq_len].to(device=x.device, dtype=x.dtype)
sin = self.freqs_sin[start:start + seq_len].to(device=x.device, dtype=x.dtype)
if kv_cache is None:
for block in self.blocks:
x = block(x, cos, sin)
else:
for i, block in enumerate(self.blocks):
x = block(x, cos, sin, kv_cache, i)
kv_cache.pos = start + seq_len
if last_logits_only:
x = x[:, -1:, :]
return self.lm_head(self.ln_f(x))
def new_kv_cache(self, max_len=None, batch_size=1):
""
limit = self.freqs_cos.shape[0]
max_len = limit if max_len is None else min(int(max_len), limit)
return KVCache(self.config.num_hidden_layers, max_len, batch_size)
@torch.no_grad()
def load_hf_state_dict(self, hf_sd: dict, strict: bool = True):
mapped = {}
mapped["token_emb.weight"] = hf_sd["model.embed_tokens.weight"]
mapped["ln_f.weight"] = hf_sd["model.norm.weight"]
if "lm_head.weight" in hf_sd:
mapped["lm_head.weight"] = hf_sd["lm_head.weight"]
else:
mapped["lm_head.weight"] = hf_sd["model.embed_tokens.weight"]
for i in range(self.config.num_hidden_layers):
hf = f"model.layers.{i}"
jr = f"blocks.{i}"
mapped[f"{jr}.norm1.weight"] = hf_sd[f"{hf}.input_layernorm.weight"]
mapped[f"{jr}.norm2.weight"] = hf_sd[f"{hf}.post_attention_layernorm.weight"]
mapped[f"{jr}.q_proj.weight"] = hf_sd[f"{hf}.self_attn.q_proj.weight"]
mapped[f"{jr}.k_proj.weight"] = hf_sd[f"{hf}.self_attn.k_proj.weight"]
mapped[f"{jr}.v_proj.weight"] = hf_sd[f"{hf}.self_attn.v_proj.weight"]
mapped[f"{jr}.q_proj.bias"] = hf_sd[f"{hf}.self_attn.q_proj.bias"]
mapped[f"{jr}.k_proj.bias"] = hf_sd[f"{hf}.self_attn.k_proj.bias"]
mapped[f"{jr}.v_proj.bias"] = hf_sd[f"{hf}.self_attn.v_proj.bias"]
mapped[f"{jr}.out_proj.weight"] = hf_sd[f"{hf}.self_attn.o_proj.weight"]
mapped[f"{jr}.ffn_w1.weight"] = hf_sd[f"{hf}.mlp.gate_proj.weight"]
mapped[f"{jr}.ffn_w3.weight"] = hf_sd[f"{hf}.mlp.up_proj.weight"]
mapped[f"{jr}.ffn_w2.weight"] = hf_sd[f"{hf}.mlp.down_proj.weight"]
missing, unexpected = self.load_state_dict(mapped, strict=False)
real_missing = [k for k in missing if not k.endswith("lambda_")]
if strict:
assert not real_missing, f"missing from HF checkpoint: {real_missing}"
assert not unexpected, f"unexpected keys: {unexpected}"
print(f"✅ HF weights loaded: {len(mapped)} tensors "
f"({len(real_missing)} missing, {len(unexpected)} unexpected)")
return real_missing, unexpected
@torch.no_grad()
def export_ternary_state_dict(self):
out = {}
for name, module in self.named_modules():
if isinstance(module, BitLinear):
w = module.weight.float()
gamma = w.abs().mean().clamp(min=module.eps)
codes = torch.clamp(torch.round(w / gamma), -1.0, 1.0).to(torch.int8)
out[f"{name}.codes"] = codes
out[f"{name}.gamma"] = gamma
if module.bias is not None:
out[f"{name}.bias"] = module.bias.detach().clone()
out["token_emb.weight"] = self.token_emb.weight.detach().clone()
out["lm_head.weight"] = self.lm_head.weight.detach().clone()
out["ln_f.weight"] = self.ln_f.weight.detach().clone()
for name, module in self.named_modules():
if isinstance(module, RMSNorm) and name != "ln_f":
out[f"{name}.weight"] = module.weight.detach().clone()
return out
JiRackConfig = JiRackConfig
JiRackTransformer = JiRackTransformer
if __name__ == "__main__":
class TinyConfig(JiRackConfig):
def __init__(self):
super().__init__()
self.vocab_size = 256
self.hidden_size = 64
self.intermediate_size = 128
self.num_hidden_layers = 2
self.num_attention_heads = 4
self.num_key_value_heads = 2
self.head_dim = 16
self.max_seq_len = 64
torch.manual_seed(0)
model = JiRackTransformer(TinyConfig()).eval()
ids = torch.randint(0, 256, (2, 32))
with torch.no_grad():
model.set_lambda(0.0)
y0 = model(ids)
model.set_lambda(1e-4)
y_eps = model(ids)
model.set_lambda(1.0)
y1 = model(ids)
rel_jump = (y_eps - y0).norm() / y0.norm()
print(f"relative change at lambda=1e-4: {rel_jump.item():.2e} (must be ~1e-4)")
assert rel_jump < 1e-2, "lambda warmup is not continuous!"
ratio = y1.std() / y0.std()
print(f"std ratio lambda=1 vs lambda=0: {ratio.item():.3f} (must be O(1))")
assert 0.1 < ratio.item() < 10.0, "output scale collapsed or exploded!"
model.train()
model.set_lambda(1.0)
loss = model(ids).float().pow(2).mean()
loss.backward()
g = model.blocks[0].q_proj.weight.grad
gb = model.blocks[0].q_proj.bias.grad
assert g is not None and torch.isfinite(g).all() and g.abs().sum() > 0
assert gb is not None and torch.isfinite(gb).all(), "qkv bias got no grad!"
print(f"grad norms q_proj: weight={g.norm().item():.4f}, bias={gb.norm().item():.4f}")
sd = model.state_dict()
model2 = JiRackTransformer(TinyConfig())
model2.load_state_dict(sd)
assert abs(model2.get_lambda() - 1.0) < 1e-9, "lambda_ not serialized!"
print("lambda serialization: OK")
model2.eval(); model.eval()
with torch.no_grad():
assert torch.allclose(model2(ids), model(ids), atol=1e-5), "lambda host cache stale after load!"
model.train()
print("lambda after load used in eval: OK")
fake_hf = {
"model.embed_tokens.weight": model.token_emb.weight.detach().clone(),
"model.norm.weight": model.ln_f.weight.detach().clone(),
"lm_head.weight": model.lm_head.weight.detach().clone(),
}
for i, blk in enumerate(model.blocks):
p = f"model.layers.{i}"
fake_hf[f"{p}.input_layernorm.weight"] = blk.norm1.weight.detach().clone()
fake_hf[f"{p}.post_attention_layernorm.weight"] = blk.norm2.weight.detach().clone()
fake_hf[f"{p}.self_attn.q_proj.weight"] = blk.q_proj.weight.detach().clone()
fake_hf[f"{p}.self_attn.k_proj.weight"] = blk.k_proj.weight.detach().clone()
fake_hf[f"{p}.self_attn.v_proj.weight"] = blk.v_proj.weight.detach().clone()
fake_hf[f"{p}.self_attn.q_proj.bias"] = blk.q_proj.bias.detach().clone()
fake_hf[f"{p}.self_attn.k_proj.bias"] = blk.k_proj.bias.detach().clone()
fake_hf[f"{p}.self_attn.v_proj.bias"] = blk.v_proj.bias.detach().clone()
fake_hf[f"{p}.self_attn.o_proj.weight"] = blk.out_proj.weight.detach().clone()
fake_hf[f"{p}.mlp.gate_proj.weight"] = blk.ffn_w1.weight.detach().clone()
fake_hf[f"{p}.mlp.up_proj.weight"] = blk.ffn_w3.weight.detach().clone()
fake_hf[f"{p}.mlp.down_proj.weight"] = blk.ffn_w2.weight.detach().clone()
model3 = JiRackTransformer(TinyConfig()).eval()
model3.load_hf_state_dict(fake_hf)
model3.set_lambda(0.0)
model.eval(); model.set_lambda(0.0)
with torch.no_grad():
y_ref = model(ids)
y_map = model3(ids)
assert torch.allclose(y_ref, y_map, atol=1e-5), "HF mapping mismatch!"
print("HF name-mapping round-trip: OK")
exported = model.export_ternary_state_dict()
codes = exported["blocks.0.q_proj.codes"]
assert set(codes.unique().tolist()) <= {-1, 0, 1}
assert "blocks.0.q_proj.bias" in exported, "qkv bias lost in export!"
print(f"export: {sum('codes' in k for k in exported)} ternary tensors, "
f"biases preserved, OK")
import copy
md = copy.deepcopy(model).double().eval()
one = ids[:1]
for lam in (0.0, 1.0):
md.set_lambda(lam)
with torch.no_grad():
full = md(one)
cache = md.new_kv_cache()
parts = [md(one[:, :20], kv_cache=cache)]
for t in range(20, 32):
parts.append(md(one[:, t:t + 1], kv_cache=cache))
inc = torch.cat(parts, dim=1)
scale = full.abs().max()
err_dec = ((inc - full).abs().max() / scale).item()
cache.truncate(10)
tail = md(one[:, 10:], kv_cache=cache)
err_pre = ((tail - full[:, 10:]).abs().max() / scale).item()
last = md(one[:, :0 + 1], kv_cache=md.new_kv_cache())
err_one = ((last - full[:, :1]).abs().max() / scale).item()
cache.truncate(31)
only = md(one[:, 31:32], kv_cache=cache, last_logits_only=True)
err_last = ((only[:, 0] - full[:, 31]).abs().max() / scale).item()
print(f"KV cache lambda={lam}: decode {err_dec:.1e}, prefill-on-cache {err_pre:.1e}, "
f"first token {err_one:.1e}, last-only {err_last:.1e}")
assert max(err_dec, err_pre, err_one, err_last) < 1e-9, "KV cache mismatch!"
assert cache.pos == 32
small = md.new_kv_cache(max_len=8)
md(one[:, :8], kv_cache=small)
try:
md(one[:, 8:9], kv_cache=small)
raise AssertionError("cache overflow not detected")
except ValueError:
pass
print("KV cache overflow detected: OK")
print("\nAll smoke tests passed.")