File size: 3,929 Bytes
f93f1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""trace.py - per-token expert choices for a sample of tokens per domain (gap 5). Built on record.py.

  /srv/venv_hf/bin/python trace.py --texts /srv/prune/data/texts/calib --domains chat,code,... --out /srv/prune/out/gaps/trace \
      --model /srv/prune/models/hf_orig --max-mem-gib 12 --windows 4

Same model loading and text windows as record.py (first --windows 1,024-token windows of each domain's calibration
text). For every token and every layer visit it saves the 8 chosen experts (router output, the same hook record.py uses).
Writes out/trace_<domain>.npz: ids [T] int64, idx [24, 3, T, 8] int16 (-1 for passes a layer does not run),
w [24, 3, T, 8] float16 router weights, plus out/trace_<domain>.tokens.json (token strings, convert_ids_to_tokens).
"""
import argparse
import json
import os
import sys

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from record import WINDOW, domain_windows, load_model, log  # noqa: E402


class Tracer:
    def __init__(self, text_model):
        cfg = text_model.config
        self.layers = text_model.layers
        self.embed_device = text_model.embed_tokens.weight.device
        core = range(cfg.loop_layer_index_start, cfg.loop_layer_index_end)
        self.n_pass = cfg.loop_num_passes
        self.expected = [self.n_pass if i in core else 1 for i in range(len(self.layers))]
        self.count = [0] * len(self.layers)
        self.cur = None
        for i, layer in enumerate(self.layers):
            layer.mlp.register_forward_pre_hook(lambda m, inp, i=i: self._pre(i))
            layer.mlp.gate.register_forward_hook(lambda m, inp, out, i=i: self._router(i, out))

    def _pre(self, i):
        self.count[i] += 1

    def _router(self, i, out):
        p = self.count[i] - 1
        self.cur[0][i, p] = out[2].reshape(-1, out[2].shape[-1]).cpu().numpy().astype(np.int16)
        self.cur[1][i, p] = out[1].reshape(-1, out[1].shape[-1]).float().cpu().numpy().astype(np.float16)

    @torch.no_grad()
    def forward(self, model, ids):
        t = ids.shape[0]
        self.cur = (np.full((len(self.layers), self.n_pass, t, 8), -1, np.int16),
                    np.zeros((len(self.layers), self.n_pass, t, 8), np.float16))
        self.count = [0] * len(self.layers)
        model(input_ids=ids[None].to(self.embed_device), use_cache=False)
        if self.count != self.expected:
            raise RuntimeError(f"MoE call counts {self.count} != expected {self.expected}")
        return self.cur


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--texts", required=True)
    ap.add_argument("--domains", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--model", default="/srv/prune/models/hf_orig")
    ap.add_argument("--max-mem-gib", type=int, default=None)
    ap.add_argument("--windows", type=int, default=4)
    args = ap.parse_args()
    args.tiny_random = False
    from transformers import AutoTokenizer

    os.makedirs(args.out, exist_ok=True)
    tok = AutoTokenizer.from_pretrained(args.model)
    model, text_model = load_model(args)
    tr = Tracer(text_model)
    for d in args.domains.split(","):
        path = os.path.join(args.texts, f"{d}.jsonl")
        if not os.path.exists(path):
            log(f"{d}: no {path}, skipped")
            continue
        win = domain_windows(tok, path, None, args.windows)
        idx, w = zip(*[tr.forward(model, win[c]) for c in range(win.shape[0])])
        ids = win.reshape(-1).numpy()
        np.savez_compressed(os.path.join(args.out, f"trace_{d}.npz"), ids=ids, idx=np.concatenate(idx, 2),
                            w=np.concatenate(w, 2))
        json.dump(tok.convert_ids_to_tokens(ids.tolist()), open(os.path.join(args.out, f"trace_{d}.tokens.json"), "w"))
        log(f"{d}: traced {win.shape[0]} x {WINDOW} tokens")


if __name__ == "__main__":
    sys.exit(main())