| """ |
| RoPE variant of the GPT language model used by this project. |
| |
| This file mirrors model/transformer.py, but removes the learned absolute |
| position embedding (wpe) and applies rotary position embedding to q/k inside |
| causal self-attention. The public surface is intentionally kept compatible with |
| GPTConfig/GPT: transformer.h exists for hooks, forward returns (logits, loss), |
| and generate/configure_optimizers are reused from the base GPT implementation. |
| """ |
|
|
| import math |
| from dataclasses import dataclass |
|
|
| import torch |
| import torch.nn as nn |
| from torch.nn import functional as F |
|
|
| from .transformer import ( |
| GPT as BaseGPT, |
| LayerNorm, |
| MLP, |
| NonLinearPrefixScan, |
| DyadicFixedAttention, |
| ) |
|
|
|
|
| class RotaryEmbedding(nn.Module): |
| def __init__(self, dim, base=10000.0): |
| super().__init__() |
| assert dim % 2 == 0, "RoPE requires an even head dimension" |
| inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) |
| self.register_buffer("inv_freq", inv_freq, persistent=False) |
|
|
| def forward(self, x, pos_offset=0): |
| t = x.size(-2) |
| positions = torch.arange( |
| pos_offset, pos_offset + t, |
| device=x.device, |
| dtype=self.inv_freq.dtype, |
| ) |
| freqs = torch.outer(positions, self.inv_freq.to(x.device)) |
| cos = freqs.cos().to(dtype=x.dtype).view(1, 1, t, -1) |
| sin = freqs.sin().to(dtype=x.dtype).view(1, 1, t, -1) |
| return cos, sin |
|
|
|
|
| def apply_rotary_emb(x, cos, sin): |
| x_pair = x.reshape(*x.shape[:-1], -1, 2) |
| x_even = x_pair[..., 0] |
| x_odd = x_pair[..., 1] |
| x_rot = torch.stack( |
| (x_even * cos - x_odd * sin, x_even * sin + x_odd * cos), |
| dim=-1, |
| ) |
| return x_rot.flatten(-2).type_as(x) |
|
|
|
|
| class CausalSelfAttentionRoPE(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| assert config.n_embd % config.n_head == 0 |
| head_size = config.n_embd // config.n_head |
| assert head_size % 2 == 0, "RoPE requires n_embd / n_head to be even" |
| self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) |
| self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) |
| self.attn_dropout = nn.Dropout(config.dropout) |
| self.resid_dropout = nn.Dropout(config.dropout) |
| self.n_head = config.n_head |
| self.n_embd = config.n_embd |
| self.dropout = config.dropout |
| self.rope = RotaryEmbedding(head_size, base=getattr(config, 'rope_base', 10000.0)) |
| self.flash = config.use_flash and hasattr(torch.nn.functional, 'scaled_dot_product_attention') |
| if not self.flash: |
| if not config.use_flash: |
| print("INFO: Flash attention disabled via --local flag (for local GPU compatibility)") |
| else: |
| print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0") |
| self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)) |
| .view(1, 1, config.block_size, config.block_size)) |
|
|
| def forward(self, x, kv_cache=None): |
| bsz, t, channels = x.size() |
| q, k, v = self.c_attn(x).split(self.n_embd, dim=2) |
| n_head = self.n_head |
| head_size = channels // n_head |
| k = k.view(bsz, t, n_head, head_size).transpose(1, 2) |
| q = q.view(bsz, t, n_head, head_size).transpose(1, 2) |
| v = v.view(bsz, t, n_head, head_size).transpose(1, 2) |
|
|
| cur_len = kv_cache.get('len', 0) if kv_cache is not None else 0 |
| cos, sin = self.rope(q, pos_offset=cur_len) |
| q = apply_rotary_emb(q, cos, sin) |
| k = apply_rotary_emb(k, cos, sin) |
|
|
| if kv_cache is None: |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k, v, attn_mask=None, |
| dropout_p=self.dropout if self.training else 0, |
| is_causal=True) |
| else: |
| att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) |
| att = att.masked_fill(self.bias[:, :, :t, :t] == 0, float('-inf')) |
| att = F.softmax(att, dim=-1) |
| att = self.attn_dropout(att) |
| y = att @ v |
| else: |
| max_len = kv_cache['max_L'] |
| if 'k_buf' not in kv_cache: |
| kv_cache['k_buf'] = torch.empty(bsz, n_head, max_len, head_size, dtype=k.dtype, device=k.device) |
| kv_cache['v_buf'] = torch.empty(bsz, n_head, max_len, head_size, dtype=v.dtype, device=v.device) |
| new_end = cur_len + t |
| assert new_end <= max_len, f"KV cache overflow: {new_end} > {max_len}" |
| kv_cache['k_buf'][:, :, cur_len:new_end].copy_(k) |
| kv_cache['v_buf'][:, :, cur_len:new_end].copy_(v) |
| kv_cache['len'] = new_end |
|
|
| k_full = kv_cache['k_buf'][:, :, :new_end] |
| v_full = kv_cache['v_buf'][:, :, :new_end] |
|
|
| if t == 1: |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k_full, v_full, attn_mask=None, dropout_p=0, is_causal=False) |
| else: |
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(head_size)) |
| att = F.softmax(att, dim=-1) |
| y = att @ v_full |
| else: |
| device = q.device |
| q_abs = torch.arange(cur_len, new_end, device=device).unsqueeze(1) |
| k_abs = torch.arange(0, new_end, device=device).unsqueeze(0) |
| mask = (k_abs <= q_abs).view(1, 1, t, new_end) |
| if self.flash: |
| y = torch.nn.functional.scaled_dot_product_attention( |
| q, k_full, v_full, attn_mask=mask, dropout_p=0, is_causal=False) |
| else: |
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(head_size)) |
| att = att.masked_fill(~mask, float('-inf')) |
| att = F.softmax(att, dim=-1) |
| y = att @ v_full |
|
|
| y = y.transpose(1, 2).contiguous().view(bsz, t, channels) |
| y = self.resid_dropout(self.c_proj(y)) |
| return y |
|
|
|
|
| class BlockRoPE(nn.Module): |
| def __init__(self, config, layer_idx=0, dyadic_attn_override=None): |
| super().__init__() |
| self.layer_idx = layer_idx |
| self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) |
| if dyadic_attn_override is None: |
| use_dyadic = bool(getattr(config, 'dyadic_attn', False)) |
| else: |
| use_dyadic = bool(dyadic_attn_override) |
| self.is_dyadic_attn = use_dyadic |
| if use_dyadic: |
| self.attn = DyadicFixedAttention(config, layer_idx) |
| else: |
| self.attn = CausalSelfAttentionRoPE(config) |
| self.ln_2 = LayerNorm(config.n_embd, bias=config.bias) |
| self.mlp = MLP(config) |
|
|
| self.per_block_gru = None |
| self.ln_gru = None |
| if getattr(config, 'post_gru', False): |
| self.ln_gru = LayerNorm(config.n_embd, bias=config.bias) |
| self.per_block_gru = nn.GRU( |
| config.n_embd, config.n_embd, num_layers=1, batch_first=True, |
| ) |
| for name, param in self.per_block_gru.named_parameters(): |
| if 'weight_hh' in name or 'weight_ih' in name: |
| nn.init.xavier_uniform_(param, gain=0.1) |
| elif 'bias' in name: |
| nn.init.zeros_(param) |
|
|
| self.per_block_nls = None |
| self.ln_nls = None |
| if getattr(config, 'per_block_nls', False): |
| self.ln_nls = LayerNorm(config.n_embd, bias=config.bias) |
| self.per_block_nls = NonLinearPrefixScan( |
| config.n_embd, dropout=config.dropout, |
| ) |
|
|
| def forward(self, x, nls_cache=None, kv_cache=None): |
| x = x + self.attn(self.ln_1(x), kv_cache=kv_cache) |
| x = x + self.mlp(self.ln_2(x)) |
| if self.per_block_gru is not None: |
| orig_dtype = x.dtype |
| with torch.amp.autocast(device_type='cuda', enabled=False): |
| g, _ = self.per_block_gru(self.ln_gru(x).float()) |
| x = x + g.to(orig_dtype) |
| if self.per_block_nls is not None: |
| x = x + self.per_block_nls(self.ln_nls(x), cache=nls_cache) |
| return x |
|
|
|
|
| @dataclass |
| class GPTRoPEConfig: |
| block_size: int = 1024 |
| vocab_size: int = 50304 |
| n_layer: int = 12 |
| n_head: int = 12 |
| n_embd: int = 768 |
| dropout: float = 0.0 |
| bias: bool = True |
| use_flash: bool = True |
| rope_base: float = 10000.0 |
| post_gru: bool = False |
| per_block_nls: bool = False |
| dyadic_attn: bool = False |
| dyadic_hybrid: bool = False |
|
|
|
|
| class GPTRoPE(nn.Module): |
| configure_optimizers = BaseGPT.configure_optimizers |
| estimate_mfu = BaseGPT.estimate_mfu |
| generate = BaseGPT.generate |
|
|
| def __init__(self, config): |
| super().__init__() |
| assert config.vocab_size is not None |
| assert config.block_size is not None |
| self.config = config |
|
|
| if getattr(config, 'dyadic_hybrid', False): |
| n_levels = max(1, math.ceil(math.log2(config.block_size))) if config.block_size > 1 else 1 |
| blocks = [] |
| for _ in range(config.n_layer): |
| blocks.append(BlockRoPE(config, layer_idx=0, dyadic_attn_override=False)) |
| for level in range(n_levels): |
| blocks.append(BlockRoPE(config, layer_idx=level, dyadic_attn_override=True)) |
| block_list = nn.ModuleList(blocks) |
| else: |
| block_list = nn.ModuleList([BlockRoPE(config, layer_idx=i) for i in range(config.n_layer)]) |
|
|
| self.transformer = nn.ModuleDict(dict( |
| wte=nn.Embedding(config.vocab_size, config.n_embd), |
| drop=nn.Dropout(config.dropout), |
| h=block_list, |
| ln_f=LayerNorm(config.n_embd, bias=config.bias), |
| )) |
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) |
| self.transformer.wte.weight = self.lm_head.weight |
|
|
| self.apply(self._init_weights) |
| for name, param in self.named_parameters(): |
| if name.endswith('c_proj.weight'): |
| torch.nn.init.normal_(param, mean=0.0, std=0.02 / math.sqrt(2 * len(self.transformer.h))) |
|
|
| print("number of parameters: %.2fM" % (self.get_num_params() / 1e6,)) |
|
|
| def get_num_params(self, non_embedding=True): |
| return sum(param.numel() for param in self.parameters()) |
|
|
| def _init_weights(self, module): |
| if isinstance(module, nn.Linear): |
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
| if module.bias is not None: |
| torch.nn.init.zeros_(module.bias) |
| elif isinstance(module, nn.Embedding): |
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
|
|
| def forward(self, idx, targets=None, nls_caches=None, kv_caches=None): |
| bsz, t = idx.size() |
| if kv_caches is not None and len(kv_caches) > 0 and kv_caches[0].get('len', 0) > 0: |
| pos_offset = kv_caches[0]['len'] |
| else: |
| pos_offset = 0 |
| assert pos_offset + t <= self.config.block_size, ( |
| f"Cannot forward sequence of length {pos_offset + t}, block size is only {self.config.block_size}") |
|
|
| tok_emb = self.transformer.wte(idx) |
| x = self.transformer.drop(tok_emb) |
| for i, block in enumerate(self.transformer.h): |
| blk_nls_cache = nls_caches[i] if nls_caches is not None else None |
| blk_kv_cache = kv_caches[i] if kv_caches is not None else None |
| x = block(x, nls_cache=blk_nls_cache, kv_cache=blk_kv_cache) |
| x = self.transformer.ln_f(x) |
|
|
| if targets is not None: |
| logits = self.lm_head(x) |
| loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0) |
| else: |
| logits = self.lm_head(x[:, [-1], :]) |
| loss = None |
| return logits, loss |
|
|
| def crop_block_size(self, block_size): |
| assert block_size <= self.config.block_size |
| self.config.block_size = block_size |
| for block in self.transformer.h: |
| if hasattr(block.attn, 'bias'): |
| block.attn.bias = block.attn.bias[:, :, :block_size, :block_size] |
|
|
|
|
| GPTConfig = GPTRoPEConfig |
| GPT = GPTRoPE |
|
|