File size: 17,117 Bytes
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbe1c17
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7e2049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e3ceca
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
 
 
 
 
 
 
da0bf36
fbe1c17
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
 
 
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec7310
da0bf36
4ec7310
da0bf36
4ec7310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
fbe1c17
 
 
 
 
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b30e32
 
 
da0bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Trainable router shell for the frozen Fable host and frozen donor experts.

The production campaign keeps host and expert tensors immutable.  This module
adds an explicit host-only route, a bounded expert residual, deterministic
forced routes for counterfactual discovery, and state helpers for the small
router-only checkpoints.
"""
from __future__ import annotations

import contextlib
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint


PROJECTIONS = ("gate_proj", "up_proj", "down_proj")


def inverse_softplus(value: float) -> float:
    if value <= 0:
        raise ValueError("softplus target must be positive")
    return math.log(math.expm1(value))


class FrozenSwiGLUExpert(nn.Module):
    def __init__(self, hidden_size: int = 2048, intermediate_size: int = 512):
        super().__init__()
        self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta")
        self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta")
        self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, device="meta")

    def materialize(self, weights: dict[str, torch.Tensor], device: torch.device, dtype: torch.dtype) -> None:
        for name in PROJECTIONS:
            tensor = weights[f"{name}.weight"].to(device=device, dtype=dtype, non_blocking=True)
            module = getattr(self, name)
            module.weight = nn.Parameter(tensor, requires_grad=False)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        if self.gate_proj.weight.device == hidden_states.device:
            return self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))

        # Free 16 GiB runtimes cannot safely keep the 6.04 GiB frozen donor
        # bank beside the 5.3 GiB host and long-context activations.  The
        # expert branch is detached by FrozenExpertRouterBlock, so immutable
        # projections can be staged one active expert at a time without
        # retaining a weight-gradient graph.  This preserves arithmetic: bank
        # tensors are cast to the same device/dtype used by resident experts.
        device, dtype = hidden_states.device, hidden_states.dtype
        gate_weight = self.gate_proj.weight.to(device=device, dtype=dtype)
        up_weight = self.up_proj.weight.to(device=device, dtype=dtype)
        activated = F.silu(F.linear(hidden_states, gate_weight)) * F.linear(hidden_states, up_weight)
        del gate_weight, up_weight
        down_weight = self.down_proj.weight.to(device=device, dtype=dtype)
        output = F.linear(activated, down_weight)
        del down_weight
        return output


class ExplicitOffRouter(nn.Module):
    """Expert logits plus a fixed zero-logit host-only class.

    The off class is explicit in the classification/ranking objective but adds
    no new trainable parameter beyond the frozen contract's router gate.
    """

    def __init__(self, hidden_size: int, num_experts: int):
        super().__init__()
        self.gate = nn.Linear(hidden_size, num_experts, bias=False)
        nn.init.normal_(self.gate.weight, mean=0.0, std=0.01)
        self.num_experts = num_experts

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        # Router and scale are the only trainable parameters.  Keep their
        # master precision at FP32 even when the frozen host and experts run in
        # FP16; casting this tiny trainable gate to FP16 caused its task-loss
        # gradient to underflow to exactly zero on T4.
        expert_logits = self.gate(hidden_states.to(self.gate.weight.dtype))
        off_logits = torch.zeros(
            (*expert_logits.shape[:-1], 1),
            dtype=expert_logits.dtype,
            device=expert_logits.device,
        )
        return torch.cat((expert_logits, off_logits), dim=-1)


@dataclass
class RouteTrace:
    logits: torch.Tensor
    selected_experts: torch.Tensor
    selected_weights: torch.Tensor
    off_probability: torch.Tensor
    active_scale: torch.Tensor
    host_std: torch.Tensor
    donor_input_std: torch.Tensor
    expert_std: torch.Tensor
    normalization_factor: torch.Tensor
    residual_std: torch.Tensor
    residual_max_abs: torch.Tensor
    post_add_changed: torch.Tensor


class FrozenExpertRouterBlock(nn.Module):
    """A sparse, bounded residual over one frozen host layer output."""

    def __init__(
        self,
        expert_ids: list[int],
        *,
        hidden_size: int = 2048,
        intermediate_size: int = 512,
        top_k: int = 2,
        initial_scale: float = 0.005,
        maximum_scale: float = 0.1,
        donor_input_normalization: str = "none",
        donor_norm_eps: float = 1e-6,
    ):
        super().__init__()
        if len(expert_ids) != 32 or len(set(expert_ids)) != 32:
            raise ValueError("a frozen bank layer must contain 32 unique experts")
        if not 1 <= top_k <= len(expert_ids):
            raise ValueError("top_k is outside the expert bank")
        self.expert_ids = tuple(int(item) for item in expert_ids)
        self.router = ExplicitOffRouter(hidden_size, len(expert_ids))
        self.experts = nn.ModuleList(
            FrozenSwiGLUExpert(hidden_size, intermediate_size) for _ in expert_ids
        )
        self.expert_scale = nn.Parameter(torch.tensor(inverse_softplus(initial_scale)))
        self.top_k = top_k
        self.maximum_scale = float(maximum_scale)
        if donor_input_normalization not in {"none", "unit_rms", "donor_rms"}:
            raise ValueError("unsupported donor input normalization")
        self.donor_input_normalization = donor_input_normalization
        self.donor_norm_eps = float(donor_norm_eps)
        self.register_buffer("donor_norm_weight", torch.ones(hidden_size), persistent=False)
        self._donor_norm_loaded = donor_input_normalization != "donor_rms"
        self.donor_norm_weight_transform: str | None = None
        self.enabled = True
        self.checkpoint_enabled = False
        self._forced_expert: int | None = None
        self._forced_scale: float | None = None
        self.last_trace: RouteTrace | None = None

    @property
    def off_class_index(self) -> int:
        return len(self.expert_ids)

    @contextlib.contextmanager
    def forced_route(self, local_expert: int | None, scale: float = 0.025) -> Iterator[None]:
        if local_expert is not None and not 0 <= local_expert < len(self.expert_ids):
            raise ValueError("forced expert index is outside the local bank")
        old_expert, old_scale = self._forced_expert, self._forced_scale
        self._forced_expert, self._forced_scale = local_expert, float(scale)
        try:
            yield
        finally:
            self._forced_expert, self._forced_scale = old_expert, old_scale

    def load_router_warmstart(self, weight: torch.Tensor) -> None:
        if tuple(weight.shape) != tuple(self.router.gate.weight.shape):
            raise ValueError(
                f"router warm-start shape {tuple(weight.shape)} does not match "
                f"{tuple(self.router.gate.weight.shape)}"
            )
        with torch.no_grad():
            self.router.gate.weight.copy_(weight.to(self.router.gate.weight))

    def load_donor_norm(
        self,
        weight: torch.Tensor,
        *,
        device: torch.device,
        dtype: torch.dtype,
        stored_weight_transform: str,
    ) -> None:
        if tuple(weight.shape) != tuple(self.donor_norm_weight.shape):
            raise ValueError(f"donor RMSNorm shape mismatch: {tuple(weight.shape)}")
        if stored_weight_transform == "one_plus_stored_delta":
            effective_weight = 1.0 + weight.float()
        elif stored_weight_transform == "identity":
            effective_weight = weight.float()
        else:
            raise ValueError(f"unsupported donor RMSNorm stored-weight transform: {stored_weight_transform}")
        self.donor_norm_weight = effective_weight.to(device=device, dtype=dtype).contiguous()
        self.donor_norm_weight_transform = stored_weight_transform
        self._donor_norm_loaded = True

    def materialize_experts(
        self,
        bank_path: Path,
        layer: int,
        *,
        device: torch.device,
        dtype: torch.dtype,
    ) -> None:
        from safetensors import safe_open

        with safe_open(str(bank_path), framework="pt", device="cpu") as bank:
            for local_index, global_expert in enumerate(self.expert_ids):
                prefix = f"model.layers.{layer}.mlp.experts.{global_expert}"
                weights = {
                    f"{projection}.weight": bank.get_tensor(f"{prefix}.{projection}.weight")
                    for projection in PROJECTIONS
                }
                self.experts[local_index].materialize(weights, device, dtype)
        for parameter in self.experts.parameters():
            parameter.requires_grad_(False)

    def _expert_output(
        self,
        flat: torch.Tensor,
        selected: torch.Tensor,
        weights: torch.Tensor,
    ) -> torch.Tensor:
        output = torch.zeros_like(flat)
        detached = flat.detach()
        for local_index, expert in enumerate(self.experts):
            positions = (selected == local_index).nonzero(as_tuple=False)
            if positions.numel() == 0:
                continue
            token_indices, rank_indices = positions.unbind(dim=1)
            expert_values = expert(detached.index_select(0, token_indices)).detach()
            weighted = expert_values * weights[token_indices, rank_indices].unsqueeze(-1)
            output = output.index_add(0, token_indices, weighted)
        return output

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        if not self.enabled:
            self.last_trace = None
            return hidden_states
        original_shape = hidden_states.shape
        flat = hidden_states.reshape(-1, original_shape[-1])
        donor_input = flat
        if self.donor_input_normalization in {"unit_rms", "donor_rms"}:
            if not self._donor_norm_loaded:
                raise RuntimeError("exact donor RMSNorm weight was not loaded")
            norm_weight = self.donor_norm_weight.float() if self.donor_input_normalization == "donor_rms" else None
            donor_input = F.rms_norm(
                flat.float(), (flat.shape[-1],), weight=norm_weight, eps=self.donor_norm_eps
            ).to(flat.dtype)
        logits = self.router(donor_input)

        if self._forced_expert is not None:
            selected = torch.full(
                (flat.shape[0], 1), self._forced_expert, dtype=torch.long, device=flat.device
            )
            weights = torch.ones((flat.shape[0], 1), dtype=flat.dtype, device=flat.device)
            off_probability = torch.zeros(flat.shape[0], dtype=flat.dtype, device=flat.device)
            scale = torch.as_tensor(self._forced_scale, dtype=flat.dtype, device=flat.device)
        else:
            probabilities = torch.softmax(logits.float(), dim=-1).to(flat.dtype)
            expert_probabilities = probabilities[:, :-1]
            weights, selected = expert_probabilities.topk(self.top_k, dim=-1)
            off_probability = probabilities[:, -1]
            scale = torch.clamp(F.softplus(self.expert_scale), max=self.maximum_scale).to(flat.dtype)

        expert_output = self._expert_output(donor_input, selected, weights)
        host_std = flat.float().std().detach().clamp_min(1e-6)
        donor_input_std = donor_input.float().std().detach().clamp_min(1e-6)
        expert_std = expert_output.float().std().detach().clamp_min(1e-6)
        normalization = torch.clamp(host_std / expert_std, max=2.0).to(flat.dtype)
        expert_output = expert_output * normalization
        residual = scale * expert_output
        routed_flat = flat + residual
        self.last_trace = RouteTrace(
            logits,
            selected,
            weights,
            off_probability,
            scale,
            host_std,
            donor_input_std,
            expert_std,
            normalization.detach(),
            residual.float().std().detach(),
            residual.float().abs().max().detach(),
            torch.count_nonzero((routed_flat - flat).detach()),
        )
        return routed_flat.reshape(original_shape)


class AugmentedHostLayer(nn.Module):
    def __init__(self, host_layer: nn.Module, expert_block: FrozenExpertRouterBlock):
        super().__init__()
        self.host_layer = host_layer
        self.expert_block = expert_block
        self.is_attention_layer = getattr(host_layer, "is_attention_layer", False)

    def forward(self, hidden_states: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
        output = self.host_layer(hidden_states, *args, **kwargs)
        if not isinstance(output, torch.Tensor):
            raise TypeError(f"unsupported LFM2 layer output type: {type(output)!r}")
        if self.expert_block.checkpoint_enabled and self.training and torch.is_grad_enabled():
            return checkpoint(
                self.expert_block,
                output,
                use_reentrant=False,
                preserve_rng_state=False,
            )
        return self.expert_block(output)


def attach_router_block(model: nn.Module, layer: int, block: FrozenExpertRouterBlock) -> AugmentedHostLayer:
    layers = model.model.layers
    if not 0 <= layer < len(layers):
        raise ValueError(f"layer {layer} outside host model with {len(layers)} layers")
    wrapper = AugmentedHostLayer(layers[layer], block)
    layers[layer] = wrapper
    return wrapper


def freeze_except_routers(model: nn.Module) -> dict[str, int]:
    counts = {"hostAndExperts": 0, "router": 0, "expertScale": 0, "trainable": 0}
    for name, parameter in model.named_parameters():
        if ".expert_block.router.gate.weight" in name:
            parameter.requires_grad_(True)
            counts["router"] += parameter.numel()
        elif name.endswith(".expert_block.expert_scale"):
            parameter.requires_grad_(True)
            counts["expertScale"] += parameter.numel()
        else:
            parameter.requires_grad_(False)
            counts["hostAndExperts"] += parameter.numel()
        if parameter.requires_grad:
            counts["trainable"] += parameter.numel()
    assert_trainable_isolation(model)
    return counts


def assert_trainable_isolation(model: nn.Module) -> list[str]:
    names = [name for name, parameter in model.named_parameters() if parameter.requires_grad]
    invalid = [
        name
        for name in names
        if ".expert_block.router.gate.weight" not in name
        and not name.endswith(".expert_block.expert_scale")
    ]
    if invalid:
        raise RuntimeError(f"trainable-parameter isolation failed: {invalid[:5]}")
    if not names:
        raise RuntimeError("trainable-parameter isolation found no router parameters")
    return names


def router_state_dict(model: nn.Module) -> dict[str, torch.Tensor]:
    return {
        name: tensor.detach().cpu().contiguous()
        for name, tensor in model.state_dict().items()
        if ".expert_block.router.gate.weight" in name
        or name.endswith(".expert_block.expert_scale")
    }


def load_router_state_dict(model: nn.Module, state: dict[str, torch.Tensor]) -> None:
    expected = set(router_state_dict(model))
    if set(state) != expected:
        raise RuntimeError(
            f"router checkpoint identity mismatch: missing={sorted(expected-set(state))}, "
            f"extra={sorted(set(state)-expected)}"
        )
    current = model.state_dict()
    with torch.no_grad():
        for name, tensor in state.items():
            current[name].copy_(tensor.to(current[name]))


def benefit_targets(host_nll: torch.Tensor, candidate_nll: torch.Tensor, margin: float) -> torch.Tensor:
    """Return the best expert index, or the explicit off class if none earns its cost.

    ``candidate_nll`` is shaped ``[tokens, candidates]`` and must contain
    exact detached counterfactual losses generated outside the served path.
    """
    if host_nll.ndim != 1 or candidate_nll.ndim != 2 or candidate_nll.shape[0] != host_nll.shape[0]:
        raise ValueError("counterfactual NLL shapes are incompatible")
    best_nll, best_index = candidate_nll.min(dim=-1)
    off_index = candidate_nll.shape[-1]
    off = torch.full_like(best_index, off_index)
    return torch.where(best_nll + margin < host_nll, best_index, off)


def benefit_weighted_router_loss(
    logits: torch.Tensor,
    targets: torch.Tensor,
    host_nll: torch.Tensor,
    candidate_nll: torch.Tensor,
) -> torch.Tensor:
    best_nll = candidate_nll.min(dim=-1).values
    benefit = (host_nll - best_nll).clamp_min(0).detach()
    weights = torch.where(targets == logits.shape[-1] - 1, torch.ones_like(benefit), 1 + benefit)
    return (F.cross_entropy(logits.float(), targets, reduction="none") * weights.float()).mean()