# Adapted from Ethoric-10M (https://huggingface.co/techdotus/Ethoric-10M, MIT License) # with tapered per-layer FFN dimensions and PyraLM-10M configuration. """PyraLM: compact tapered-FFN decoder-only transformer with RMSNorm, RoPE, GQA, SwiGLU, depthwise Canon convolutions and Peri-LN residuals. Each block normalises on the way into a sublayer and again on the way out, which is what Peri-LN means here: h = RMSNorm_attn_in(x); h = h + CanonA(h) x = x + RMSNorm_attn_out(Attention(h)) h = RMSNorm_mlp_in(x); h = h + CanonC(h) x = x + RMSNorm_mlp_out(SwiGLU(h)) Module and parameter names follow the usual Transformers layout. Works on Transformers 4.x and 5.x; the v5 differences are marked inline. """ from __future__ import annotations import math from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F import transformers from transformers import PreTrainedModel from transformers.modeling_outputs import CausalLMOutputWithPast try: # exported as a sibling file; importable either way from .attention import RMSNorm, PyraLMAttention, build_flex_block_mask from .configuration_pyralm import PyraLMConfig except ImportError: # pragma: no cover - direct script use from attention import RMSNorm, PyraLMAttention, build_flex_block_mask from configuration_pyralm import PyraLMConfig # Sentinel doc_id used for masked padding tokens (distinct from valid doc_ids >= 0 # and Canon's left convolution padding sentinel -1). _PAD_DOC_ID = -2 # ----------------------------------------------------------------------------- canon class Canon(nn.Module): """Causal depthwise conv1d, kernel k, no bias, used as a residual branch. Left-padded by k-1 so the output at t depends only on positions <= t. With `doc_ids` the convolution is also masked to the current document, so taps reaching back past an EOS or padding boundary contribute nothing. """ def __init__(self, d_model: int, kernel: int): super().__init__() self.kernel = int(kernel) self.weight = nn.Parameter(torch.empty(d_model, 1, self.kernel)) nn.init.normal_(self.weight, mean=0.0, std=0.02) def forward( self, x: torch.Tensor, state: Optional[torch.Tensor] = None, doc_ids: Optional[torch.Tensor] = None, state_docs: Optional[torch.Tensor] = None, ): """x is [B, T, d]. `state` carries the previous k-1 inputs for decoding. Returns (out, new_state, new_state_docs) so a caller stepping one token at a time can thread the convolution window through the cache. """ k = self.kernel xt = x.transpose(1, 2) # [B, d, T] xt = F.pad(xt, (k - 1, 0)) if state is None else torch.cat([state, xt], dim=2) new_state = xt[:, :, -(k - 1):] if k > 1 else xt[:, :, :0] if doc_ids is None: out = F.conv1d(xt, self.weight.to(xt.dtype), groups=xt.shape[1]) return out.transpose(1, 2), new_state, None # -1 never matches a real document id, so the left padding masks out # exactly as zero-padding would. if state_docs is None: dpad = F.pad(doc_ids, (k - 1, 0), value=-1) else: dpad = torch.cat([state_docs, doc_ids], dim=1) new_state_docs = dpad[:, -(k - 1):] if k > 1 else dpad[:, :0] T = x.shape[1] w = self.weight.to(xt.dtype) out = torch.zeros_like(xt[:, :, :T]) for i in range(k): seg = xt[:, :, i : i + T] keep = (dpad[:, i : i + T] == doc_ids).unsqueeze(1).to(seg.dtype) out = out + w[:, 0, i].view(1, -1, 1) * seg * keep return out.transpose(1, 2), new_state, new_state_docs # ----------------------------------------------------------------------------- blocks class SwiGLU(nn.Module): def __init__(self, d_model: int, hidden: int): super().__init__() self.gate_proj = nn.Linear(d_model, hidden, bias=False) self.up_proj = nn.Linear(d_model, hidden, bias=False) self.down_proj = nn.Linear(hidden, d_model, bias=False) def forward(self, x): return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) class PyraLMBlock(nn.Module): """One Peri-LN block: norm in, Canon, sublayer, norm out, residual add. The out-norms are the part that differs from a conventional pre-norm block. They sit inside the residual branch, so the residual stream itself is never normalised and the identity path stays exact. """ def __init__(self, config: PyraLMConfig, layer_idx: int): super().__init__() d, eps = config.d_model, config.norm_eps self.attn_in_norm = RMSNorm(d, eps) self.attn_out_norm = RMSNorm(d, eps) self.mlp_in_norm = RMSNorm(d, eps) self.mlp_out_norm = RMSNorm(d, eps) self.attn = PyraLMAttention(config, layer_idx) self.mlp = SwiGLU(d, getattr(config, "ffn_by_layer", [config.ffn_hidden] * config.n_layer)[layer_idx]) canon = config.canon or {} self.canon_enabled = bool(canon.get("enabled", False)) canon_positions = list(canon.get("positions", [])) k = int(canon.get("kernel", 4)) self.canon_doc_masking = bool(canon.get("doc_masking", True)) self.canon_a = Canon(d, k) if self.canon_enabled and "A" in canon_positions else None self.canon_c = Canon(d, k) if self.canon_enabled and "C" in canon_positions else None def _canon(self, module, name, h, doc_ids, layer_cache, force_doc_mask: bool = False): docs = doc_ids if (self.canon_doc_masking or force_doc_mask) else None state = layer_cache.get(name) if layer_cache is not None else None state_docs = layer_cache.get(f"{name}_docs") if layer_cache is not None else None delta, new_state, new_docs = module(h, state, docs, state_docs) if layer_cache is not None: layer_cache[name] = new_state layer_cache[f"{name}_docs"] = new_docs return h + delta def forward( self, x, *, positions, doc_ids, layer_cache=None, block_mask=None, force_canon_mask: bool = False, ): h = self.attn_in_norm(x) if self.canon_a is not None: h = self._canon(self.canon_a, "canon_a", h, doc_ids, layer_cache, force_doc_mask=force_canon_mask) a = self.attn( h, positions=positions, doc_ids=doc_ids, layer_cache=layer_cache, block_mask=block_mask, ) x = x + self.attn_out_norm(a) h = self.mlp_in_norm(x) if self.canon_c is not None: h = self._canon(self.canon_c, "canon_c", h, doc_ids, layer_cache, force_doc_mask=force_canon_mask) return x + self.mlp_out_norm(self.mlp(h)) # ----------------------------------------------------------------------------- cache class PyraLMCache(list): """One dict per layer: extended keys, values, positions, Canon conv state. A plain list of dicts rather than a transformers Cache subclass, so the file stays self-contained across transformers versions. """ def __init__(self, iterable=()): super().__init__(iterable) self.next_pos: Optional[torch.Tensor] = None self.next_doc: Optional[torch.Tensor] = None @classmethod def empty(cls, n_layer: int) -> "PyraLMCache": return cls({} for _ in range(n_layer)) @property def seen_tokens(self) -> int: pos = self[0].get("positions") if len(self) else None return 0 if pos is None else int(pos.shape[1]) # ----------------------------------------------------------------------------- model class PyraLMPreTrainedModel(PreTrainedModel): config_class = PyraLMConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["PyraLMBlock"] def _init_weights(self, module): std = 0.02 if isinstance(module, nn.Linear): 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=std) elif isinstance(module, RMSNorm): nn.init.ones_(module.weight) class PyraLMModel(PyraLMPreTrainedModel): def __init__(self, config: PyraLMConfig): super().__init__(config) self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model) self.layers = nn.ModuleList( PyraLMBlock(config, i) for i in range(config.n_layer) ) self.final_norm = RMSNorm(config.d_model, config.norm_eps) self.post_init() def forward( self, input_ids: torch.LongTensor, *, attention_mask: Optional[torch.Tensor] = None, doc_ids: Optional[torch.Tensor] = None, positions: Optional[torch.Tensor] = None, past_key_values: Optional[PyraLMCache] = None, use_cache: bool = False, ): B, T = input_ids.shape device = input_ids.device prev_seen = past_key_values.seen_tokens if past_key_values is not None else 0 valid: Optional[torch.Tensor] = None has_pad = False if attention_mask is not None: if attention_mask.dim() != 2 or attention_mask.shape[0] != B: raise ValueError( f"attention_mask must have shape (batch_size, seq_len) with batch_size={B}, " f"got {tuple(attention_mask.shape)}" ) mask_len = attention_mask.shape[1] full_valid = attention_mask.to(device=device).ne(0) if prev_seen > 0 and mask_len == prev_seen + T: valid = full_valid[:, -T:] elif mask_len == T: valid = full_valid else: raise ValueError( f"attention_mask length {mask_len} does not match input_ids length {T}" + (f" or total length {prev_seen + T}" if prev_seen > 0 else "") ) has_pad = bool((~valid).any()) if bool((~full_valid).any()): # Canon is a contiguous 1D causal conv over sequence indices, so # internal pad holes (1 ... 0 ... 1) cannot be faithfully masked. # Left-padding (0* 1*) and right-padding (1* 0*) are contiguous and exact. has_one_left = full_valid.int().cumsum(dim=1) > 0 has_one_right = full_valid.flip(1).int().cumsum(dim=1).flip(1) > 0 if bool(((~full_valid) & has_one_left & has_one_right).any()): raise ValueError( "PyraLM does not support non-contiguous internal padding in attention_mask; " "use left-padding or right-padding." ) explicit_positions = positions is not None prev_next_pos = ( past_key_values.next_pos if (past_key_values is not None and past_key_values.next_pos is not None) else torch.full((B, 1), prev_seen, device=device, dtype=torch.long) ) if not explicit_positions: if valid is None: if prev_seen == 0 and T > self.config.max_seq_len: raise ValueError( f"Sequence length {T} exceeds max_seq_len={self.config.max_seq_len}" ) positions = prev_next_pos + torch.arange(T, device=device, dtype=torch.long).unsqueeze(0) new_next_pos = prev_next_pos + T else: positions = (prev_next_pos + valid.long().cumsum(dim=1) - 1).clamp_min(0) new_next_pos = prev_next_pos + valid.long().sum(dim=1, keepdim=True) else: if valid is None: new_next_pos = positions[:, -1:].to(torch.long) + 1 else: new_next_pos = prev_next_pos + valid.long().sum(dim=1, keepdim=True) if (explicit_positions or valid is not None or prev_seen > 0) and positions.numel(): min_pos = int(positions.min()) max_pos = int(positions.max()) if min_pos < 0 or max_pos >= self.config.max_seq_len: raise ValueError( f"Position indices must be in [0, {self.config.max_seq_len - 1}], " f"got [{min_pos}, {max_pos}]" ) cache_has_docs = ( past_key_values is not None and prev_seen > 0 and past_key_values[0].get("doc_ids") is not None ) need_pad_docs = has_pad or cache_has_docs eos_id = int(self.config.eos_token_id or 0) new_next_doc: Optional[torch.Tensor] = None if doc_ids is None: if self.config.doc_masking: prev_next_doc = ( past_key_values.next_doc if (past_key_values is not None and past_key_values.next_doc is not None) else torch.zeros((B, 1), device=device, dtype=torch.int32) ) is_eos = input_ids == eos_id if valid is not None: is_eos = is_eos & valid is_eos_i32 = is_eos.to(torch.int32) eos_cum = torch.cumsum(is_eos_i32, dim=1) doc_ids = prev_next_doc + (eos_cum - is_eos_i32) new_next_doc = prev_next_doc + eos_cum[:, -1:] if has_pad: doc_ids = doc_ids.masked_fill(~valid, _PAD_DOC_ID) elif need_pad_docs: doc_ids = torch.zeros((B, T), device=device, dtype=torch.int32) if has_pad: doc_ids = doc_ids.masked_fill(~valid, _PAD_DOC_ID) else: if not self.config.doc_masking and not need_pad_docs: doc_ids = None elif has_pad: doc_ids = doc_ids.masked_fill(~valid, _PAD_DOC_ID) block_mask = None backend = getattr(self.layers[0].attn, "backend", "dense") if backend == "flex": k_pos = positions k_doc = doc_ids if past_key_values is not None and prev_seen: k_pos = torch.cat([past_key_values[0]["positions"], positions], dim=1) if doc_ids is not None and past_key_values[0].get("doc_ids") is not None: k_doc = torch.cat([past_key_values[0]["doc_ids"], doc_ids], dim=1) # Two masks: windowed layers additionally restrict to the local window. block_mask = { None: build_flex_block_mask(positions, k_pos, doc_ids, k_doc, None, self.config.n_head), } for layer in self.layers: w = layer.attn.attn_window if w is not None and w not in block_mask: block_mask[w] = build_flex_block_mask( positions, k_pos, doc_ids, k_doc, w, self.config.n_head ) x = self.embed_tokens(input_ids) for i, layer in enumerate(self.layers): cache = past_key_values[i] if (use_cache and past_key_values is not None) else None bm = None if block_mask is not None: w = layer.attn.attn_window bm = block_mask[w] x = layer( x, positions=positions, doc_ids=doc_ids, layer_cache=cache, block_mask=bm, force_canon_mask=need_pad_docs, ) if use_cache and past_key_values is not None: past_key_values.next_pos = new_next_pos if new_next_doc is not None: past_key_values.next_doc = new_next_doc return self.final_norm(x) # transformers 4.x expects a list of tied names; 5.x expects a # {target: source} mapping. Support both so the export loads either way. _TRANSFORMERS_MAJOR = int(transformers.__version__.split(".")[0]) _TIED_WEIGHTS_KEYS = ( {"lm_head.weight": "model.embed_tokens.weight"} if _TRANSFORMERS_MAJOR >= 5 else ["lm_head.weight"] ) class PyraLMForCausalLM(PyraLMPreTrainedModel): _tied_weights_keys = _TIED_WEIGHTS_KEYS def __init__(self, config: PyraLMConfig): super().__init__(config) self.model = PyraLMModel(config) self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) self.post_init() self._apply_residual_init() def _apply_residual_init(self): """Residual-output projections get scaled down by depth so the residual stream does not blow up at init (the GPT-2 trick). Runs after post_init(), so it overwrites what _init_weights wrote. Under from_pretrained the loaded weights land afterwards and win, which is why a trained checkpoint is unaffected by anything in here. """ std = 0.02 / math.sqrt(2 * self.config.n_layer) for layer in self.model.layers: nn.init.normal_(layer.attn.o_proj.weight, mean=0.0, std=std) nn.init.normal_(layer.mlp.down_proj.weight, mean=0.0, std=std) if layer.attn.gate_proj is not None: # Zero weight, bias 2.0: the gate starts near-open at # sigmoid(2.0) ~= 0.88 and input-independent, so early training # sees plain attention and learns the gating later. nn.init.zeros_(layer.attn.gate_proj.weight) nn.init.constant_(layer.attn.gate_proj.bias, 2.0) def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_attention_backend(self, backend: str): """'flex' or 'dense'. Dense is the CPU/MPS path and the reference.""" if backend not in ("flex", "dense"): raise ValueError("backend must be 'flex' or 'dense'") for layer in self.model.layers: layer.attn.backend = backend return self def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.LongTensor] = None, *, inputs_embeds=None, doc_ids=None, positions=None, position_ids=None, token_type_ids=None, past_key_values: Optional[PyraLMCache] = None, use_cache: bool = False, z_loss: float = 0.0, return_dict: bool = True, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, **kwargs, ): if inputs_embeds is not None: raise ValueError("PyraLM requires input_ids; inputs_embeds is not supported") if input_ids is None: raise ValueError("PyraLM requires input_ids") if output_attentions: raise ValueError("PyraLMForCausalLM does not support output_attentions=True") if output_hidden_states: raise ValueError("PyraLMForCausalLM does not support output_hidden_states=True") if positions is not None and position_ids is not None: raise ValueError("Specify at most one of positions or position_ids") if positions is None and position_ids is not None: positions = position_ids if use_cache and past_key_values is None: past_key_values = PyraLMCache.empty(self.config.n_layer) hidden = self.model( input_ids, attention_mask=attention_mask, doc_ids=doc_ids, positions=positions, past_key_values=past_key_values, use_cache=use_cache, ) logits = self.lm_head(hidden) loss = None if labels is not None: if labels.shape != input_ids.shape: raise ValueError( f"labels shape {tuple(labels.shape)} must match input_ids shape {tuple(input_ids.shape)}" ) loss = self.loss_with_z(logits, labels, z_loss=z_loss) if not return_dict: return (loss, logits) if loss is not None else (logits,) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=past_key_values if use_cache else None, ) @staticmethod def loss_with_z(logits, labels, z_loss: float = 0.0): """Standard causal LM next-token cross-entropy (internal 1-token shift) plus optional z-loss. Positions labelled -100 are ignored by both terms. """ if logits.shape[1] < 2: raise ValueError("Cannot compute causal LM loss for sequence length < 2") shift_logits = logits[:, :-1, :].contiguous() shift_labels = labels[:, 1:].contiguous() flat = shift_logits.float().view(-1, shift_logits.shape[-1]) tgt = shift_labels.reshape(-1) loss = F.cross_entropy(flat, tgt, ignore_index=-100) if z_loss: keep = tgt != -100 if keep.any(): lse = torch.logsumexp(flat[keep], dim=-1) loss = loss + z_loss * lse.pow(2).mean() return loss def _resolve_eos_ids(self, eos_token_id) -> list[int]: if eos_token_id is None: gen_cfg = getattr(self, "generation_config", None) if gen_cfg is not None and gen_cfg.eos_token_id is not None: eos_token_id = gen_cfg.eos_token_id else: eos_token_id = self.config.eos_token_id if eos_token_id is None: return [] if isinstance(eos_token_id, int): return [int(eos_token_id)] if isinstance(eos_token_id, (list, tuple, set)): return [int(x) for x in eos_token_id] raise ValueError(f"Invalid eos_token_id: {eos_token_id!r}") def _resolve_pad_id(self, pad_token_id, eos_ids: list[int]) -> int: if pad_token_id is None: gen_cfg = getattr(self, "generation_config", None) if gen_cfg is not None and gen_cfg.pad_token_id is not None: pad_token_id = gen_cfg.pad_token_id elif self.config.pad_token_id is not None: pad_token_id = self.config.pad_token_id elif eos_ids: pad_token_id = eos_ids[0] else: pad_token_id = 0 return int(pad_token_id) @torch.no_grad() def generate( self, input_ids: Optional[torch.LongTensor] = None, max_new_tokens: int = 32, *, attention_mask: Optional[torch.Tensor] = None, do_sample: bool = False, temperature: float = 1.0, top_k: Optional[int] = None, use_cache: bool = True, eos_token_id: Optional[int | list[int]] = None, pad_token_id: Optional[int] = None, token_type_ids: Optional[torch.Tensor] = None, **kwargs, ): """Greedy / top-k sampling with default EOS stopping from config/generation_config. Defined here rather than inherited so the exported model does not depend on a particular transformers Cache API. Supports unpadded and left-padded batched inputs; unsupported generation kwargs raise ValueError explicitly. """ if kwargs: raise ValueError( f"Unsupported generate() arguments for PyraLMForCausalLM: {sorted(kwargs.keys())}. " "Supported arguments: input_ids, attention_mask, max_new_tokens, do_sample, " "temperature, top_k, use_cache, eos_token_id, pad_token_id." ) if input_ids is None: raise ValueError("PyraLMForCausalLM.generate() requires input_ids") if input_ids.dim() != 2: raise ValueError( f"input_ids must be 2D (batch_size, seq_len), got shape {tuple(input_ids.shape)}" ) max_new_tokens = int(max_new_tokens) if max_new_tokens < 0: raise ValueError("max_new_tokens must be >= 0") if do_sample and float(temperature) <= 0.0: raise ValueError("temperature must be > 0 when do_sample=True") if top_k is not None and int(top_k) <= 0: raise ValueError("top_k must be a positive integer") if max_new_tokens == 0: return input_ids.clone() B, T = input_ids.shape device = input_ids.device if attention_mask is not None: if attention_mask.shape != (B, T): raise ValueError( f"attention_mask shape {tuple(attention_mask.shape)} must match input_ids shape {(B, T)}" ) mask_bool = attention_mask.to(device=device).ne(0) if not bool(mask_bool[:, -1].all()): raise ValueError( "Right-padded inputs are not supported in generate(); " "set tokenizer.padding_side = 'left' for batched generation." ) prompt_lens = mask_bool.long().sum(dim=1) full_mask: Optional[torch.Tensor] = mask_bool.long() else: prompt_lens = torch.full((B,), T, device=device, dtype=torch.long) full_mask = None if int(prompt_lens.max()) > self.config.max_seq_len: raise ValueError( f"Prompt length {int(prompt_lens.max())} exceeds max_seq_len={self.config.max_seq_len}" ) eos_ids = self._resolve_eos_ids(eos_token_id) pad_id = self._resolve_pad_id(pad_token_id, eos_ids) eos_tensor = torch.tensor(eos_ids, device=device, dtype=input_ids.dtype) if eos_ids else None finished = torch.zeros(B, dtype=torch.bool, device=device) self.eval() cache = PyraLMCache.empty(self.config.n_layer) if use_cache else None ids = input_ids cur = input_ids cur_mask = full_mask cur_lens = prompt_lens.clone() for step in range(max_new_tokens): if step > 0 and bool((cur_lens[~finished] > self.config.max_seq_len).any()): break out = self.forward( cur if use_cache else ids, attention_mask=cur_mask if use_cache else full_mask, past_key_values=cache, use_cache=use_cache, return_dict=True, ) logits = out.logits[:, -1, :].float() if do_sample: logits = logits / float(temperature) if top_k is not None: k = min(int(top_k), logits.shape[-1]) kth = logits.topk(k, dim=-1).values[:, -1:] logits = logits.masked_fill(logits < kth, float("-inf")) nxt = torch.multinomial(F.softmax(logits, dim=-1), 1) else: nxt = logits.argmax(dim=-1, keepdim=True) if bool(finished.any()): nxt = torch.where(finished.unsqueeze(1), torch.full_like(nxt, pad_id), nxt) ids = torch.cat([ids, nxt], dim=1) cur = nxt active_next = (~finished).long().unsqueeze(1) cur_lens = cur_lens + (~finished).long() if eos_tensor is not None: finished = finished | torch.isin(nxt.squeeze(-1), eos_tensor) if full_mask is not None or bool(finished.any()): if full_mask is None: full_mask = torch.ones((B, ids.shape[1] - 1), device=device, dtype=torch.long) full_mask = torch.cat([full_mask, active_next], dim=1) cur_mask = active_next else: cur_mask = None if eos_tensor is not None and bool(finished.all()): break return ids # ----------------------------------------------------------------------------- helpers def document_ids(input_ids: torch.Tensor, eos_id: int = 0) -> torch.Tensor: """Document id per position: EOS *ends* a document, so the id increments after the EOS token. The EOS itself belongs to the document it closes. Getting that boundary backwards puts each EOS in the following document, which quietly changes what every mask built from these ids allows. """ is_eos = (input_ids == eos_id).to(torch.int32) return torch.cumsum(is_eos, dim=1) - is_eos __all__ = [ "PyraLMConfig", "PyraLMForCausalLM", "PyraLMModel", "PyraLMCache", "document_ids", ]