Spaces:
Running

File size: 6,531 Bytes
660e352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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;
}