File size: 5,865 Bytes
6ec9472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Capture real per-token expert routing traces from OLMoE and derive the
statistics that drive the expert-cache model: activation-frequency skew,
temporal reuse, and cross-layer predictability.
"""
import json, os, sys, time
import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

sys.path.insert(0, os.path.dirname(__file__))
import data

MODEL = "allenai/OLMoE-1B-7B-0924"
DEV = "cuda"
RES = os.path.join(os.path.dirname(__file__), "..", "results")


@torch.no_grad()
def trace(nseq=24, seqlen=2048):
    tok = AutoTokenizer.from_pretrained(MODEL)
    model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.bfloat16,
                                                 low_cpu_mem_usage=True)
    model.eval(); model.config.use_cache = False
    L = model.config.num_hidden_layers
    E = model.config.num_experts
    K = model.config.num_experts_per_tok

    picks = {l: [] for l in range(L)}
    hooks = []

    def mk(l):
        def fn(mod, inp, out):
            logits = out[0] if isinstance(out, tuple) else out
            top = logits.float().reshape(-1, E).topk(K, dim=-1).indices
            picks[l].append(top.to(torch.int16).cpu())
        return fn

    for l, layer in enumerate(model.model.layers):
        hooks.append(layer.mlp.gate.register_forward_hook(mk(l)))

    tests = data.test_tokens(tok, seqlen)[:nseq]
    model.model.embed_tokens.to(DEV); model.model.rotary_emb.to(DEV)
    model.model.norm.to(DEV)
    for i, b in enumerate(tests):
        b = b.to(DEV)
        hs = model.model.embed_tokens(b)
        pos = torch.arange(seqlen, device=DEV).unsqueeze(0)
        pe = model.model.rotary_emb(hs, pos)
        for layer in model.model.layers:
            layer.to(DEV)
            hs = layer(hs, attention_mask=None, position_ids=pos,
                       position_embeddings=pe)
            hs = hs[0] if isinstance(hs, tuple) else hs
            layer.to("cpu")
            torch.cuda.empty_cache()
        print(f"  seq {i+1}/{len(tests)}", flush=True)
    for h in hooks:
        h.remove()

    T = torch.stack([torch.cat(picks[l]) for l in range(L)])   # [L, tokens, K]
    np.save(os.path.join(RES, "routing_trace.npy"), T.numpy().astype(np.int16))
    print("trace shape", tuple(T.shape))
    return T.numpy().astype(np.int64), L, E, K


def analyse(T, L, E, K):
    ntok = T.shape[1]
    freq = np.zeros((L, E))
    for l in range(L):
        c = np.bincount(T[l].reshape(-1), minlength=E)
        freq[l] = c / c.sum()
    json.dump({str(l): freq[l].tolist() for l in range(L)},
              open(os.path.join(RES, "routing_freq.json"), "w"))

    srt = np.sort(freq, axis=1)[:, ::-1]
    cum = np.cumsum(srt, axis=1)
    out = {
        "tokens": int(ntok), "layers": L, "experts": E, "topk": K,
        "gini": [float(gini(freq[l])) for l in range(L)],
        "mass_top25pct": float(cum[:, E // 4 - 1].mean()),
        "mass_top50pct": float(cum[:, E // 2 - 1].mean()),
        "cum_mean": cum.mean(0).tolist(),
    }

    # temporal reuse: probability an expert used at token t was also used at t-1
    reuse = []
    for l in range(L):
        a = T[l][:-1]; b = T[l][1:]
        m = np.zeros((len(a), E), dtype=bool)
        m[np.arange(len(a))[:, None], a] = True
        hit = m[np.arange(len(b))[:, None], b].sum(1) / K
        reuse.append(float(hit.mean()))
    out["reuse_prev_token"] = reuse

    # working set: distinct experts over a window of W tokens
    ws = {}
    for W in [1, 4, 16, 64, 256, 1024]:
        vals = []
        for l in range(L):
            n = min(len(T[l]) // W, 64)
            for i in range(n):
                vals.append(len(np.unique(T[l][i * W:(i + 1) * W])))
        ws[W] = float(np.mean(vals))
    out["working_set"] = ws
    json.dump(out, open(os.path.join(RES, "routing_stats.json"), "w"), indent=2)
    return out


def gini(p):
    x = np.sort(p)
    n = len(x)
    return float((2 * np.arange(1, n + 1) - n - 1).dot(x) / (n * x.sum()))


def simulate_cache(T, L, E, K, expert_bytes, cache_bytes, freq=None,
                   policy="lru", pin_frac=0.0):
    """Byte-accurate expert cache simulation over the real trace.

    Returns fraction of expert activations served from cache (hit rate) and
    bytes fetched from storage per token.
    """
    cap = int(cache_bytes // expert_bytes)
    if cap <= 0:
        return 0.0, K * L * expert_bytes
    npin = int(cap * pin_frac)
    pinned = set()
    if npin and freq is not None:
        flat = [(freq[l][e], (l, e)) for l in range(L) for e in range(E)]
        flat.sort(reverse=True)
        pinned = {k for _, k in flat[:npin]}
    from collections import OrderedDict
    cache = OrderedDict((k, True) for k in pinned)
    hits = tot = 0
    ntok = T.shape[1]
    for t in range(ntok):
        for l in range(L):
            for e in T[l, t]:
                key = (l, int(e))
                tot += 1
                if key in cache:
                    hits += 1
                    if key not in pinned:
                        cache.move_to_end(key)
                else:
                    cache[key] = True
                    while len(cache) > cap:
                        k0, _ = next(iter(cache.items()))
                        if k0 in pinned:
                            cache.move_to_end(k0)
                            continue
                        cache.popitem(last=False)
    hr = hits / tot
    return hr, (1 - hr) * K * L * expert_bytes


if __name__ == "__main__":
    nseq = int(sys.argv[1]) if len(sys.argv) > 1 else 24
    p = os.path.join(RES, "routing_trace.npy")
    if os.path.exists(p):
        T = np.load(p).astype(np.int64)
        L, E, K = T.shape[0], 64, T.shape[2]
    else:
        T, L, E, K = trace(nseq)
    st = analyse(T, L, E, K)
    print(json.dumps({k: v for k, v in st.items() if k != "cum_mean"}, indent=2))