Spaces:
Running

nhamid289's picture
Deploy elvis-code attention-architecture d17e79c
b869e0a verified
Raw History Blame Contribute Delete
7.3 kB
import { useCallback, useEffect, useState } from "react";
import {
AppLayout,
Button,
Dialog,
InputField,
InputSection,
SegmentedControl,
StepControls,
useStepper,
} from "@elvis/ui";
import AttentionHeatmap from "./AttentionHeatmap";
import Candidates from "./Candidates";
import InspectDialog from "./InspectDialog";
import { LANGUAGES } from "./languages";
import ModelDiagram from "./ModelDiagram";
import TokenLines from "./TokenLines";
import useTranslation from "./useTranslation";
const MEAN = "mean";
// The Q/K/V popup behind a click on a heatmap square; off for now (2026-11-13)
const INSPECT = false;
const STEP_MS = 500;
export default function App() {
const app = useTranslation();
// Index into cross; -1 is the last layer
const [layer, setLayer] = useState(-1);
const [head, setHead] = useState(MEAN);
const [architectureOpen, setArchitectureOpen] = useState(false);
// The heatmap cell being inspected
const [inspected, setInspected] = useState<{
row: number;
col: number;
} | null>(null);
// Step k shows the first k output tokens
const length = app.translation?.target.length ?? 0;
const fetchStep = useCallback(
async (k: number) => (k <= length ? k : null),
[length],
);
const steps = useStepper(fetchStep, { intervalMs: STEP_MS });
const { stepper } = steps;
useEffect(() => {
if (app.translation) {
stepper.restart({
total: app.translation.target.length,
intervalMs: STEP_MS,
});
}
}, [app.translation, stepper]);
// Capped for the render where a shorter translation arrives, before the restart
const shown = Math.min(steps.iteration, length);
const language = LANGUAGES.find((l) => l.value === app.language)!.label;
const cross = app.translation?.cross;
const layerIndex = cross ? (layer < 0 ? cross.length - 1 : layer) : 0;
const heads = cross?.[layerIndex];
const weights =
heads &&
(head === MEAN
? heads[0].map((row, i) =>
row.map((_, j) => mean(heads.map((h) => h[i][j]))),
)
: heads[Number(head)]);
return (
<AppLayout
title="Attention"
panel={
<>
<InputSection label="Sentence">
<InputField
label="English sentence"
hideLabel
value={app.sentence}
onChange={app.setSentence}
error={app.error}
rows={2}
/>
</InputSection>
<InputSection label="Language">
<SegmentedControl
label="Translate into"
options={LANGUAGES.map(({ value, label }) => ({ value, label }))}
value={app.language}
onChange={app.setLanguage}
/>
</InputSection>
{cross && (
<InputSection label="Model">
<div className="text-ink-muted text-sm">
<p>A small transformer with an attention mechanism:</p>
<ul className="list-disc pl-5">
<li>Two encoder layers read the English input sentence.</li>
<li>
Two decoder layers write the {language} output sentence one
token at a time.
</li>
<li>
Each decoder layer has four cross-attention heads, which
attend to parts of the English input sentence.
</li>
</ul>
</div>
<p className="text-sm">
Showing layer {layerIndex + 1},{" "}
{head === MEAN ? "mean of heads" : `head ${Number(head) + 1}`}.
</p>
<Button
label="View architecture"
onClick={() => setArchitectureOpen(true)}
/>
<Dialog
title="Model architecture"
open={architectureOpen}
onClose={() => setArchitectureOpen(false)}
>
<div className="mx-auto max-w-sm">
<ModelDiagram
layers={cross.length}
heads={cross[0].length}
layer={layerIndex}
head={head === MEAN ? null : Number(head)}
language={language}
onSelect={(l, h) => {
setLayer(l);
setHead(h === null ? MEAN : String(h));
}}
/>
</div>
</Dialog>
</InputSection>
)}
{app.status === "loading" && (
<p className="text-ink-muted text-sm">
Loading Python… the translation will appear once it is ready.
</p>
)}
{app.status === "failed" && (
<p className="text-danger font-semibold">Python failed to load.</p>
)}
{app.translation && (
<>
<InputSection label="Step">
<StepControls stepper={steps} />
</InputSection>
<InputSection label="Prediction">
{shown === 0 ? (
<p className="text-ink-muted text-sm">
Step forward to predict the first token.
</p>
) : (
<>
<p className="text-ink-muted text-sm">
The model's {app.translation.candidates[shown - 1].length}{" "}
most likely tokens at step {shown}. Greedy decoding takes
the most likely one.
</p>
<Candidates
candidates={app.translation.candidates[shown - 1]}
/>
</>
)}
</InputSection>
</>
)}
</>
}
>
{app.translation && cross && heads && weights && (
<>
<div className="flex justify-center">
<TokenLines
source={app.translation.source}
target={app.translation.target}
shown={shown}
weights={weights}
/>
</div>
<div className="[container-type:size] flex min-h-[26rem] flex-1 items-center justify-center py-4">
<AttentionHeatmap
source={app.translation.source}
target={app.translation.target}
weights={weights}
shown={shown}
onSelect={
INSPECT
? (row, col) => {
stepper.pause();
setInspected({ row, col });
}
: undefined
}
/>
</div>
{INSPECT && (
<InspectDialog
key={inspected ? `${inspected.row}/${inspected.col}` : "closed"}
translation={app.translation}
layer={layerIndex}
head={head === MEAN ? 0 : Number(head)}
cell={inspected}
onClose={() => setInspected(null)}
/>
)}
</>
)}
</AppLayout>
);
}
function mean(values: number[]): number {
return values.reduce((a, b) => a + b, 0) / values.length;
}