shared-blocks track code
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Block-wise weight sharing ("parameter squishing") for the pear15 parallel line.
A fresh architecture experiment, deliberately OUTSIDE the frozen trainer: thefrozen ``pear15.scratch_train.run_training`` accepts an optional``model_factory(raw_config)`` seam, and this module supplies factories thatbuild weight-shared Llama backbones. Nothing in the frozen sources changes, sothe main campaign's implementation fingerprint is untouched. The factory nameis recorded verbatim in checkpoint identity (``model_factory``), giving thisline its own training identity distinct from the main campaign.
Design (MobileLLM-style immediate block-wise repetition): the model config's``num_hidden_layers`` stays the EFFECTIVE depth (same forward compute and thesame packed-data contract as the main line), while only``num_hidden_layers // repeat`` unique decoder blocks exist. Each unique blockis applied ``repeat`` times in immediate succession with different residualstreams; PyTorch accumulates the gradients from every use into the singleshared parameter, which is what "parameter squishing" means here. For the134.5M main config (30 layers, hidden 576, vocab 49152, tied embeddings),repeat=2 yields ~81M parameters with identical 30-layer forward depth.
The wrapper is a training-time artifact: evaluation and export materialize theshared weights into a standard ``num_hidden_layers`` LlamaForCausalLM (see``scripts/export_shared_hf.py``), so lm-eval sees an ordinary Llama model.Generation (``.generate``) is intentionally unsupported on the wrapper."""from __future__ import annotations
import torchfrom torch import nnfrom transformers.models.llama.configuration_llama import LlamaConfigfrom transformers.models.llama.modeling_llama import LlamaForCausalLMfrom transformers.masking_utils import create_causal_maskfrom transformers.modeling_outputs import CausalLMOutputWithPast
def build_shared_model(raw_config, *, repeat=2, attention_backend="sdpa"): """Build a weight-shared Llama causal LM; ``raw_config`` is a plain dict.
``num_hidden_layers`` in the config is the EFFECTIVE depth; the backbone holds ``num_hidden_layers // repeat`` unique blocks. Every unique block is applied ``repeat`` times per pass. The layer plan is derived from the config (never stored in the checkpoint), so a rebuilt model resumes strictly. """ raw = dict(raw_config) effective = int(raw.get("num_hidden_layers", 0)) if repeat < 1 or effective < 1 or effective % repeat: raise ValueError( f"num_hidden_layers {effective} must be divisible by repeat {repeat}") unique = effective // repeat
inner_config = dict(raw) inner_config["num_hidden_layers"] = unique config = LlamaConfig(**inner_config) config.use_cache = False config._attn_implementation = attention_backend inner = LlamaForCausalLM(config)
plan = [index // repeat for index in range(effective)] return SharedBlocksCausalLM(inner, plan)
class SharedBlocksCausalLM(nn.Module): """Wraps a reduced-depth LlamaForCausalLM and replays blocks per the plan.
The inner model is a standard LlamaForCausalLM with ``len(plan_unique)`` layers; forward runs the shared loop manually so the SAME module instance (hence the same parameters) receives gradient contributions from every one of its uses. With sdpa and unpadded fixed-length batches the causal mask is handled by ``is_causal`` exactly as in the stock forward path. """
def __init__(self, inner, layer_plan): super().__init__() self.inner = inner self.layer_plan = list(layer_plan)
@property def config(self): return self.inner.config
def gradient_checkpointing_enable(self, **kwargs): # Delegated: transformers 5.x sets the flag on each # GradientCheckpointingLayer, so direct layer calls below honor it. self.inner.gradient_checkpointing_enable(**kwargs)
def forward(self, input_ids=None, use_cache=False, **kwargs): if use_cache: raise ValueError("SharedBlocksCausalLM does not support caching; use the materialized export for generation") model = self.inner.model inputs_embeds = model.embed_tokens(input_ids) batch, seq = input_ids.shape position_ids = torch.arange(seq, device=input_ids.device).unsqueeze(0).expand(batch, -1) causal_mask = create_causal_mask( config=model.config, inputs_embeds=inputs_embeds, attention_mask=None, past_key_values=None, position_ids=position_ids) position_embeddings = model.rotary_emb(inputs_embeds, position_ids=position_ids) hidden_states = inputs_embeds for index in self.layer_plan: hidden_states = model.layers[index]( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=None, use_cache=False, position_embeddings=position_embeddings, **kwargs, ) if isinstance(hidden_states, tuple): # older transformers returns (hidden,) hidden_states = hidden_states[0] hidden_states = model.norm(hidden_states) logits = self.inner.lm_head(hidden_states) return CausalLMOutputWithPast(logits=logits)
def make_shared_factory(*, repeat=2): """``model_factory`` for pear15.scratch_train.run_training (identity seam).
The returned callable has a deterministic ``__qualname__`` so the trainer's checkpoint identity (``model_factory`` field) is stable across sessions for the same repeat factor, and distinct from the main campaign's factory. """
def factory(raw_config): return build_shared_model(raw_config, repeat=repeat, attention_backend="sdpa")
factory.__module__ = "pear15.shared_model" factory.__qualname__ = f"make_shared_factory.<locals>.shared_blocks_x{repeat}_factory" return factorypear15/shared_model.pyAdded+128