File size: 10,475 Bytes
fc3971e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unstructured Wanda / SparseGPT on SparseMoE expert Linears.

Shapes are unchanged. Only expert `up_gate_proj` and `down_proj` are pruned.
Layer-sequential: prune block i, then re-forward before scoring block i+1.
"""

from __future__ import annotations

import json
import os
import types
from typing import Any

import torch
import torch.nn as nn

from inference.model.dit.dit_module import SparseMoEMLP

from .sparsegpt_full import SparseGPT
from .wanda_unstructured import WrappedGPT, prune_linear_wanda

FORMAT = "davinci_unstructured_v1"
CAPTURE_ENV = "MAGI_UNSTRUCTURED_CAPTURE"
OUT_ROOT_ENV = "MAGI_UNSTRUCTURED_OUT_ROOT"
METHODS_ENV = "MAGI_UNSTRUCTURED_METHODS"
SPARSITIES_ENV = "MAGI_UNSTRUCTURED_SPARSITIES"
STRIDE_ENV = "MAGI_UNSTRUCTURED_STRIDE"
MAX_ENV = "MAGI_UNSTRUCTURED_MAX"
SOURCE_ENV = "MAGI_UNSTRUCTURED_SOURCE_CKPT"

__all__ = [
    "FORMAT",
    "moe_expert_linears",
    "prune_linear_wanda",
    "sequential_unstructured",
    "global_mlp_sparsity",
    "maybe_attach_capture",
    "maybe_prune_captured",
]


def moe_expert_linears(mlp: SparseMoEMLP) -> dict[str, nn.Linear]:
    out: dict[str, nn.Linear] = {}
    for eid, expert in enumerate(mlp.experts):
        out[f"expert{eid}.up_gate_proj"] = expert.up_gate_proj
        out[f"expert{eid}.down_proj"] = expert.down_proj
    return out


def global_mlp_sparsity(model) -> float:
    total = 0
    zeros = 0
    for layer in model.block.layers:
        mlp = getattr(layer, "mlp", None)
        if not isinstance(mlp, SparseMoEMLP):
            continue
        for lin in moe_expert_linears(mlp).values():
            w = lin.weight.data
            total += int(w.numel())
            zeros += int((w == 0).sum())
    return zeros / max(total, 1)


def _run_layer(layer, sample: dict[str, Any]):
    with torch.amp.autocast("cuda", dtype=torch.bfloat16):
        out = layer(
            sample["h"],
            sample["rope"],
            sample["permute_mapping"],
            sample["inv_permute_mapping"],
            sample["varlen_handler"],
            sample["local_attn_handler"],
            sample["modality_dispatcher"],
            sample["cp_split_sizes"],
        )
    return out.detach() if torch.is_tensor(out) else out


def _clone_samples(samples: list[dict[str, Any]]) -> list[dict[str, Any]]:
    cloned = []
    for sample in samples:
        item = dict(sample)
        item["h"] = sample["h"].clone()
        cloned.append(item)
    return cloned


@torch.no_grad()
def sequential_unstructured(
    model,
    samples: list[dict[str, Any]],
    sparsity: float,
    method: str,
    verbose: bool = True,
) -> dict:
    method = method.strip().lower()
    if method not in ("wanda", "sparsegpt"):
        raise ValueError(f"method must be wanda or sparsegpt, got {method}")
    # Grouped GEMM calls F.linear on packed weights and skips nn.Linear.forward,
    # so Wanda/SparseGPT hooks would see nsamples=0 and zero the expert.
    os.environ["MAGI_MOE_GROUPED"] = "off"
    work = _clone_samples(samples)
    layer_meta: dict[str, Any] = {}
    captured_any = False
    for layer_idx, layer in enumerate(model.block.layers):
        mlp = getattr(layer, "mlp", None)
        is_moe = isinstance(mlp, SparseMoEMLP)
        linears = moe_expert_linears(mlp) if is_moe else {}
        wrappers: dict[str, Any] = {}
        handles = []
        if is_moe:
            if method == "wanda":
                wrappers = {name: WrappedGPT(lin) for name, lin in linears.items()}
            else:
                wrappers = {name: SparseGPT(lin) for name, lin in linears.items()}

            def _make_hook(wrapper):
                def _hook(_, inp, out):
                    wrapper.add_batch(inp[0].data, out.data)
                return _hook

            for name, lin in linears.items():
                handles.append(lin.register_forward_hook(_make_hook(wrappers[name])))
            for sample in work:
                _run_layer(layer, sample)
            for handle in handles:
                handle.remove()
            names_meta = {}
            layer_ns = [int(wrappers[name].nsamples) for name in linears]
            if sum(layer_ns) == 0:
                raise RuntimeError(
                    f"unstructured {method} layer {getattr(mlp, 'layer_idx', layer_idx)} "
                    "captured 0 expert activations; MAGI_MOE_GROUPED must be off"
                )
            captured_any = True
            for name, lin in linears.items():
                nsamples = int(wrappers[name].nsamples)
                if nsamples == 0:
                    names_meta[name] = {
                        "sparsity": 0.0,
                        "shape": list(lin.weight.shape),
                        "nsamples": 0,
                        "skipped": True,
                    }
                    if hasattr(wrappers[name], "free"):
                        wrappers[name].free()
                    continue
                if method == "wanda":
                    sp = prune_linear_wanda(lin, wrappers[name].scaler_row, sparsity)
                else:
                    sp = wrappers[name].fasterprune(sparsity, verbose=verbose)
                    wrappers[name].free()
                names_meta[name] = {
                    "sparsity": float(sp),
                    "shape": list(lin.weight.shape),
                    "nsamples": nsamples,
                }
            layer_meta[str(int(getattr(mlp, "layer_idx", layer_idx)))] = names_meta
        for sample in work:
            sample["h"] = _run_layer(layer, sample)
        if verbose and is_moe:
            print(
                f"unstructured {method} layer {getattr(mlp, 'layer_idx', layer_idx)} "
                f"sparsity={sparsity:.3f}",
                flush=True,
            )
        torch.cuda.empty_cache()
    if not captured_any:
        raise RuntimeError(f"unstructured {method} captured 0 expert activations")
    return {
        "method": method,
        "sparsity": float(sparsity),
        "keep_ratio": float(1.0 - sparsity),
        "global_mlp_sparsity": global_mlp_sparsity(model),
        "n_samples": len(samples),
        "layers": layer_meta,
    }


def maybe_attach_capture(model) -> dict | None:
    flag = os.getenv(CAPTURE_ENV, "").strip()
    if flag not in ("1", "true", "True", "yes"):
        return None
    stride = int(os.getenv(STRIDE_ENV, "8") or "8")
    max_samples = int(os.getenv(MAX_ENV, "40") or "40")
    block = model.block
    orig = block.forward
    bag: dict[str, Any] = {"samples": [], "calls": 0, "orig": orig}

    def wrapped(
        self,
        x,
        rope,
        permute_mapping,
        inv_permute_mapping,
        varlen_handler,
        local_attn_handler,
        modality_dispatcher,
        cp_split_sizes,
    ):
        bag["calls"] += 1
        if bag["calls"] % stride == 0 and len(bag["samples"]) < max_samples:
            bag["samples"].append(
                {
                    "h": x.detach().clone(),
                    "rope": rope,
                    "permute_mapping": permute_mapping,
                    "inv_permute_mapping": inv_permute_mapping,
                    "varlen_handler": varlen_handler,
                    "local_attn_handler": local_attn_handler,
                    "modality_dispatcher": modality_dispatcher,
                    "cp_split_sizes": cp_split_sizes,
                }
            )
        return orig(
            x,
            rope,
            permute_mapping,
            inv_permute_mapping,
            varlen_handler,
            local_attn_handler,
            modality_dispatcher,
            cp_split_sizes,
        )

    block.forward = types.MethodType(wrapped, block)
    model._unstr_capture = bag
    print(
        f"unstructured capture stride={stride} max={max_samples}",
        flush=True,
    )
    return bag


def save_unstructured_checkpoint(path: str, model, meta: dict) -> None:
    payload = {
        "format": FORMAT,
        "model": model.state_dict(),
        "unstructured_meta": meta,
    }
    os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
    torch.save(payload, path)


def maybe_prune_captured(model) -> list[str]:
    out_root = os.getenv(OUT_ROOT_ENV, "").strip()
    if not out_root:
        return []
    bag = getattr(model, "_unstr_capture", None)
    if not bag or not bag.get("samples"):
        raise RuntimeError(
            f"{OUT_ROOT_ENV} is set but no TransformerBlock inputs were captured"
        )
    block = model.block
    orig = bag.get("orig")
    if orig is not None:
        block.forward = orig
    methods = [m.strip() for m in os.getenv(METHODS_ENV, "wanda,sparsegpt").split(",") if m.strip()]
    sparsities = [
        float(x) for x in os.getenv(SPARSITIES_ENV, "0.25,0.50,0.75").split(",") if x.strip()
    ]
    source = os.getenv(SOURCE_ENV, "").strip()
    samples = bag["samples"]
    print(
        f"unstructured prune captured={len(samples)} calls={bag.get('calls')} "
        f"methods={methods} sparsities={sparsities}",
        flush=True,
    )
    orig_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
    written: list[str] = []
    os.makedirs(out_root, exist_ok=True)
    for method in methods:
        for sparsity in sparsities:
            keep = 1.0 - float(sparsity)
            slug = f"{method}_unstr_keep{int(round(keep * 100)):03d}"
            out_path = os.path.join(out_root, f"{slug}.pt")
            if os.path.isfile(out_path):
                print(f"[skip prune] {out_path} exists", flush=True)
                written.append(out_path)
                continue
            print(f"unstructured apply {slug}", flush=True)
            model.load_state_dict(orig_state, strict=True)
            meta = sequential_unstructured(
                model, samples, sparsity=float(sparsity), method=method, verbose=True,
            )
            meta["source"] = source
            meta["captured_calls"] = int(bag.get("calls") or 0)
            save_unstructured_checkpoint(out_path, model, meta)
            meta_json = os.path.splitext(out_path)[0] + "_meta.json"
            with open(meta_json, "w", encoding="utf-8") as f:
                json.dump(meta, f, indent=2)
                f.write("\n")
            print(f"wrote {out_path} global_mlp_sparsity={meta['global_mlp_sparsity']:.4f}", flush=True)
            written.append(out_path)
            torch.cuda.empty_cache()
    return written