File size: 11,317 Bytes
2594d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Physical narrow E8T1 FFN with one always-on shared expert.

The original H3 block applies its AdaLN gate *after* calling this module.
Consequently the selected FFN output remains a drop-in replacement for
``MiniMaxH3MLP`` and the block's existing router auxiliary plumbing works.
"""
from __future__ import annotations

from contextlib import nullcontext

from typing import Iterable
import warnings

import torch
from torch import nn
from torch.func import functional_call
import torch.nn.functional as F

from diffsynth.models.minimax_h3_dit import MiniMaxH3MLP


def _full_parameters(params):
    """Expose full weights during channel copying under ZeRO-3."""
    if any(hasattr(p, "ds_id") for p in params):
        import deepspeed
        return deepspeed.zero.GatheredParameters(params, modifier_rank=0)
    return nullcontext()


class SharedE8T1MLP(nn.Module):
    def __init__(self, hidden_size: int, shared_width: int, private_width: int,
                 num_experts: int = 8, temperature: float = 1.0,
                 eesd_tokens: int = 128):
        super().__init__()
        if num_experts != 8 or min(shared_width, private_width) < 1:
            raise ValueError("E8T1 needs eight nonempty private experts and a shared expert")
        self.shared = MiniMaxH3MLP(hidden_size, shared_width)
        self.experts = nn.ModuleList(
            MiniMaxH3MLP(hidden_size, private_width) for _ in range(num_experts)
        )
        self.router = nn.Linear(hidden_size, num_experts, bias=False)
        self.temperature = float(temperature)
        self.eesd_tokens = int(eesd_tokens)
        self.ema_decay = 0.999
        self._ema: dict[str, torch.Tensor] = {}
        self._eesd_loss: torch.Tensor | None = None
        self._warned_zero3_ema = False
        self._disable_ema_for_zero3 = False
        self._route_counts = torch.zeros(num_experts, dtype=torch.long)
        self._last_route_counts = torch.zeros(num_experts, dtype=torch.long)

    @property
    def executed_width(self) -> int:
        return self.shared.fc2.in_features + self.experts[0].fc2.in_features

    def init_ema(self) -> None:
        """Track only trainable LoRA/router weights, never a second dense FFN."""
        self._ema = {
            name: p.detach().clone() for name, p in self.named_parameters()
            if p.requires_grad and ("lora_" in name or name == "router.weight")
        }

    def _apply(self, fn):
        super()._apply(fn)
        self._ema = {name: fn(value) for name, value in self._ema.items()}
        return self

    @torch.no_grad()
    def update_ema(self) -> None:
        params = dict(self.named_parameters())
        for name, old in self._ema.items():
            old.lerp_(params[name].detach().to(old.dtype), 1 - self.ema_decay)

    def _ema_call(self, module: nn.Module, prefix: str, x: torch.Tensor) -> torch.Tensor:
        overrides = {
            name[len(prefix):]: value
            for name, value in self._ema.items() if name.startswith(prefix)
        }
        return functional_call(module, overrides, (x,), strict=False) if overrides else module(x)

    def _eesd(self, x: torch.Tensor, probs: torch.Tensor,
              student: torch.Tensor) -> torch.Tensor:
        # DeepSpeed ZeRO-3 installs parameter-fetch hooks on every linear.
        # functional_call substitutes plain EMA tensors, which lack ds_status
        # and cannot be fetched by those hooks. The EMA consistency term is
        # therefore disabled for this ZeRO-3 feasibility run; the teacher
        # anchor, FlowMatch, and router balance losses remain active.
        if self._disable_ema_for_zero3 or hasattr(self.router.weight, "ds_status"):
            if not self._warned_zero3_ema:
                warnings.warn("EESD EMA term disabled under ZeRO-3 parameter partitioning")
                self._warned_zero3_ema = True
            return x.new_zeros(())
        n = min(self.eesd_tokens, x.shape[0])
        if n == 0 or not self._ema:
            return x.new_zeros(())
        k = n // 2
        entropy = -(probs * probs.clamp_min(1e-9).log()).sum(-1)
        high = entropy.topk(k, sorted=False).indices if k else x.new_empty((0,), dtype=torch.long)
        random = torch.randperm(x.shape[0], device=x.device)[: n - k]
        idx = torch.unique(torch.cat((high, random)))
        with torch.no_grad():
            xs = x[idx]
            er = self._ema.get("router.weight", self.router.weight.detach())
            ep = F.softmax(F.linear(F.normalize(xs.float(), dim=-1), er.float()) / self.temperature, -1)
            soft = self._ema_call(self.shared, "shared.", xs).float()
            for e, expert in enumerate(self.experts):
                soft = soft + ep[:, e:e + 1] * self._ema_call(expert, f"experts.{e}.", xs).float()
        return F.mse_loss(student[idx].float(), soft)

    def forward(self, x: torch.Tensor):
        if x.ndim != 2:
            raise ValueError(f"expected packed [tokens,hidden], got {tuple(x.shape)}")
        # ZeRO/Accelerate may cast the router parameter to bf16 during prepare.
        # Keep the routing scores in fp32 and let autograd cast the weight grad
        # back to the parameter dtype.
        logits = F.linear(F.normalize(x.float(), dim=-1), self.router.weight.float()) / self.temperature
        probs = F.softmax(logits, dim=-1)
        chosen = logits.argmax(-1)
        out = self.shared(x)
        for expert_id, expert in enumerate(self.experts):
            indices = torch.nonzero(chosen == expert_id, as_tuple=True)[0]
            if indices.numel() == 0:
                # Every rank must traverse every trainable expert. Otherwise
                # ZeRO-2 can see different gradient hooks on different ranks
                # and stall in its partition/reduction epilogue.
                out = out + expert(x[:0]).sum().to(out.dtype) * 0
                continue
            part = expert(x.index_select(0, indices))
            if self.training and torch.is_grad_enabled():
                p = probs.index_select(0, indices)[:, expert_id]
                part = part * (1 + p - p.detach()).to(part.dtype).unsqueeze(-1)
            out = out.index_add(0, indices, part)
        with torch.no_grad():
            self._last_route_counts = torch.bincount(chosen.detach().cpu(), minlength=8)
            self._route_counts += self._last_route_counts
        if not (self.training and torch.is_grad_enabled()):
            self._eesd_loss = None
            return out
        hard_fraction = torch.bincount(chosen, minlength=8).float() / max(1, x.shape[0])
        balance = 8 * (hard_fraction.detach() * probs.mean(0)).sum()
        entropy = -(probs * probs.clamp_min(1e-9).log()).sum(-1).mean()
        self._eesd_loss = self._eesd(x, probs, out)
        return out, balance, entropy.detach(), (chosen != 0).float().mean().detach()


def apply_shared_e8t1(dit: nn.Module, init: dict, layers: Iterable[int] = range(15, 35)):
    """Replace exactly the requested middle FFNs using copied dense neuron triplets."""
    layers = tuple(layers)
    if layers != tuple(range(15, 35)):
        raise ValueError("pilot is fixed to H3 blocks 15..34")
    for layer in layers:
        dense = dit.blocks[layer].mlp
        if not isinstance(dense, MiniMaxH3MLP):
            raise TypeError(f"block {layer}: expected dense MiniMaxH3MLP")
        spec = init[str(layer)]
        shared_idx = torch.as_tensor(spec["shared_indices"], dtype=torch.long)
        private_idx = [torch.as_tensor(v, dtype=torch.long) for v in spec["private_indices"]]
        if len(private_idx) != 8 or any(len(v) != len(private_idx[0]) for v in private_idx):
            raise ValueError(f"block {layer}: malformed private indices")
        if len(shared_idx) + len(private_idx[0]) >= dense.fc2.in_features:
            raise ValueError(f"block {layer}: no activated width reduction")
        moe = SharedE8T1MLP(dense.fc1.in_features, len(shared_idx), len(private_idx[0]),
                             temperature=float(spec.get("temperature", 1.0)))
        moe.to(device=dense.fc1.weight.device, dtype=dense.fc1.weight.dtype)
        moe.router.to(dtype=torch.float32)
        width = dense.fc2.in_features
        # ZeRO-3 may expose only an empty placeholder on each rank here. Gather
        # the two dense weights before selecting physical neuron triplets.
        with _full_parameters((dense.fc1.weight, dense.fc2.weight)):
            fc1_weight = dense.fc1.weight.dequantize()
            fc2_weight = dense.fc2.weight.dequantize()
            def copy_neurons(dst, ids):
                ids = ids.to(fc1_weight.device)
                with _full_parameters((dst.fc1.weight, dst.fc2.weight)), torch.no_grad():
                    dst.fc1.weight.copy_(torch.cat((fc1_weight[ids], fc1_weight[width + ids])))
                    dst.fc2.weight.copy_(fc2_weight[:, ids])
            copy_neurons(moe.shared, shared_idx)
            for dst, ids in zip(moe.experts, private_idx):
                copy_neurons(dst, ids)
        center = torch.as_tensor(spec["router_centers"], dtype=torch.float32, device=moe.router.weight.device)
        if center.shape != moe.router.weight.shape:
            raise ValueError(f"block {layer}: router center shape {center.shape}")
        with _full_parameters((moe.router.weight,)), torch.no_grad():
            moe.router.weight.copy_(F.normalize(center, dim=-1).to(moe.router.weight.dtype))
        dit.blocks[layer].mlp = moe
    dit.moe_layers = layers
    dit.moe_kind = "shared_e8t1"
    dit.num_experts = 8
    dit.moe_balance_reduce = "mean"
    return dit


def ema_loss(dit: nn.Module) -> torch.Tensor:
    losses = [dit.blocks[i].mlp._eesd_loss for i in dit.moe_layers]
    losses = [v for v in losses if v is not None]
    return torch.stack(losses).mean() if losses else next(dit.parameters()).new_zeros(())


def route_histogram(dit: nn.Module) -> dict[int, list[int]]:
    return {i: dit.blocks[i].mlp._route_counts.tolist() for i in dit.moe_layers}


def apply_narrow_ffn(dit: nn.Module, init: dict, layers: Iterable[int] = range(15, 35)):
    layers = tuple(layers)
    if layers != tuple(range(15, 35)):
        raise ValueError("pilot is fixed to H3 blocks 15..34")
    for layer in layers:
        dense = dit.blocks[layer].mlp
        spec = init[str(layer)]
        ids = torch.as_tensor(spec["narrow_indices"], dtype=torch.long, device=dense.fc1.weight.device)
        width = dense.fc2.in_features
        expected = len(spec["shared_indices"]) + len(spec["private_indices"][0])
        if len(ids) != expected or len(ids) >= width:
            raise ValueError(f"block {layer}: invalid narrow FFN width")
        narrow = MiniMaxH3MLP(dense.fc1.in_features, len(ids)).to(
            device=dense.fc1.weight.device, dtype=dense.fc1.weight.dtype)
        with _full_parameters((dense.fc1.weight, dense.fc2.weight)), \
             _full_parameters((narrow.fc1.weight, narrow.fc2.weight)), torch.no_grad():
            fc1_weight = dense.fc1.weight.dequantize()
            fc2_weight = dense.fc2.weight.dequantize()
            narrow.fc1.weight.copy_(torch.cat((fc1_weight[ids], fc1_weight[width + ids])))
            narrow.fc2.weight.copy_(fc2_weight[:, ids])
        dit.blocks[layer].mlp = narrow
    dit.moe_layers = layers
    dit.moe_kind = "narrow_ffn"
    return dit