jeevanpillay's picture
Monitors from inside Beam: the explorer, from lightfastai/beam-entry 8ca9a4b
fb9b912 verified
Raw History Blame Contribute Delete
20.2 kB
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { SHEET, GAP, SHEET_Y0, ATTN_DX, MLP_DX, layerX } from "./data.js";
// The map, after neuron-explorer's map3d.js (lyramakesmusic/neuron-explorer): layers run left to right along x. Each
// layer is the residual stream passing through an attention slab and then its MLP, drawn as a vertical sheet: a
// 16x16 sheet of experts for an MoE layer, a plain sheet for a dense one.
const PAL = {
bg: 0x000000,
idle: new THREE.Color(0.036, 0.046, 0.052), none: new THREE.Color(0.11, 0.13, 0.14),
lo: new THREE.Color(0.42, 0.30, 0.10), hi: new THREE.Color(1.0, 0.71, 0.28), named: new THREE.Color(1, 1, 1),
out: new THREE.Color(0.22, 0.78, 1.0), in: new THREE.Color(1.0, 0.31, 0.6),
wire: 0x1c2a30, wireDense: 0x3a5a66, slabEdge: 0x3c4a52,
};
const qs = new URLSearchParams(location.search);
// overall brightness of the structure (sheets, wires, idle points); data colours keep their hue
const BRIGHT = Number(qs.get("bright")) || 2.5;
for (const k of ["idle", "none", "out", "in", "wire", "wireDense", "slabEdge"]) PAL[k] = new THREE.Color(PAL[k]).multiplyScalar(BRIGHT);
function glowPoints(sizePx, maxScale = 3) {
return new THREE.RawShaderMaterial({
uniforms: { size: { value: sizePx * Math.min(devicePixelRatio, 2) }, ref: { value: 1 }, maxScale: { value: maxScale },
focusX: { value: 0 }, fadeW: { value: 1 }, fadeAmt: { value: 0 }, camSide: { value: 1 }, tdist: { value: 1 } },
vertexShader: `precision highp float;
uniform mat4 modelViewMatrix, projectionMatrix; uniform float size, ref, maxScale, focusX, fadeW, fadeAmt, camSide, tdist;
attribute vec3 position; attribute vec3 color; varying vec3 vC;
void main() { float d = (position.x - focusX) / fadeW;
vec4 mv = modelViewMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * mv;
// the scene brightens as the camera nears its focus, by one factor for every point
float near = clamp(sqrt(ref / tdist), 1.0, 3.5);
// layers away from the focus fade as you zoom in (never below a quarter); layers between the camera and the
// focus fade further, to 40% up close
float front = step(0.45, (position.x - focusX) * camSide / ${GAP.toFixed(3)});
float keep = mix(1.0, exp(-d * d), fadeAmt * 0.75) * mix(1.0, 1.0 - 0.6 * fadeAmt, front);
float sc = clamp(sqrt(ref / -mv.z), 0.6, maxScale), sc0 = clamp(sqrt(ref / tdist), 0.6, maxScale);
vC = color * keep * near * min(1.0, sc0 / sc);
gl_PointSize = size * sc; }`,
fragmentShader: `precision highp float; varying vec3 vC;
void main() { float r = length(gl_PointCoord - 0.5); if (r > 0.5) discard;
float edge = 1.0 - smoothstep(0.38, 0.5, r); gl_FragColor = vec4(vC * edge, 1.0); }`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
});
}
// space: from data.js's makeSpace; cb: { onPick(layer, expert), onHover(pick, x, y), onLayerMode(layer | null) }
export function createMap(canvas, space, cb) {
const { arch } = space, L = arch.n_layers, N = arch.n_experts, moe = arch.moe_layers;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setClearColor(PAL.bg);
const scene = new THREE.Scene();
const V = (x, y, z) => new THREE.Vector3(x, y, z);
const X0 = ATTN_DX - 1.6, X1 = (L - 1) * GAP + MLP_DX + 1.4;
const pos = (layer, e) => V(...space.expertPos(layer, e));
const insets = { left: 410, right: 0 };
let fitPerPx = null;
const camera = new THREE.PerspectiveCamera(32, 1, 0.02, 2000);
let homeDist = 60;
const home = { target: V((L - 1) * GAP / 2, SHEET_Y0 + SHEET / 2 - 0.4, 0), dir: V(0.62, 0.4, 1).normalize() };
camera.position.copy(home.target).addScaledVector(home.dir, homeDist);
const controls = new OrbitControls(camera, canvas);
controls.target.copy(home.target);
controls.enableDamping = false;
controls.zoomToCursor = true;
controls.minDistance = 1.6; controls.maxDistance = 400;
controls.zoomSpeed = 0.6;
controls.update();
// every expert of every MoE layer, one draw call
const col = new Float32Array(space.nPoints * 3);
for (let i = 0; i < space.nPoints; i++) PAL.idle.toArray(col, i * 3);
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.BufferAttribute(space.positions, 3));
geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
const pointMat = glowPoints(3.2, 5);
const points = new THREE.Points(geo, pointMat);
scene.add(points);
// structure: the residual line, each layer's sheet outline and stalks, its attention slab, and a fill for dense sheets
const wires = [], denseWires = [];
const seg = (arr, a, b) => arr.push(a.x, a.y, a.z, b.x, b.y, b.z);
const sheetCorners = x => { const h = SHEET / 2; return [V(x, SHEET_Y0, -h), V(x, SHEET_Y0, h), V(x, SHEET_Y0 + SHEET, h), V(x, SHEET_Y0 + SHEET, -h)]; };
seg(wires, V(X0, 0, 0), V(X1, 0, 0));
const slabs = [], denseSheets = [];
for (const s of space.sheets) {
const l = s.layer, x = layerX(l), mx = s.x, ax = x + ATTN_DX, cs = sheetCorners(mx);
const dense = s.kind === "dense", target = dense ? denseWires : wires;
for (let i = 0; i < 4; i++) seg(target, cs[i], cs[(i + 1) % 4]);
seg(wires, V(ax, 0, 0), V(ax, SHEET_Y0, 0)); seg(wires, V(mx, 0, 0), V(mx, SHEET_Y0, 0));
const slab = new THREE.Mesh(new THREE.BoxGeometry(0.14, SHEET * 0.92, SHEET * 0.92), new THREE.MeshBasicMaterial({
color: 0x7a909b, transparent: true, opacity: 0.055 * BRIGHT, depthWrite: false }));
slab.position.set(ax, SHEET_Y0 + SHEET / 2, 0);
slab.userData = { layer: l, part: "attention" };
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(slab.geometry), new THREE.LineBasicMaterial({ color: PAL.slabEdge, transparent: true }));
edges.position.copy(slab.position);
slab.userData.edges = edges; slab.userData.baseOpacity = slab.material.opacity;
scene.add(slab, edges); slabs.push(slab);
if (dense) {
// a dense MLP is one block of neurons, not experts: a plain filled sheet
const m = new THREE.Mesh(new THREE.PlaneGeometry(SHEET, SHEET), new THREE.MeshBasicMaterial({
color: 0x6f8590, transparent: true, opacity: 0.06 * BRIGHT, depthWrite: false, side: THREE.DoubleSide }));
m.rotation.y = Math.PI / 2; m.position.set(mx, SHEET_Y0 + SHEET / 2, 0);
m.userData = { layer: l, part: "dense", baseOpacity: m.material.opacity };
scene.add(m); denseSheets.push(m);
}
}
const fadeLines = [];
for (const m of [X0, X1].map(() => new THREE.LineBasicMaterial({ color: PAL.slabEdge, transparent: true }))) fadeLines.push(m);
[X0, X1].forEach((x, i) => {
const slab = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(0.14, 1.4, 2.2)), fadeLines[i]);
slab.position.set(x, 0, 0); scene.add(slab);
});
for (const [arr, color] of [[wires, PAL.wire], [denseWires, PAL.wireDense]]) {
const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.Float32BufferAttribute(arr, 3));
const m = new THREE.LineBasicMaterial({ color, transparent: true });
scene.add(new THREE.LineSegments(g, m)); fadeLines.push(m);
}
for (const m of fadeLines) m.userData.base = 1;
const bounds = [];
for (const x of [X0, X1]) for (const y of [-0.8, SHEET_Y0 + SHEET]) for (const z of [-SHEET / 2, SHEET / 2]) bounds.push(V(x, y, z));
// highlights and links (their geometry changes every update, so culling is off)
const hiGeo = new THREE.BufferGeometry(), hiMat = glowPoints(7, 2);
const hiPts = new THREE.Points(hiGeo, hiMat);
hiPts.frustumCulled = false; hiPts.renderOrder = 3; scene.add(hiPts);
const conGeo = new THREE.BufferGeometry();
const conLines = new THREE.LineSegments(conGeo, new THREE.LineBasicMaterial({
vertexColors: true, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
conLines.frustumCulled = false; conLines.renderOrder = 2; scene.add(conLines);
let selected = null, hovered = null, links = [];
function refreshHighlights() {
const p = [], c = [];
const add = (l, e, color) => { const v = pos(l, e); p.push(v.x, v.y, v.z); c.push(color.r, color.g, color.b); };
const wmax = Math.max(...links.map(k => k.w), 1e-9);
const linkCol = k => (k.side === "out" ? PAL.out : PAL.in).clone().multiplyScalar(0.3 + 0.7 * k.w / wmax);
for (const k of links) add(k.layer, k.expert, linkCol(k));
if (hovered) add(hovered.layer, hovered.expert, PAL.named.clone().multiplyScalar(0.7));
if (selected) add(selected.layer, selected.expert, PAL.named);
hiGeo.setAttribute("position", new THREE.Float32BufferAttribute(p, 3));
hiGeo.setAttribute("color", new THREE.Float32BufferAttribute(c, 3));
const lp = [], lc = [];
if (selected) {
const a = pos(selected.layer, selected.expert);
for (const k of links) {
const b = pos(k.layer, k.expert), cl = linkCol(k).multiplyScalar(0.6);
lp.push(a.x, a.y, a.z, b.x, b.y, b.z); lc.push(cl.r, cl.g, cl.b, cl.r, cl.g, cl.b);
}
}
conGeo.setAttribute("position", new THREE.Float32BufferAttribute(lp, 3));
conGeo.setAttribute("color", new THREE.Float32BufferAttribute(lc, 3));
render();
}
// layer labels: text in each layer's plane, just above the top-right corner of its sheet
const LABEL_H = Number(qs.get("labelsize")) || 0.2;
const labels = [];
for (let l = 0; l < L; l++) {
const cv = document.createElement("canvas"), ctx = cv.getContext("2d"), font = "600 64px ui-monospace, Menlo, monospace";
ctx.font = font; const tw = Math.ceil(ctx.measureText(`L${l}`).width) + 8;
cv.width = tw; cv.height = 80;
ctx.font = font; ctx.fillStyle = "#fff"; ctx.textBaseline = "middle"; ctx.fillText(`L${l}`, 4, 42);
const tex = new THREE.CanvasTexture(cv); tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = 8;
const w = LABEL_H * tw / 80;
const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false, side: THREE.DoubleSide, color: 0xc8d4da });
mat.userData.base = 0.85;
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, LABEL_H), mat);
m.rotation.y = Math.PI / 2;
m.position.set(layerX(l) + MLP_DX, SHEET_Y0 + SHEET + 0.08 + LABEL_H / 2, -SHEET / 2 + w / 2);
m.userData = { layer: l };
scene.add(m); labels.push(m);
}
let pending = false;
function render() {
if (pending) return; pending = true;
requestAnimationFrame(() => {
pending = false;
for (const m of [pointMat, hiMat]) { m.uniforms.ref.value = homeDist; m.uniforms.tdist.value = curDist(); }
applyFade();
renderer.render(scene, camera);
});
}
function resize() {
const w = canvas.clientWidth, h = canvas.clientHeight;
if (!w || !h) return;
renderer.setSize(w, h, false);
const narrow = w <= 760, li = narrow ? 0 : insets.left, ri = narrow ? 0 : insets.right;
const availW = Math.max(200, w - li - ri);
camera.aspect = w / h;
if (fitPerPx === null) {
// the distance at which the model's bounding sphere fits the visible gap, set once
const center = home.target, r = Math.max(...bounds.map(b => b.distanceTo(center)));
const vHalf = THREE.MathUtils.degToRad(camera.fov / 2), hHalf = Math.atan(Math.tan(vHalf) * availW / h);
homeDist = r / Math.sin(Math.min(vHalf, hHalf)) * 0.82;
camera.position.copy(home.target).addScaledVector(home.dir, homeDist);
controls.update();
fitPerPx = homeDist;
}
// the orbit target sits in the middle of the visible gap between the list and the panel
const tx = li + availW / 2;
camera.setViewOffset(w, h, w / 2 - tx, 0, w, h);
camera.updateProjectionMatrix(); render();
}
new ResizeObserver(resize).observe(canvas);
controls.addEventListener("change", render);
// picking
const ray = new THREE.Raycaster(); ray.params.Points.threshold = 0.07;
const mouse = new THREE.Vector2();
function pick(ev) {
const r = canvas.getBoundingClientRect();
mouse.set((ev.clientX - r.left) / r.width * 2 - 1, -(ev.clientY - r.top) / r.height * 2 + 1);
ray.setFromCamera(mouse, camera);
// hits come sorted by depth: take the frontmost visible layer's hits, then the point closest to the ray
const hits = ray.intersectObject(points);
if (hits.length) {
const layerOf = h => space.byFlat(h.index).layer;
const ls = [...new Set(hits.map(layerOf))];
const front = ls.find(l => layerVisibility(l) > 0.5) ?? ls.reduce((a, b) => layerVisibility(b) > layerVisibility(a) ? b : a);
let best = null;
for (const h of hits) if (layerOf(h) === front && (!best || h.distanceToRay < best.distanceToRay)) best = h;
const { layer, expert } = space.byFlat(best.index);
return { type: "expert", layer, expert };
}
const hit = ray.intersectObjects([...labels, ...denseSheets, ...slabs])[0];
if (hit) return { type: "block", layer: hit.object.userData.layer, part: hit.object.userData.part || "label" };
return null;
}
let moveQueued = null, downAt = null;
canvas.addEventListener("pointermove", ev => {
if (moveQueued) { moveQueued = ev; return; }
moveQueued = ev;
requestAnimationFrame(() => {
const e = moveQueued; moveQueued = null;
const p = pick(e);
const h = p && p.type === "expert" ? { layer: p.layer, expert: p.expert } : null;
if (JSON.stringify(h) !== JSON.stringify(hovered)) { hovered = h; refreshHighlights(); }
cb.onHover(p, e.clientX, e.clientY);
});
});
canvas.addEventListener("pointerleave", () => { hovered = null; refreshHighlights(); cb.onHover(null); });
canvas.addEventListener("pointerdown", ev => { downAt = [ev.clientX, ev.clientY]; });
canvas.addEventListener("pointerup", ev => {
if (!downAt || Math.hypot(ev.clientX - downAt[0], ev.clientY - downAt[1]) > 4) return;
const p = pick(ev);
if (p && p.type === "expert") cb.onPick(p.layer, p.expert);
else if (p && p.type === "block" && layerMode === null) enterLayer(p.layer);
});
// the closer the camera is to the orbit target, the more the layers away from the target's x fade out
const fade = { fx: 0, fw: 1, amt: 0, side: 1 };
const layerVisibility = l => {
const dx = layerX(l) + MLP_DX - fade.fx, d = dx / fade.fw;
if (dx * fade.side / GAP > 0.45) return 1 - fade.amt;
return 1 - 0.75 * fade.amt * (1 - Math.exp(-d * d));
};
let layerMode = null, saved = null;
function enterLayer(l) {
if (layerMode === null) saved = { pos: camera.position.clone(), tgt: controls.target.clone() };
layerMode = l;
const c = V(layerX(l) + MLP_DX, SHEET_Y0 + SHEET / 2, 0);
const dist = (SHEET / 2) / Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.12;
// face the sheet from +x, where its rows and columns and the layer labels read the right way round
controls.target.copy(c); camera.position.copy(c).add(V(dist, 0, 0));
controls.enableRotate = false;
controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
controls.update(); render(); cb.onLayerMode && cb.onLayerMode(l);
}
function exitLayer() {
if (layerMode === null) return;
layerMode = null;
controls.enableRotate = true;
controls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
camera.position.copy(saved.pos); controls.target.copy(saved.tgt);
controls.update(); render(); cb.onLayerMode && cb.onLayerMode(null);
}
function setFadeOf(fx, fw, amt, side) {
pointMat.uniforms.focusX.value = fx; pointMat.uniforms.fadeW.value = fw; pointMat.uniforms.fadeAmt.value = amt;
pointMat.uniforms.camSide.value = side;
Object.assign(fade, { fx, fw, amt, side });
}
function applyFade() {
if (layerMode !== null) {
setFadeOf(layerX(layerMode) + MLP_DX, 0.05, 1, 1);
for (const s of slabs) { s.material.opacity = 0; s.userData.edges.material.opacity = 0; }
for (const d of denseSheets) d.material.opacity = d.userData.layer === layerMode ? d.userData.baseOpacity : 0;
for (const lb of labels) lb.material.opacity = 0;
for (const m of fadeLines) m.opacity = 0;
return;
}
// continuous in zoom: eased on log-distance from the overview (no fade) to a sheet filling the view (full fade)
const dist = curDist();
const far = Math.log(homeDist * 0.7), near = Math.log(homeDist * 0.07);
const amt = THREE.MathUtils.smoothstep(THREE.MathUtils.clamp((far - Math.log(dist)) / (far - near), 0, 1), 0, 1);
// the focus is the layer whose sheet centre lands closest to the middle of the view on screen
const tv = controls.target.clone().project(camera), pv = new THREE.Vector3();
let fx = controls.target.x, best = Infinity;
for (let l = 0; l < L; l++) {
pv.set(layerX(l) + MLP_DX, SHEET_Y0 + SHEET / 2, 0).project(camera);
const dd = Math.hypot((pv.x - tv.x) * camera.aspect, pv.y - tv.y);
if (pv.z < 1 && dd < best) { best = dd; fx = layerX(l) + MLP_DX; }
}
const fw = GAP * (0.85 + 2.5 * (1 - amt));
setFadeOf(fx, fw, amt, Math.sign(camera.position.x - fx) || 1);
const f = x => { const d = (x - fx) / fw; return 1 - amt * (1 - Math.exp(-d * d)); };
for (const s of slabs) { const k = f(s.position.x); s.material.opacity = s.userData.baseOpacity * k; s.userData.edges.material.opacity = k; }
for (const d of denseSheets) d.material.opacity = d.userData.baseOpacity * f(d.position.x);
for (let l = 0; l < L; l++) {
const d = (layerX(l) + MLP_DX - fx) / fw;
labels[l].material.opacity = labels[l].material.userData.base * (1 - 0.5 * amt * (1 - Math.exp(-d * d)));
}
for (const m of fadeLines) m.opacity = m.userData.base * (1 - 0.9 * amt);
}
function flyTo(target, dist) {
const from = controls.target.clone(), to = target.clone();
const dir = camera.position.clone().sub(controls.target), d0 = dir.length();
dir.normalize();
const t0 = performance.now();
(function step(t) {
const k = Math.min(1, (t - t0) / 450), e = k * k * (3 - 2 * k);
controls.target.lerpVectors(from, to, e);
camera.position.copy(controls.target).addScaledVector(dir, d0 + (dist - d0) * e);
controls.update(); render();
if (k < 1) requestAnimationFrame(step);
})(t0);
}
const curDist = () => camera.position.distanceTo(controls.target);
return {
// shades: data.js's shade(), one per point, 0..1 or -1 for no value
setShades(shades) {
for (let i = 0; i < space.nPoints; i++) {
const s = shades[i];
(s < 0 ? PAL.none : PAL.lo.clone().lerp(PAL.hi, s)).toArray(col, i * 3);
}
geo.attributes.color.needsUpdate = true; render();
},
// select an expert (or null) and draw its links: out = the card's own, in = the cards that link to it
select(layer, expert, linkList = [], fly = true) {
selected = layer == null ? null : { layer, expert };
links = linkList;
refreshHighlights();
if (!fly || layer == null || layerMode !== null) return;
const v = pos(layer, expert).project(camera);
if (v.z > 1 || Math.abs(v.x) > 0.9 || Math.abs(v.y) > 0.9) flyTo(pos(layer, expert), Math.min(curDist(), homeDist * 0.35));
},
focusExpert(layer, expert) { if (layerMode === null) flyTo(pos(layer, expert), Math.min(curDist(), homeDist * 0.35)); },
hover(layer, expert) { hovered = layer == null ? null : { layer, expert }; refreshHighlights(); },
enterLayer, exitLayer,
get layerMode() { return layerMode; },
home() { flyTo(home.target, homeDist); },
setInsets(left, right) { insets.left = left; insets.right = right; resize(); },
// what is drawn, for checks: one sheet per layer, one point per expert
stats() {
return { sheets: space.sheets.length, moeSheets: space.sheets.filter(s => s.kind === "moe").length,
denseSheets: denseSheets.length, points: geo.attributes.position.count, labels: labels.length };
},
render,
};
}