File size: 7,214 Bytes
fb9b912
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// The Space's data, from the folder build.py writes (beam_schema.space's format), and where each expert sits on the
// map. No DOM and no three.js here, so node can test it.
//
// A layer is always the model's own index, 0 to 51. Dense layers have no experts and draw as plain sheets; each MoE
// layer is a GRID x GRID sheet whose cell for expert e is layout[layer][e] = row * GRID + col.

// geometry: layers run left to right along x; a sheet stands in the y-z plane
export const SHEET = 4.2, GAP = 1.9, SHEET_Y0 = 0.7, ATTN_DX = -0.62, MLP_DX = 0.18;
export const layerX = l => l * GAP;

export function parseId(s) {
  const m = /^\s*L\s*(\d+)\s*[E\s,/.:-]\s*E?\s*(\d+)\s*$/i.exec(String(s));
  return m ? { layer: +m[1], expert: +m[2] } : null;
}
export const idOf = (layer, expert) => `L${layer}E${expert}`;

// check what the page relies on and refuse anything else; the Space reads only a public folder
export function checkSpace(arch, layout, cardsByLayer) {
  if (arch.public !== true) throw new Error("data/arch.json is not public; the Space reads only a folder written with public=True");
  const { n_layers: L, n_experts: N, grid: G } = arch, moe = arch.moe_layers, dense = arch.dense_layers;
  if (G * G !== N) throw new Error(`grid ${G} does not hold ${N} experts`);
  const all = [...dense, ...moe].sort((a, b) => a - b);
  if (all.length !== L || all.some((l, i) => l !== i)) throw new Error("dense and MoE layers must cover 0 to n_layers - 1 once");
  for (const l of moe) {
    const cells = layout[l], cards = cardsByLayer[l];
    if (!cells || cells.length !== N || new Set(cells).size !== N || cells.some(c => !(c >= 0 && c < N) || c !== Math.floor(c)))
      throw new Error(`layout of layer ${l} is not a permutation of 0..${N - 1}`);
    if (!cards || cards.length !== N || cards.some((c, e) => c.id !== idOf(l, e)))
      throw new Error(`cards of layer ${l} must be its ${N} experts in order`);
  }
}

// getJson(path) -> parsed JSON; the folder's own paths, relative to its root
export async function loadSpace(getJson) {
  const arch = await getJson("arch.json");
  const raw = await getJson("layout.json");
  const layout = {};
  for (const k of Object.keys(raw)) layout[+k] = raw[k];
  const rows = await Promise.all(arch.moe_layers.map(l => getJson(`experts/L${l}.json`)));
  const cardsByLayer = {};
  arch.moe_layers.forEach((l, i) => { cardsByLayer[l] = rows[i]; });
  checkSpace(arch, layout, cardsByLayer);
  return makeSpace(arch, layout, cardsByLayer);
}

export function makeSpace(arch, layout, cardsByLayer) {
  const { n_layers: L, n_experts: N, grid: G } = arch, moe = arch.moe_layers, moe0 = moe[0];
  const isMoe = new Set(moe);
  // flat index, for arrays only: one point per expert, MoE layers in order
  const flat = (layer, e) => (layer - moe0) * N + e;
  const byFlat = i => ({ layer: moe0 + Math.floor(i / N), expert: i % N });
  const card = (layer, e) => (isMoe.has(layer) && e >= 0 && e < N ? cardsByLayer[layer][e] : null);
  const cell = (layer, e) => layout[layer][e];
  // row 0 at the top of the sheet and column 0 at its left, seen face on from +x (as the layer view sees it)
  const cellPos = (layer, c) => {
    const col = c % G, row = Math.floor(c / G);
    return [layerX(layer) + MLP_DX, SHEET_Y0 + (1 - row / (G - 1)) * SHEET, (0.5 - col / (G - 1)) * SHEET];
  };
  const expertPos = (layer, e) => cellPos(layer, cell(layer, e));
  const sheets = Array.from({ length: L }, (_, l) => ({ layer: l, kind: isMoe.has(l) ? "moe" : "dense", x: layerX(l) + MLP_DX }));
  const nPoints = moe.length * N;
  const positions = new Float32Array(nPoints * 3);
  for (const l of moe) for (let e = 0; e < N; e++) positions.set(expertPos(l, e), flat(l, e) * 3);

  // who links into each expert: the reverse of every card's links
  const inbound = new Map();
  for (const l of moe) for (const c of cardsByLayer[l]) for (const k of c.links || []) {
    if (!inbound.has(k.to)) inbound.set(k.to, []);
    inbound.get(k.to).push({ from: c.id, w: k.w });
  }
  for (const v of inbound.values()) v.sort((a, b) => b.w - a.w);

  // what the data offers to colour and rank by: always freq; the rest only where some card has it
  const lights = new Set(), domains = new Set();
  let hasEntropy = false, hasScore = false;
  for (const l of moe) for (const c of cardsByLayer[l]) {
    for (const k of Object.keys(c.lights || {})) lights.add(k);
    for (const k of Object.keys(c.domains || {})) domains.add(k);
    if (c.entropy != null) hasEntropy = true;
    if (c.label_score != null) hasScore = true;
  }
  const measures = [{ key: "freq", name: "routing share" }];
  if (hasScore) measures.push({ key: "label_score", name: "label score" });
  if (hasEntropy) measures.push({ key: "entropy", name: "token entropy" });
  for (const d of [...domains].sort()) measures.push({ key: `domain:${d}`, name: `domain · ${d}` });
  for (const k of [...lights].sort()) measures.push({ key: `light:${k}`, name: `light · ${k}` });

  return { arch, layout, cardsByLayer, flat, byFlat, card, cell, cellPos, expertPos, sheets, nPoints, positions,
    inbound: id => inbound.get(id) || [], measures, uniform: arch.top_k / N };
}

// one card's value on a measure, or null where it has none
export function measure(c, key) {
  if (key === "freq") return c.freq;
  if (key === "label_score") return c.label_score ?? null;
  if (key === "entropy") return c.entropy ?? null;
  if (key.startsWith("domain:")) return c.domains?.[key.slice(7)] ?? null;
  if (key.startsWith("light:")) return c.lights?.[key.slice(6)] ?? null;
  return null;
}

// each point's brightness on a measure, 0..1, or -1 where the card has no value; routing share is on a log scale
// around the uniform share (top_k / n_experts), the rest by rank within the whole model
export function shade(space, key) {
  const out = new Float32Array(space.nPoints).fill(-1), vals = [];
  for (const l of space.arch.moe_layers) space.cardsByLayer[l].forEach((c, e) => {
    const v = measure(c, key);
    if (v != null && Number.isFinite(v)) vals.push([space.flat(l, e), v]);
  });
  if (key === "freq") {
    const u = space.uniform;
    for (const [i, v] of vals) out[i] = Math.max(0, Math.min(1, 0.5 + Math.log2(Math.max(v, 1e-9) / u) / 6));
    return out;
  }
  vals.sort((a, b) => a[1] - b[1]);
  vals.forEach(([i], r) => { out[i] = vals.length > 1 ? r / (vals.length - 1) : 1; });
  return out;
}

// the ranked list: cards in scope (one layer, or null for all), filtered by text, highest first on the measure
export function rank(space, key, layer = null, q = "") {
  const want = String(q).trim().toLowerCase(), pid = parseId(want), out = [];
  for (const l of layer == null ? space.arch.moe_layers : [layer]) for (const c of space.cardsByLayer[l] || []) {
    const v = measure(c, key);
    if (v == null) continue;
    if (want) {
      const hit = pid ? c.id === idOf(pid.layer, pid.expert)
        : c.id.toLowerCase() === want || (c.label || "").toLowerCase().includes(want) || (c.top_tokens || []).some(t => t.toLowerCase().includes(want));
      if (!hit) continue;
    }
    out.push({ id: c.id, layer: l, expert: +c.id.slice(c.id.indexOf("E") + 1), v, card: c });
  }
  return out.sort((a, b) => b.v - a.v);
}