coderofpears commited on
Commit
a9a05bb
·
verified ·
1 Parent(s): 1f1937b

shared-blocks track code

Browse files
Files changed (1) hide show
  1. pear15/shared_model.py +128 -0
pear15/shared_model.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Block-wise weight sharing ("parameter squishing") for the pear15 parallel line.
2
+
3
+ A fresh architecture experiment, deliberately OUTSIDE the frozen trainer: the
4
+ frozen ``pear15.scratch_train.run_training`` accepts an optional
5
+ ``model_factory(raw_config)`` seam, and this module supplies factories that
6
+ build weight-shared Llama backbones. Nothing in the frozen sources changes, so
7
+ the main campaign's implementation fingerprint is untouched. The factory name
8
+ is recorded verbatim in checkpoint identity (``model_factory``), giving this
9
+ line its own training identity distinct from the main campaign.
10
+
11
+ Design (MobileLLM-style immediate block-wise repetition): the model config's
12
+ ``num_hidden_layers`` stays the EFFECTIVE depth (same forward compute and the
13
+ same packed-data contract as the main line), while only
14
+ ``num_hidden_layers // repeat`` unique decoder blocks exist. Each unique block
15
+ is applied ``repeat`` times in immediate succession with different residual
16
+ streams; PyTorch accumulates the gradients from every use into the single
17
+ shared parameter, which is what "parameter squishing" means here. For the
18
+ 134.5M main config (30 layers, hidden 576, vocab 49152, tied embeddings),
19
+ repeat=2 yields ~81M parameters with identical 30-layer forward depth.
20
+
21
+ The wrapper is a training-time artifact: evaluation and export materialize the
22
+ shared weights into a standard ``num_hidden_layers`` LlamaForCausalLM (see
23
+ ``scripts/export_shared_hf.py``), so lm-eval sees an ordinary Llama model.
24
+ Generation (``.generate``) is intentionally unsupported on the wrapper.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import torch
29
+ from torch import nn
30
+ from transformers.models.llama.configuration_llama import LlamaConfig
31
+ from transformers.models.llama.modeling_llama import LlamaForCausalLM
32
+ from transformers.masking_utils import create_causal_mask
33
+ from transformers.modeling_outputs import CausalLMOutputWithPast
34
+
35
+
36
+ def build_shared_model(raw_config, *, repeat=2, attention_backend="sdpa"):
37
+ """Build a weight-shared Llama causal LM; ``raw_config`` is a plain dict.
38
+
39
+ ``num_hidden_layers`` in the config is the EFFECTIVE depth; the backbone
40
+ holds ``num_hidden_layers // repeat`` unique blocks. Every unique block is
41
+ applied ``repeat`` times per pass. The layer plan is derived from the config
42
+ (never stored in the checkpoint), so a rebuilt model resumes strictly.
43
+ """
44
+ raw = dict(raw_config)
45
+ effective = int(raw.get("num_hidden_layers", 0))
46
+ if repeat < 1 or effective < 1 or effective % repeat:
47
+ raise ValueError(
48
+ f"num_hidden_layers {effective} must be divisible by repeat {repeat}")
49
+ unique = effective // repeat
50
+
51
+ inner_config = dict(raw)
52
+ inner_config["num_hidden_layers"] = unique
53
+ config = LlamaConfig(**inner_config)
54
+ config.use_cache = False
55
+ config._attn_implementation = attention_backend
56
+ inner = LlamaForCausalLM(config)
57
+
58
+ plan = [index // repeat for index in range(effective)]
59
+ return SharedBlocksCausalLM(inner, plan)
60
+
61
+
62
+ class SharedBlocksCausalLM(nn.Module):
63
+ """Wraps a reduced-depth LlamaForCausalLM and replays blocks per the plan.
64
+
65
+ The inner model is a standard LlamaForCausalLM with ``len(plan_unique)``
66
+ layers; forward runs the shared loop manually so the SAME module instance
67
+ (hence the same parameters) receives gradient contributions from every one
68
+ of its uses. With sdpa and unpadded fixed-length batches the causal mask is
69
+ handled by ``is_causal`` exactly as in the stock forward path.
70
+ """
71
+
72
+ def __init__(self, inner, layer_plan):
73
+ super().__init__()
74
+ self.inner = inner
75
+ self.layer_plan = list(layer_plan)
76
+
77
+ @property
78
+ def config(self):
79
+ return self.inner.config
80
+
81
+ def gradient_checkpointing_enable(self, **kwargs):
82
+ # Delegated: transformers 5.x sets the flag on each
83
+ # GradientCheckpointingLayer, so direct layer calls below honor it.
84
+ self.inner.gradient_checkpointing_enable(**kwargs)
85
+
86
+ def forward(self, input_ids=None, use_cache=False, **kwargs):
87
+ if use_cache:
88
+ raise ValueError("SharedBlocksCausalLM does not support caching; use the materialized export for generation")
89
+ model = self.inner.model
90
+ inputs_embeds = model.embed_tokens(input_ids)
91
+ batch, seq = input_ids.shape
92
+ position_ids = torch.arange(seq, device=input_ids.device).unsqueeze(0).expand(batch, -1)
93
+ causal_mask = create_causal_mask(
94
+ config=model.config, inputs_embeds=inputs_embeds,
95
+ attention_mask=None, past_key_values=None, position_ids=position_ids)
96
+ position_embeddings = model.rotary_emb(inputs_embeds, position_ids=position_ids)
97
+ hidden_states = inputs_embeds
98
+ for index in self.layer_plan:
99
+ hidden_states = model.layers[index](
100
+ hidden_states,
101
+ attention_mask=causal_mask,
102
+ position_ids=position_ids,
103
+ past_key_values=None,
104
+ use_cache=False,
105
+ position_embeddings=position_embeddings,
106
+ **kwargs,
107
+ )
108
+ if isinstance(hidden_states, tuple): # older transformers returns (hidden,)
109
+ hidden_states = hidden_states[0]
110
+ hidden_states = model.norm(hidden_states)
111
+ logits = self.inner.lm_head(hidden_states)
112
+ return CausalLMOutputWithPast(logits=logits)
113
+
114
+
115
+ def make_shared_factory(*, repeat=2):
116
+ """``model_factory`` for pear15.scratch_train.run_training (identity seam).
117
+
118
+ The returned callable has a deterministic ``__qualname__`` so the trainer's
119
+ checkpoint identity (``model_factory`` field) is stable across sessions for
120
+ the same repeat factor, and distinct from the main campaign's factory.
121
+ """
122
+
123
+ def factory(raw_config):
124
+ return build_shared_model(raw_config, repeat=repeat, attention_backend="sdpa")
125
+
126
+ factory.__module__ = "pear15.shared_model"
127
+ factory.__qualname__ = f"make_shared_factory.<locals>.shared_blocks_x{repeat}_factory"
128
+ return factory