Quasar / quasar /model /transformer.py
Atlas Ai
Upload evaluated Quasar weights with portable inference and pinned codecs
d2a1a41 verified
Raw History Blame Contribute Delete
6.53 kB
"""Quasar: one decoder-only transformer over the unified text/image/video token space.
Pre-norm blocks (RMSNorm -> GQA attention with RoPE -> residual -> RMSNorm -> SwiGLU -> residual),
tied input/output embeddings, and one extra signal for visual tokens: a learned embedding of the
token's spatial slot inside its frame (0 for non-visual tokens). The slot is a pure function of
the token sequence (index within the current contiguous run of visual codes), so it carries no
information the tokens do not already imply; it just saves a small model from learning to count.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from .attention import Attention, KVCache
from .axiom import HybridBlock, HybridCache
from .config import ModelConfig
from .layers import RMSNorm, SwiGLU, rope_tables
class Block(nn.Module):
def __init__(self, cfg: ModelConfig):
super().__init__()
self.attn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)
self.attn = Attention(cfg)
self.ffn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)
self.ffn = SwiGLU(cfg.d_model, cfg.ffn_hidden)
def forward(self, x, cos, sin, cache=None, layer=0, start=0):
x = x + self.attn(self.attn_norm(x), cos, sin, cache, layer, start)
return x + self.ffn(self.ffn_norm(x))
class Quasar(nn.Module):
def __init__(self, cfg: ModelConfig):
super().__init__()
self.cfg = cfg
self.embed = nn.Embedding(cfg.vocab_size, cfg.d_model)
self.vis_embed = nn.Embedding(cfg.vis_positions + 1, cfg.d_model, padding_idx=0) if cfg.vis_positions else None
self.hybrid = cfg.architecture == "axiom1_1"
self.blocks = nn.ModuleList(HybridBlock(cfg, i) if self.hybrid else Block(cfg) for i in range(cfg.n_layers))
self.norm = RMSNorm(cfg.d_model, cfg.norm_eps)
self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
if cfg.tie_embeddings:
self.head.weight = self.embed.weight
cos, sin = rope_tables(cfg.head_dim, cfg.max_seq_len, cfg.rope_theta)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
self.apply(self._init)
for b in self.blocks: # scale residual-branch outputs (GPT-2 style)
residuals = [b.mix.out.weight, *(c[2].weight for c in b.ffn.cells)] if self.hybrid else [b.attn.wo.weight, b.ffn.w_down.weight]
for w in residuals:
nn.init.normal_(w, std=cfg.init_std / math.sqrt(2 * cfg.n_layers))
def _init(self, m: nn.Module) -> None:
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=self.cfg.init_std)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.zeros_(m.bias)
if isinstance(m, nn.Embedding) and m.padding_idx is not None:
with torch.no_grad():
m.weight[m.padding_idx].zero_()
def num_params(self, include_embedding: bool = True) -> int:
n = sum(p.numel() for p in self.parameters()) # tied weights counted once
return n if include_embedding else n - self.embed.weight.numel()
def visual_positions(self, tokens: torch.Tensor) -> torch.Tensor:
"""1-based index of each visual token inside its contiguous run (0 for other tokens)."""
lo, hi = self.cfg.visual_offset, self.cfg.visual_offset + self.cfg.visual_size
is_vis = (tokens >= lo) & (tokens < hi)
idx = torch.arange(tokens.shape[-1], device=tokens.device).expand_as(tokens)
run_start = torch.where(is_vis, torch.zeros_like(idx), idx + 1).cummax(dim=-1).values
return torch.where(is_vis, idx - run_start + 1, torch.zeros_like(idx)).clamp(max=self.cfg.vis_positions)
def forward(self, tokens: torch.Tensor, vis_pos: torch.Tensor | None = None, cache: KVCache | HybridCache | None = None, start: int = 0,
return_aux: bool = False):
"""tokens [B, L] -> logits [B, L, V]. With a cache, `start` is the absolute position of tokens[:, 0]."""
B, L = tokens.shape
if start + L > self.cfg.max_seq_len:
raise ValueError(f"sequence length {start + L} exceeds max_seq_len {self.cfg.max_seq_len}")
if cache is not None and self.hybrid:
if not isinstance(cache, HybridCache) or start != cache.next_pos or start + L > cache.max_len:
raise ValueError("hybrid cache requires consecutive appends within its capacity; use a fresh cache for a new sequence")
x = self.embed(tokens)
if self.vis_embed is not None:
x = x + self.vis_embed(self.visual_positions(tokens) if vis_pos is None else vis_pos)
cos, sin = self.rope_cos[start : start + L], self.rope_sin[start : start + L]
balances = []
for i, blk in enumerate(self.blocks):
if self.cfg.grad_checkpoint and self.training and cache is None:
result = checkpoint(blk, x, cos, sin, use_reentrant=False)
else:
result = blk(x, cos, sin, cache, i, start)
if self.hybrid:
x, balance = result
balances.append(balance)
else:
x = result
if cache is not None and self.hybrid:
cache.next_pos = start + L
logits = self.head(self.norm(x))
aux = torch.stack(balances).mean() if balances else logits.new_zeros(())
return (logits, aux) if return_aux else logits
def loss(self, tokens: torch.Tensor, labels: torch.Tensor, include_aux: bool = True) -> tuple[torch.Tensor, torch.Tensor]:
"""Mean target-token CE, optionally plus Axiom balance loss; (objective, n_targets)."""
logits, aux = self(tokens, return_aux=True)
n = (labels != -100).sum()
loss = F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), labels.reshape(-1), ignore_index=-100)
return loss + (self.cfg.balance_weight * aux if include_aux else 0), n
def new_cache(self, batch: int, max_len: int | None = None, dtype=None) -> KVCache:
p = next(self.parameters())
cache_type = HybridCache if self.hybrid else KVCache
return cache_type(self.cfg, batch, max_len or self.cfg.max_seq_len, p.device, dtype or p.dtype)