File size: 7,848 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Do two runs of real Kimi over the same tokens compute the same thing?

Checking several positions in one sweep must give the tokens real Kimi would write one at a
time. If the two ways of running rounded differently, a discrete choice on the edge could flip:
a token whose two best candidates are tied or, more often, the last of the 16 experts a position
is routed to. Once one expert differs, everything after it differs visibly. This tool finds
where two runs part.

  hkimi sweep STORE --tokens-file T --dump-routing whole.route --dump-logits whole.logits
  hkimi sweep STORE --tokens-file T --split 37,38,39,... --dump-routing steps.route --dump-logits steps.logits
  python3 tools/sweep_diff.py whole.route steps.route --logits whole.logits steps.logits

It prints how many (position, layer) pairs were routed to different experts, the first of them
with the weights of the experts that were swapped, how far the logits are apart before and after
that point, and every position where the two runs would write a different token.

Needs Python 3.8+ and NumPy.
"""
import argparse
import sys

import numpy as np

sys.dont_write_bytecode = True
from routing_stats import load   # noqa: E402

def compare(a, b, logits_a=None, logits_b=None):
    """a, b: routing files as routing_stats.load returns them. logits_*: float32 [P, vocab] or None."""
    if a["P"] != b["P"] or a["M"] != b["M"] or a["k"] != b["k"] or not np.array_equal(a["token"], b["token"]):
        raise ValueError("the two files are not runs over the same tokens of the same model")
    P, M, k = a["P"], a["M"], a["k"]
    ia, ib = np.sort(a["ids"].astype(np.int64), axis=2), np.sort(b["ids"].astype(np.int64), axis=2)
    differs = (ia != ib).any(axis=2)                       # [M, P]: this layer sent this position elsewhere
    out = dict(positions=P, layers=M, k=k, pairs=int(differs.sum()), per_position=differs.sum(axis=0).astype(int),
               swaps=[], top1_differs=[int(p) for p in np.nonzero(a["top1"] != b["top1"])[0]])
    pos_with = np.nonzero(differs.any(axis=0))[0]
    out["first_position"] = int(pos_with[0]) if len(pos_with) else None
    # where the same experts were picked, their weights show how far apart the two runs are numerically
    same = ~differs
    order_a, order_b = np.argsort(a["ids"], axis=2), np.argsort(b["ids"], axis=2)
    wa = np.take_along_axis(a["w"], order_a, axis=2)
    wb = np.take_along_axis(b["w"], order_b, axis=2)
    gap = np.abs(wa - wb).max(axis=2)                      # [M, P]
    out["weight_gap_same"] = float(gap[same].max()) if same.any() else 0.0
    clean = np.ones(P, dtype=bool)                         # positions before anything was routed differently
    if out["first_position"] is not None:
        clean[out["first_position"]:] = False
    out["weight_gap_before"] = float(gap[:, clean].max()) if clean.any() else 0.0
    # the swaps themselves, in the order the model meets them: by position, then by layer
    for p in pos_with:
        for m in np.nonzero(differs[:, p])[0]:
            sa, sb = set(int(v) for v in a["ids"][m, p]), set(int(v) for v in b["ids"][m, p])
            only_a, only_b = sorted(sa - sb), sorted(sb - sa)

            def weights(r, ids):
                row = {int(e): float(w) for e, w in zip(r["ids"][m, p], r["w"][m, p])}
                return [(e, row[e], sorted(row.values()).index(row[e]) + 1) for e in ids]   # expert, weight, rank from the smallest
            out["swaps"].append(dict(position=int(p), layer=int(a["layers"][m]), a=weights(a, only_a), b=weights(b, only_b)))
            if len(out["swaps"]) >= 2000:
                break
        if len(out["swaps"]) >= 2000:
            break
    if logits_a is not None and logits_b is not None:
        d = np.abs(logits_a.astype(np.float64) - logits_b.astype(np.float64)).max(axis=1)      # [P]
        out["logit_gap"] = d
        out["logit_gap_before"] = float(d[clean].max()) if clean.any() else 0.0
        out["logit_gap_after"] = float(d[~clean].max()) if (~clean).any() else 0.0
        top2 = np.sort(logits_a.astype(np.float64), axis=1)[:, -2:]
        out["margin_a"] = top2[:, 1] - top2[:, 0]          # how far run A's first choice is ahead of its second
    return out

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("a", help="routing file of the first run (hkimi sweep --dump-routing)")
    ap.add_argument("b", help="routing file of the second run")
    ap.add_argument("--logits", nargs=2, metavar=("A", "B"), help="the two runs' --dump-logits files")
    ap.add_argument("--names", nargs=2, default=["first run", "second run"], metavar=("A", "B"))
    ap.add_argument("--show", type=int, default=12, help="how many differences to print")
    args = ap.parse_args()
    a, b = load(args.a), load(args.b)
    la = lb = None
    if args.logits:
        la = np.fromfile(args.logits[0], dtype=np.float32).reshape(a["P"], -1)
        lb = np.fromfile(args.logits[1], dtype=np.float32).reshape(b["P"], -1)
    r = compare(a, b, la, lb)
    na, nb = args.names
    P, M = r["positions"], r["layers"]
    print("%d positions, %d layers with experts, %d experts per position and layer" % (P, M, r["k"]))
    print("routed to different experts: %d of %d (position, layer) pairs" % (r["pairs"], P * M))
    if r["first_position"] is None:
        print("the two runs picked the same experts everywhere; their routing weights differ by at most %.1e" % r["weight_gap_same"])
    else:
        hit = int((r["per_position"] > 0).sum())
        print("  %d of %d positions are touched, the first is position %d" % (hit, P, r["first_position"]))
        print("  before that position the routing weights of the two runs differ by at most %.1e" % r["weight_gap_before"])
        print("  the first differences (rank 1 = the smallest of the %d weights at that place):" % r["k"])
        for s in r["swaps"][:args.show]:
            def side(items):
                return ", ".join("expert %d weight %.5f rank %d" % it for it in items)
            print("    position %d, layer %d: %s has %s; %s has %s" % (s["position"], s["layer"], na, side(s["a"]), nb, side(s["b"])))
        last_rank = [it[2] for s in r["swaps"] for it in s["a"] + s["b"]]
        print("  of the %d experts swapped in the differences listed, %d%% carried the smallest or second smallest weight"
              % (len(last_rank), round(100 * float(np.mean(np.array(last_rank) <= 2)))))
    if "logit_gap" in r and r["first_position"] is None:
        print("largest difference between the two runs' logits: %.1e" % r["logit_gap_before"])
    elif "logit_gap" in r:
        print("largest difference between the two runs' logits: %.1e before the first routing difference, %.1e from there on"
              % (r["logit_gap_before"], r["logit_gap_after"]))
    print("positions where the two runs' first choice for the next token differs: %d of %d" % (len(r["top1_differs"]), P))
    for p in r["top1_differs"][:args.show]:
        extra = ""
        if "margin_a" in r:
            extra = ", logits %.3f apart between the runs, %s's first choice %.3f ahead of its second" % (r["logit_gap"][p], na, r["margin_a"][p])
        nxt = ""
        if p + 1 < P:
            which = [n for n, f in ((na, a), (nb, b)) if f["next_rank"][p] == 0]
            nxt = "; the token that follows in the file is the choice of %s" % (" and ".join(which) if which else "neither")
        print("  after position %d: %s says token %d (p %.3f), %s says token %d (p %.3f), routed differently in %d layers there%s%s"
              % (p, na, a["top1"][p], np.exp(a["top1_logp"][p]), nb, b["top1"][p], np.exp(b["top1_logp"][p]),
                 r["per_position"][p], extra, nxt))
    return 0

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