Koliber-1.3-BeLooped / modeling_koliber.py
Aleksander22's picture
Add experimental Koliber 1.3 BeLooped 6B release and milestones
961326d verified
Raw History Blame Contribute Delete
11.3 kB
#!/usr/bin/env python3
# KOLIBER 1.3 BELOOPED — STANDALONE trainer and model
"""Koliber-1.3-BeLooped reference model. True FlashAttention SWA for long CUDA sequences."""
from __future__ import annotations
from dataclasses import dataclass, asdict
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
try:
from flash_attn import flash_attn_func
except ImportError:
flash_attn_func = None
@dataclass(frozen=True)
class BeLoopedConfig:
vocab_size: int = 32768 # physically padded embedding rows
tokenizer_vocab_size: int = 32000 # active IDs and output logits
hidden_size: int = 768
intermediate_size: int = 2048
num_attention_heads: int = 16
num_key_value_heads: int = 4
head_dim: int = 64
input_layers: int = 5
recurrent_layers: int = 6
output_layers: int = 4
sliding_window: int = 512
max_position_embeddings: int = 32768
rope_theta: float = 100000.0 # provisional, validate 16K/32K quality
rms_norm_eps: float = 1e-6
max_fallback_local_seq: int = 2048
@property
def num_hidden_layers(self):
return self.input_layers + self.recurrent_layers + self.output_layers
def validate(self):
assert self.num_hidden_layers == 15
assert self.num_attention_heads % self.num_key_value_heads == 0
assert self.head_dim % 2 == 0
assert self.tokenizer_vocab_size <= self.vocab_size
assert self.sliding_window > 0
class RMSNorm(nn.Module):
def __init__(self, dim, eps):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x):
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
class Rotary(nn.Module):
def __init__(self, cfg):
super().__init__()
freqs = 1.0 / (cfg.rope_theta ** (torch.arange(0, cfg.head_dim, 2, dtype=torch.float32) / cfg.head_dim))
self.head_dim = cfg.head_dim
self.rope_theta = cfg.rope_theta
def forward(self, q, k):
t = q.shape[1]
pos = torch.arange(t, device=q.device, dtype=torch.float32)
inv_freq = 1.0 / (self.rope_theta ** (
torch.arange(0, self.head_dim, 2,
device=q.device, dtype=torch.float32)
/ self.head_dim
))
phases = torch.outer(pos, inv_freq)
cos = phases.cos()[None, :, None, :]
sin = phases.sin()[None, :, None, :]
def rotate(x):
xf = x.float()
a, b = xf[..., 0::2], xf[..., 1::2]
return torch.stack((a*cos-b*sin, a*sin+b*cos), dim=-1).flatten(-2).to(x.dtype)
return rotate(q), rotate(k)
class Attention(nn.Module):
def __init__(self, cfg, local: bool, rope):
super().__init__()
self.cfg, self.local, self.rope = cfg, local, rope
q = cfg.num_attention_heads * cfg.head_dim
kv = cfg.num_key_value_heads * cfg.head_dim
self.qkv = nn.Linear(cfg.hidden_size, q+2*kv, bias=False)
self.out = nn.Linear(q, cfg.hidden_size, bias=False) # IMPORTANT: q=1024, residual=768
def forward(self, x):
b, t, _ = x.shape
c = self.cfg
qsize = c.num_attention_heads * c.head_dim
kvsize = c.num_key_value_heads * c.head_dim
q, k, v = self.qkv(x).split((qsize, kvsize, kvsize), dim=-1)
q = q.reshape(b, t, c.num_attention_heads, c.head_dim)
k = k.reshape(b, t, c.num_key_value_heads, c.head_dim)
v = v.reshape(b, t, c.num_key_value_heads, c.head_dim)
q, k = self.rope(q, k)
if flash_attn_func is not None and q.is_cuda and q.dtype in (torch.float16, torch.bfloat16):
# True local attention kernel: no dense 32K x 32K mask.
window = (c.sliding_window-1, 0) if self.local else (-1, -1)
y = flash_attn_func(q, k, v, dropout_p=0.0, causal=True, window_size=window)
else:
if self.local and t > c.max_fallback_local_seq:
raise RuntimeError('Long SWA requires flash-attn; refusing quadratic fallback. Install flash-attn.')
qh, kh, vh = q.transpose(1,2), k.transpose(1,2), v.transpose(1,2)
if self.local:
ix = torch.arange(t, device=x.device)
mask = (ix[None, :] <= ix[:, None]) & (ix[None, :] >= ix[:, None] - c.sliding_window + 1)
y = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask, dropout_p=0.0, enable_gqa=True)
else:
y = F.scaled_dot_product_attention(qh, kh, vh, is_causal=True, dropout_p=0.0, enable_gqa=True)
y = y.transpose(1,2)
return self.out(y.reshape(b,t,qsize))
class Block(nn.Module):
def __init__(self, cfg, local, rope):
super().__init__()
self.attn_norm = RMSNorm(cfg.hidden_size,cfg.rms_norm_eps)
self.attn = Attention(cfg,local,rope)
self.ffn_norm = RMSNorm(cfg.hidden_size,cfg.rms_norm_eps)
self.gate_up = nn.Linear(cfg.hidden_size, 2*cfg.intermediate_size, bias=False)
self.down = nn.Linear(cfg.intermediate_size,cfg.hidden_size,bias=False)
def forward(self,x):
x = x + self.attn(self.attn_norm(x))
gate,up = self.gate_up(self.ffn_norm(x)).chunk(2,dim=-1)
return x+self.down(F.silu(gate)*up)
class KoliberBeLooped(nn.Module):
def __init__(self,cfg=BeLoopedConfig()):
super().__init__()
cfg.validate()
self.cfg=cfg
self.embed=nn.Embedding(cfg.vocab_size,cfg.hidden_size)
self.rope=Rotary(cfg)
# F-S-F-S-F...F: 8 Full + 7 local; final L15 Full.
self.blocks=nn.ModuleList(Block(cfg, local=(i%2 == 1),rope=self.rope) for i in range(cfg.num_hidden_layers))
self.norm=RMSNorm(cfg.hidden_size,cfg.rms_norm_eps)
self.reset_parameters()
def reset_parameters(self):
residual_std=.02 / math.sqrt(2 * (self.cfg.input_layers+3*self.cfg.recurrent_layers+self.cfg.output_layers))
for m in self.modules():
if isinstance(m, (nn.Embedding,nn.Linear)):
nn.init.normal_(m.weight,mean=0,std=.02)
for b in self.blocks:
nn.init.normal_(b.attn.out.weight,mean=0,std=residual_std)
nn.init.normal_(b.down.weight,mean=0,std=residual_std)
def forward_hidden(self, ids, loops=2, grad_checkpoint=False):
if loops not in (1,2,3):
raise ValueError('loops must be one of 1,2,3')
if ids.shape[1] > self.cfg.max_position_embeddings:
raise ValueError('sequence exceeds max_position_embeddings')
x=self.embed(ids)
# Recurrent block 5..10 in zero-based indexing; input 0..4, output 11..14.
start=self.cfg.input_layers
end=start+self.cfg.recurrent_layers
schedule=list(range(start))+list(range(start,end))*loops+list(range(end,self.cfg.num_hidden_layers))
for idx in schedule:
block=self.blocks[idx]
if grad_checkpoint and self.training:
x=checkpoint(block,x,use_reentrant=False)
else:
x=block(x)
return self.norm(x)
def loss(self, ids, loops=2, grad_checkpoint=False, ce_chunk=256):
# [B,T+1] -> [B,T] prediction, preserving all T labels per packed sample.
x=self.forward_hidden(ids[:,:-1],loops,grad_checkpoint)
y=ids[:,1:].reshape(-1)
x=x.reshape(-1,self.cfg.hidden_size)
# Only 32000 real token IDs enter CE. Reserved 768 output rows never normalized.
out_weight=self.embed.weight[:self.cfg.tokenizer_vocab_size]
total=x.new_zeros((),dtype=torch.float32)
for j in range(0,y.numel(),ce_chunk):
logits=F.linear(x[j:j+ce_chunk],out_weight)
total=total+F.cross_entropy(logits.float(),y[j:j+ce_chunk],reduction='sum')
return total / y.numel()
def parameter_count(self):
return sum(p.numel() for p in self.parameters())
from transformers import PreTrainedModel
from transformers.generation import GenerationMixin
from transformers.modeling_outputs import CausalLMOutput
from .configuration_koliber import KoliberConfig
class KoliberForCausalLM(PreTrainedModel, GenerationMixin):
config_class = KoliberConfig
base_model_prefix = "model"
main_input_name = "input_ids"
_no_split_modules = ["Block"]
def __init__(self, config):
super().__init__(config)
fields = BeLoopedConfig.__dataclass_fields__
model_cfg = BeLoopedConfig(**{
k: getattr(config, k)
for k in fields
})
self.model = KoliberBeLooped(model_cfg)
self.post_init()
def get_input_embeddings(self):
return self.model.embed
def get_output_embeddings(self):
# The LM head uses F.linear(..., embed.weight[:32000]).
# No independent output weights exist.
return None
def forward(
self,
input_ids=None,
attention_mask=None,
labels=None,
recurrence_steps=None,
logits_to_keep=0,
use_cache=False,
past_key_values=None,
**kwargs,
):
if input_ids is None:
raise ValueError("input_ids required")
if use_cache or past_key_values is not None:
raise NotImplementedError(
"KV cache is not validated yet. Use use_cache=False."
)
if attention_mask is not None and not bool(attention_mask.all()):
raise NotImplementedError(
"Padded attention masks are not validated yet."
)
loops = (
self.config.recurrence_steps
if recurrence_steps is None
else int(recurrence_steps)
)
hidden = self.model.forward_hidden(
input_ids, loops=loops, grad_checkpoint=False
)
if labels is not None:
# Full logits, matching standard causal LM behavior.
logits = F.linear(
hidden,
self.model.embed.weight[
:self.config.tokenizer_vocab_size
],
)
target = labels[:, 1:].contiguous()
prediction = logits[:, :-1].contiguous()
loss = F.cross_entropy(
prediction.float().reshape(
-1, self.config.tokenizer_vocab_size
),
target.reshape(-1),
ignore_index=-100,
)
else:
keep = int(logits_to_keep or 0)
if keep > 0:
hidden = hidden[:, -keep:]
logits = F.linear(
hidden,
self.model.embed.weight[
:self.config.tokenizer_vocab_size
],
)
loss = None
return CausalLMOutput(loss=loss, logits=logits)
def prepare_inputs_for_generation(
self,
input_ids,
attention_mask=None,
recurrence_steps=None,
**kwargs,
):
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"recurrence_steps": recurrence_steps,
"use_cache": False,
"logits_to_keep": 1,
}