Spaces:
Running

attention / frontends /react /src /InspectDialog.tsx
nhamid289's picture
Deploy from elvis-code (redesigned with the ELVIS design system)
660e352 verified
Raw History Blame Contribute Delete
6.53 kB
import { useEffect, useState } from "react";
import { Dialog, SegmentedControl } from "@elvis/ui";
import { python } from "./python";
import type { Inspection, Translation } from "./types";
// Okabe–Ito Dark Blue and Dark Orange: a colour-blind-safe pair for positive and negative
const POSITIVE = "#0072B2";
const NEGATIVE = "#D55E00";
type Props = {
translation: Translation;
layer: number;
// Head to show first; give the dialog a new key per cell so it starts there
head: number;
// The clicked cell: output token `row`, source token `col`; null when closed
cell: { row: number; col: number } | null;
onClose: () => void;
};
// The steps behind one row of a head's attention: q · k, scale, softmax, weighted sum of v
export default function InspectDialog({ translation, layer, head: initialHead, cell, onClose }: Props) {
const [head, setHead] = useState(initialHead);
const [result, setResult] = useState<{ key: string; data: Inspection } | null>(null);
const [error, setError] = useState<string | null>(null);
const row = cell?.row ?? 0;
const key = `${layer}/${head}/${row}`;
useEffect(() => {
if (!cell) {
return;
}
let current = true;
python.call("handle_inspect", { layer, head, row: cell.row }).then((r) => {
if (current) {
setError(r.ok ? null : r.error.message);
if (r.ok) {
setResult({ key: `${layer}/${head}/${cell.row}`, data: r.data });
}
}
});
return () => {
current = false;
};
}, [layer, head, cell]);
const target = translation.target[row];
const data = result?.key === key ? result.data : null;
const headCount = translation.cross[layer].length;
return (
<Dialog
title={cell ? `Layer ${layer + 1}, head ${head + 1}: ${target} → ${translation.source[cell.col].token}` : ""}
open={cell !== null}
onClose={onClose}
wide
>
{cell && (
<div className="flex flex-col gap-4 text-sm text-ink">
<div className="w-80">
<SegmentedControl
label="Head"
options={Array.from({ length: headCount }, (_, h) => ({ value: String(h), label: `Head ${h + 1}` }))}
value={String(head)}
onChange={(v) => setHead(Number(v))}
/>
</div>
<p>
While predicting <b>{target}</b>, this head compares its <b>query</b> q with each English token's{" "}
<b>key</b> k. The dot product, divided by √{data?.query.length ?? "d"}, is the score; softmax turns the
scores into weights that sum to 1; the head's output is the weighted sum of the tokens' <b>values</b> v.
</p>
{error && <p className="font-semibold text-danger">{error}</p>}
{data && <Steps data={data} translation={translation} col={cell.col} />}
</div>
)}
</Dialog>
);
}
function Steps({ data, translation, col }: { data: Inspection; translation: Translation; col: number }) {
const dh = data.query.length;
const keyMax = maxAbs([data.query, ...data.keys]);
const valueMax = maxAbs([...data.values, data.output]);
const expSum = data.scores.reduce((a, s) => a + Math.exp(s), 0);
const token = translation.source[col].token;
return (
<>
<table className="w-full border-separate border-spacing-y-1">
<thead className="text-left text-xs text-ink-muted">
<tr>
<th className="pr-3 font-medium">Token</th>
<th className="pr-3 font-medium">Key k</th>
<th className="pr-3 text-right font-medium">q · k / √{dh}</th>
<th className="pr-3 text-right font-medium">Weight</th>
<th className="font-medium">Value v</th>
</tr>
</thead>
<tbody>
<tr>
<td className="pr-3 text-ink-muted">Query q</td>
<td className="pr-3">
<VectorStrip values={data.query} max={keyMax} />
</td>
<td colSpan={3} />
</tr>
{translation.source.map((s, j) => (
<tr key={j} className={j === col ? "bg-marker-soft" : ""}>
<td className={`rounded-l-sm px-1 pr-3 font-mono ${s.known ? "" : "text-danger"}`}>{s.known ? s.token : `${s.token}?`}</td>
<td className="pr-3">
<VectorStrip values={data.keys[j]} max={keyMax} />
</td>
<td className="pr-3 text-right font-mono">{data.scores[j].toFixed(2)}</td>
<td className="pr-3 text-right font-mono font-semibold">{data.weights[j].toFixed(3)}</td>
<td className="rounded-r-sm pr-1">
<VectorStrip values={data.values[j]} max={valueMax} />
</td>
</tr>
))}
<tr>
<td colSpan={4} className="pt-2 pr-3 text-right text-ink-muted">
Output Σ weight × v
</td>
<td className="pt-2">
<VectorStrip values={data.output} max={valueMax} />
</td>
</tr>
</tbody>
</table>
<p className="rounded-sm bg-paper p-2 font-mono text-xs">
q · k<sub>{token}</sub> = {(data.scores[col] * Math.sqrt(dh)).toFixed(2)}; ÷ √{dh} = {data.scores[col].toFixed(2)}
<br />
softmax: e<sup>{data.scores[col].toFixed(2)}</sup> / Σ e<sup>score</sup> = {Math.exp(data.scores[col]).toFixed(2)} /{" "}
{expSum.toFixed(2)} = {data.weights[col].toFixed(3)}
</p>
<p className="text-ink-muted">
Each square is one of the {dh} numbers in a vector: <span style={{ color: POSITIVE }}>■</span> positive,{" "}
<span style={{ color: NEGATIVE }}>■</span> negative, stronger for larger values; hover for the value. The{" "}
{translation.cross[0].length} heads' outputs are then joined and multiplied by the output matrix W<sub>O</sub>.
</p>
</>
);
}
function VectorStrip({ values, max }: { values: number[]; max: number }) {
return (
<div className="flex">
{values.map((v, d) => (
<div
key={d}
title={`[${d}] ${v.toFixed(3)}`}
className="h-4 min-w-1 flex-1 border-r border-surface last:border-r-0"
style={{
backgroundColor: `color-mix(in srgb, ${v >= 0 ? POSITIVE : NEGATIVE} ${((Math.abs(v) / max) * 100).toFixed(0)}%, var(--color-surface))`,
}}
/>
))}
</div>
);
}
function maxAbs(vectors: number[][]): number {
return Math.max(...vectors.flat().map(Math.abs)) || 1;
}