Upload model/transformer.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from .config import ModelConfig
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x):
# Normalize in float32 even when the model runs in bfloat16.
# bf16 has ~3 decimal digits of precision, which is not enough
# for a stable variance estimate and measurably slows
# convergence (and hurts loss) on long runs. The cast is cheap.
dtype = x.dtype
x = F.rms_norm(
x.float(),
(x.size(-1),),
self.weight.float(),
self.eps,
)
return x.to(dtype)
def rotate_half(x):
x1 = x[..., ::2]
x2 = x[..., 1::2]
return torch.stack(
(-x2, x1),
dim=-1,
).flatten(-2)
class RotaryEmbedding(nn.Module):
def __init__(self, dim, max_seq_len, theta=10000.0):
super().__init__()
self.dim = dim
self.max_seq_len = max_seq_len
self.theta = theta
inv_freq = 1.0 / (
theta ** (
torch.arange(
0,
dim,
2,
dtype=torch.float32,
) / dim
)
)
self.register_buffer(
"inv_freq",
inv_freq,
persistent=False,
)
self._build_cache(max_seq_len)
def _build_cache(self, seq_len):
positions = torch.arange(
seq_len,
dtype=torch.float32,
device=self.inv_freq.device,
)
freqs = torch.outer(
positions,
self.inv_freq,
)
emb = torch.cat(
(freqs, freqs),
dim=-1,
)
self.register_buffer(
"cos",
emb.cos()[None, None, :, :],
persistent=False,
)
self.register_buffer(
"sin",
emb.sin()[None, None, :, :],
persistent=False,
)
self.max_seq_len = seq_len
def forward(self, q, k, position_offset=0):
seq_len = q.size(-2)
end = position_offset + seq_len
# Grow the cache on the fly if generation
# ever runs past the configured maximum.
if end > self.max_seq_len:
self._build_cache(
max(end, 2 * self.max_seq_len)
)
cos = self.cos[
:, :, position_offset:end, :
].to(q.dtype)
sin = self.sin[
:, :, position_offset:end, :
].to(q.dtype)
q = (q * cos) + (rotate_half(q) * sin)
k = (k * cos) + (rotate_half(k) * sin)
return q, k
class Attention(nn.Module):
def __init__(self, config: ModelConfig):
super().__init__()
if config.hidden_size % config.num_heads != 0:
raise ValueError(
"hidden_size must be divisible by num_heads"
)
self.hidden_size = config.hidden_size
self.num_heads = config.num_heads
self.head_dim = config.hidden_size // config.num_heads
self.q_proj = nn.Linear(
config.hidden_size,
config.hidden_size,
bias=config.use_bias,
)
self.k_proj = nn.Linear(
config.hidden_size,
config.hidden_size,
bias=config.use_bias,
)
self.v_proj = nn.Linear(
config.hidden_size,
config.hidden_size,
bias=config.use_bias,
)
self.out_proj = nn.Linear(
config.hidden_size,
config.hidden_size,
bias=config.use_bias,
)
self.rope = RotaryEmbedding(
self.head_dim,
config.max_seq_len,
config.rope_theta,
)
def forward(self, x, past_kv=None, use_cache=False):
batch_size, seq_len, _ = x.shape
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
q = q.view(
batch_size,
seq_len,
self.num_heads,
self.head_dim,
).transpose(1, 2)
k = k.view(
batch_size,
seq_len,
self.num_heads,
self.head_dim,
).transpose(1, 2)
v = v.view(
batch_size,
seq_len,
self.num_heads,
self.head_dim,
).transpose(1, 2)
# Positions continue after any cached tokens.
position_offset = (
past_kv[0].shape[2] if past_kv is not None else 0
)
q, k = self.rope(q, k, position_offset)
if past_kv is not None:
past_k, past_v = past_kv
k = torch.cat([past_k, k], dim=2)
v = torch.cat([past_v, v], dim=2)
present_kv = (
(k, v) if use_cache else None
)
# Causal masking rules for SDPA:
# - decoding a single token against a cache:
# no mask needed (the new token may see all
# cached positions).
# - full-sequence forward with no cache:
# standard causal mask.
is_causal = past_kv is None and seq_len > 1
attention_output = F.scaled_dot_product_attention(
q,
k,
v,
attn_mask=None,
dropout_p=0.0,
is_causal=is_causal,
)
attention_output = attention_output.transpose(
1,
2,
).contiguous()
attention_output = attention_output.view(
batch_size,
seq_len,
self.hidden_size,
)
return self.out_proj(attention_output), present_kv
class SwiGLU(nn.Module):
def __init__(self, config: ModelConfig):
super().__init__()
self.gate_proj = nn.Linear(
config.hidden_size,
config.intermediate_size,
bias=config.use_bias,
)
self.up_proj = nn.Linear(
config.hidden_size,
config.intermediate_size,
bias=config.use_bias,
)
self.down_proj = nn.Linear(
config.intermediate_size,
config.hidden_size,
bias=config.use_bias,
)
def forward(self, x):
return self.down_proj(
F.silu(self.gate_proj(x))
* self.up_proj(x)
)
class TransformerBlock(nn.Module):
def __init__(self, config: ModelConfig):
super().__init__()
self.norm1 = RMSNorm(
config.hidden_size,
config.norm_eps,
)
self.attention = Attention(config)
self.norm2 = RMSNorm(
config.hidden_size,
config.norm_eps,
)
self.mlp = SwiGLU(config)
def forward(self, x, past_kv=None, use_cache=False):
attention_output, present_kv = self.attention(
self.norm1(x),
past_kv=past_kv,
use_cache=use_cache,
)
x = x + attention_output
x = x + self.mlp(
self.norm2(x)
)
if use_cache:
return x, present_kv
return x, None
class Transformer(nn.Module):
def __init__(self, config: ModelConfig):
super().__init__()
self.config = config
self.token_embedding = nn.Embedding(
config.vocab_size,
config.hidden_size,
padding_idx=config.pad_token_id,
)
self.blocks = nn.ModuleList(
[
TransformerBlock(config)
for _ in range(config.num_layers)
]
)
self.norm = RMSNorm(
config.hidden_size,
config.norm_eps,
)
self.lm_head = nn.Linear(
config.hidden_size,
config.vocab_size,
bias=False,
)
self.lm_head.weight = self.token_embedding.weight
# Flag residual output projections BEFORE initializing, so
# _init_weights sees the flags and scales their std down.
# (Setting them inside _init_weights would re-run this loop
# once per module visited by apply.)
for block in self.blocks:
block.attention.out_proj._is_residual = True
block.mlp.down_proj._is_residual = True
self.apply(self._init_weights)
def _init_weights(self, module):
if isinstance(module, nn.Linear):
std = self.config.initializer_range
# Residual output projections start smaller
# so adding a fresh block does not blow up the
# residual stream. Critical for the 17 new
# layers in the 500M model.
if getattr(module, "_is_residual", False):
std = std / (
(2.0 * self.config.num_layers) ** 0.5
)
nn.init.normal_(
module.weight,
mean=0.0,
std=std,
)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(
module.weight,
mean=0.0,
std=self.config.initializer_range,
)
def forward(
self,
input_ids,
targets=None,
past_kvs=None,
use_cache=False,
):
batch_size, seq_len = input_ids.shape
if (
past_kvs is None
and seq_len > self.config.max_seq_len
):
raise ValueError(
f"Sequence length {seq_len} exceeds "
f"maximum length {self.config.max_seq_len}"
)
x = self.token_embedding(input_ids)
present_kvs = [] if use_cache else None
use_checkpointing = (
self.config.gradient_checkpointing
and self.training
)
for layer_index, block in enumerate(self.blocks):
block_past_kv = (
past_kvs[layer_index]
if past_kvs is not None
else None
)
if use_checkpointing:
# Recompute this block's activations during
# the backward pass. ~30% slower per step,
# but activation memory drops by ~10x, which
# is what makes a 500M model trainable on an
# 8 GB laptop GPU. Caching is only used for
# inference, so it is disabled here.
x, _ = checkpoint(
block,
x,
None,
False,
use_reentrant=False,
)
else:
x, present_kv = block(
x,
past_kv=block_past_kv,
use_cache=use_cache,
)
if use_cache:
present_kvs.append(present_kv)
x = self.norm(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
# Upcast to float32 before the softmax: with a 50k-token
# vocabulary a bf16 cross-entropy loses real precision
# (the log-softmax over 50k entries needs the range).
loss = F.cross_entropy(
logits.reshape(
-1,
logits.size(-1),
).float(),
targets.reshape(-1),
)
if use_cache:
return logits, loss, present_kvs
return logits, lossmodel/transformer.pyAdded+462