feat: add reduced AttnRes trace lab

This commit is contained in:
wuyang
2026-07-30 07:30:01 +08:00
parent d1d9d22bf3
commit 4ce780dcc9
11 changed files with 1070 additions and 26 deletions
+200
View File
@@ -0,0 +1,200 @@
import { writeFileSync } from "node:fs";
const cdpPort = process.env.CDP_PORT ?? "9227";
const baseUrl = process.env.SITE_URL ?? "http://127.0.0.1:4327";
const pages = await fetch(`http://127.0.0.1:${cdpPort}/json/list`).then((response) => response.json());
const page = pages.find((entry) => entry.type === "page");
if (!page) throw new Error(`CDP ${cdpPort} 没有可用页面`);
const socket = new WebSocket(page.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
socket.addEventListener("open", resolve, { once: true });
socket.addEventListener("error", reject, { once: true });
});
let nextId = 0;
const pending = new Map();
const exceptions = [];
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
const { resolve, reject } = pending.get(message.id);
pending.delete(message.id);
if (message.error) reject(new Error(message.error.message));
else resolve(message.result);
}
if (message.method === "Runtime.exceptionThrown") {
exceptions.push(message.params.exceptionDetails.exception?.description ?? message.params.exceptionDetails.text);
}
});
const command = (method, params = {}) => new Promise((resolve, reject) => {
const id = ++nextId;
pending.set(id, { resolve, reject });
socket.send(JSON.stringify({ id, method, params }));
});
const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const evaluate = async (expression) => {
const result = await command("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);
return result.result.value;
};
const navigate = async (path) => {
await command("Page.navigate", { url: `${baseUrl}${path}` });
for (let attempt = 0; attempt < 80; attempt += 1) {
await pause(100);
if (await evaluate("document.readyState === 'complete'")) return;
}
throw new Error(`${path} 加载超时`);
};
const screenshot = async (path) => {
const result = await command("Page.captureScreenshot", { format: "png", captureBeyondViewport: false });
writeFileSync(path, Buffer.from(result.data, "base64"));
};
await command("Page.enable");
await command("Runtime.enable");
await command("Emulation.setDeviceMetricsOverride", {
width: 1440,
height: 1100,
deviceScaleFactor: 1,
mobile: false,
});
await navigate("/k3/");
const desktop = await evaluate(`(() => {
const root = document.querySelector("[data-attnres-lab]");
root.scrollIntoView({ block: "start", behavior: "instant" });
window.scrollBy(0, -78);
const text = (selector) => root.querySelector(selector)?.textContent.trim();
const panel = () => root.querySelector("[data-attnres-panel]:not([hidden])")?.dataset.attnresPanel;
const line = (architecture) => root.querySelector(\`[data-curve-series="\${architecture}"] [data-curve-line]\`)?.getAttribute("points");
const initial = {
panel: panel(),
tabs: root.querySelectorAll("[data-attnres-tab]").length,
panels: root.querySelectorAll("[data-attnres-panel]").length,
baseline: text('[data-curve-final="baseline"]'),
full: text('[data-curve-final="full"]'),
block: text('[data-curve-final="block"]'),
baselineLine: line("baseline"),
textBoundary: root.textContent.includes("不是 K3 checkpoint forward") &&
root.textContent.includes("不能写成论文梯度结果复现"),
};
root.querySelector('[data-curve-seed="0"]').click();
const seed = {
baseline: text('[data-curve-final="baseline"]'),
full: text('[data-curve-final="full"]'),
block: text('[data-curve-final="block"]'),
baselineLine: line("baseline"),
};
root.querySelector('[data-attnres-tab="rms"]').click();
const rmsInitial = {
panel: panel(),
title: text("[data-rms-title]"),
blockLine: root.querySelector('[data-rms-series="block"]').getAttribute("points"),
rhythm: root.querySelectorAll(".block-rhythm i").length,
};
root.querySelector('[data-rms-metric="branch_output_rms"]').click();
const rmsChanged = {
title: text("[data-rms-title]"),
blockLine: root.querySelector('[data-rms-series="block"]').getAttribute("points"),
};
root.querySelector('[data-attnres-tab="mixer"]').click();
const mixerInitial = {
panel: panel(),
fullVisible: !root.querySelector('[data-mixer-view="full"]').hidden,
fullRows: root.querySelectorAll('[data-mixer-view="full"] .heat-row').length,
spike: root.querySelectorAll(".spikeSource").length,
};
root.querySelector('[data-mixer-arch="block"]').click();
const mixerChanged = {
blockVisible: !root.querySelector('[data-mixer-view="block"]').hidden,
blockRows: root.querySelectorAll('[data-mixer-view="block"] .heat-row').length,
};
root.querySelector('[data-attnres-tab="gradient"]').click();
const gradient = {
panel: panel(),
cards: root.querySelectorAll(".gradient-cv article").length,
blocks: root.querySelectorAll(".gradient-grid article").length,
boundary: root.textContent.includes("BASE < FULL < BLOCK") &&
root.textContent.includes("不能写成论文梯度结果复现"),
};
root.querySelector('[data-attnres-tab="audit"]').click();
const audit = {
panel: panel(),
costs: root.querySelectorAll(".cost-grid article").length,
hashes: root.querySelectorAll(".hash-ledger code").length,
exact: root.textContent.includes("2,000 steps · 8 / 8 exact"),
claims: root.querySelectorAll(".claim-grid li").length,
};
const first = root.querySelector('[data-attnres-tab="outcome"]');
first.focus();
first.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
const keyboard = {
selected: root.querySelector('[data-attnres-tab][aria-selected="true"]').dataset.attnresTab,
panel: panel(),
};
return {
initial, seed, rmsInitial, rmsChanged, mixerInitial, mixerChanged, gradient, audit, keyboard,
documentOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
};
})()`);
await pause(180);
await screenshot("/tmp/llm-atlas-k3-attnres-desktop.png");
await command("Emulation.setDeviceMetricsOverride", {
width: 390,
height: 844,
deviceScaleFactor: 1,
mobile: true,
});
await navigate("/k3/");
const mobile = await evaluate(`(() => {
const root = document.querySelector("[data-attnres-lab]");
root.scrollIntoView({ block: "start", behavior: "instant" });
window.scrollBy(0, -64);
return {
tabs: root.querySelectorAll("[data-attnres-tab]").length,
ledger: root.querySelectorAll(".trace-ledger article").length,
documentOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
rootOverflow: root.scrollWidth - root.clientWidth,
visiblePanel: root.querySelector("[data-attnres-panel]:not([hidden])")?.dataset.attnresPanel,
};
})()`);
await pause(180);
await screenshot("/tmp/llm-atlas-k3-attnres-mobile.png");
const report = { desktop, mobile, exceptions };
console.log(JSON.stringify(report, null, 2));
const numeric = (text) => Number.parseFloat(text.replace("−", "-"));
const failures = [];
if (desktop.initial.panel !== "outcome" || desktop.initial.tabs !== 5 || desktop.initial.panels !== 5) failures.push("五视图初始结构异常");
if (Math.abs(numeric(desktop.initial.baseline) - 1.99913) > 1e-5 || Math.abs(numeric(desktop.initial.full) - 1.98457) > 1e-5 || Math.abs(numeric(desktop.initial.block) - 1.95667) > 1e-5) failures.push("三 seed 均值 BPC 异常");
if (Math.abs(numeric(desktop.seed.baseline) - 2.00054) > 1e-5 || desktop.seed.baselineLine === desktop.initial.baselineLine) failures.push("seed 切换未更新训练曲线");
if (!desktop.initial.textBoundary) failures.push("主视区缺少 K3 forward 或梯度反证边界");
if (desktop.rmsInitial.panel !== "rms" || desktop.rmsInitial.rhythm !== 32 || desktop.rmsInitial.title === desktop.rmsChanged.title || desktop.rmsInitial.blockLine === desktop.rmsChanged.blockLine) failures.push("RMS 指标切换或 32 层节律异常");
if (desktop.mixerInitial.panel !== "mixer" || !desktop.mixerInitial.fullVisible || desktop.mixerInitial.fullRows !== 32 || desktop.mixerInitial.spike !== 1 || !desktop.mixerChanged.blockVisible || desktop.mixerChanged.blockRows !== 32) failures.push("Full/Block mixer heatmap 异常");
if (desktop.gradient.panel !== "gradient" || desktop.gradient.cards !== 4 || desktop.gradient.blocks !== 16 || !desktop.gradient.boundary) failures.push("梯度反证视图异常");
if (desktop.audit.panel !== "audit" || desktop.audit.costs !== 3 || desktop.audit.hashes !== 4 || !desktop.audit.exact || desktop.audit.claims !== 6) failures.push("成本、重放或 claim boundary 异常");
if (desktop.keyboard.selected !== "rms" || desktop.keyboard.panel !== "rms") failures.push("键盘 tab 导航异常");
if (desktop.documentOverflow > 1 || mobile.documentOverflow > 1 || mobile.rootOverflow > 1) failures.push("桌面或移动端出现文档级横向溢出");
if (mobile.tabs !== 5 || mobile.ledger !== 6 || mobile.visiblePanel !== "outcome") failures.push("移动端初始结构异常");
if (exceptions.length) failures.push(`浏览器异常:${exceptions.join(" | ")}`);
if (failures.length) {
console.error(`\nFAIL\n- ${failures.join("\n- ")}`);
process.exitCode = 1;
} else {
console.log("\nPASS K3 AttnRes browser regression");
}
socket.close();
+61
View File
@@ -0,0 +1,61 @@
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
const read = (path) => {
const bytes = readFileSync(new URL(path, import.meta.url));
return {
bytes,
json: JSON.parse(bytes),
sha256: createHash("sha256").update(bytes).digest("hex"),
};
};
const raw = read("../src/data/k3-attnres-reduced.json");
const compact = read("../src/data/k3-attnres-reduced-compact.json");
const reproduction = read("../experiments/k3/attnres/reproduction.json");
const failures = [];
const expect = (condition, message) => {
if (!condition) failures.push(message);
};
expect(raw.sha256 === "44f8622654d32485f8d6e698c02ba1365ddffb10cbd73db0294136d0bd93ce88", "raw payload SHA-256 changed");
expect(compact.sha256 === "44864d48eddb2ae5887fba4b74f63b5a3d6a23497886ee307decf5b4f45d9faf", "compact payload SHA-256 changed");
expect(reproduction.sha256 === "545543b7e4a970ca3bc0e6246610a32fb53ec3d9546a98e0f17f38d7121918a2", "reproduction payload SHA-256 changed");
expect(compact.json.protocol_id === "llm-atlas-k3-attnres-reduced-v1", "protocol identity mismatch");
expect(compact.json.grid.runs === 9, "formal grid is not 9 cells");
expect(compact.json.grid.target_bytes_total === 147_456_000, "formal target-byte budget mismatch");
expect(raw.json.formal_runs.length === 9, "raw formal run count mismatch");
expect(Object.values(reproduction.json.common_initial_parameters).every((row) => row.exact), "common initial parameters are not exact within seed");
expect(Object.values(reproduction.json.smoke).every((row) => row.all_exact), "paired smoke replay mismatch");
expect(reproduction.json.formal_replay.all_numeric_and_hash_fields_exact, "formal fresh-process replay mismatch");
expect(!reproduction.json.formal_replay.timing_exact_required, "timing must not be an exact replay requirement");
const full = compact.json.final_validation.full_contrast;
const block = compact.json.final_validation.block_contrast;
expect(full.paired_deltas_bpc.length === 3 && full.paired_deltas_bpc.every((value) => value < 0), "Full paired direction mismatch");
expect(block.paired_deltas_bpc.length === 3 && block.paired_deltas_bpc.every((value) => value < 0), "Block paired direction mismatch");
expect(Math.abs(full.mean_delta_bpc - (-0.014567152672337214)) < 1e-15, "Full mean delta changed");
expect(Math.abs(block.mean_delta_bpc - (-0.04246557635602392)) < 1e-15, "Block mean delta changed");
expect(compact.json.gradients.baseline.mean_cv < compact.json.gradients.full.mean_cv, "gradient counterevidence order baseline/full changed");
expect(compact.json.gradients.full.mean_cv < compact.json.gradients.block.mean_cv, "gradient counterevidence order full/block changed");
expect(compact.json.posthoc.label.startsWith("post-hoc"), "post-hoc callout lost its evidence label");
if (failures.length) {
console.error(`FAIL K3 AttnRes data\n- ${failures.join("\n- ")}`);
process.exit(1);
}
console.log(JSON.stringify({
protocol: compact.json.protocol_id,
formalRuns: compact.json.grid.runs,
fullMeanDeltaBpc: full.mean_delta_bpc,
blockMeanDeltaBpc: block.mean_delta_bpc,
formalReplayExact: reproduction.json.formal_replay.all_numeric_and_hash_fields_exact,
hashes: {
raw: raw.sha256,
compact: compact.sha256,
reproduction: reproduction.sha256,
},
}, null, 2));
console.log("PASS K3 AttnRes frozen data");
+7 -3
View File
@@ -79,6 +79,8 @@ const overview = await evaluate(`(() => ({
artifactPanels: document.querySelectorAll("[data-artifact-panel]").length,
artifactLayers: document.querySelectorAll("[data-layer-cell]").length,
artifactMismatch: document.querySelector("#artifacts")?.textContent.includes("A_log [128] ≠ expected [96]"),
attnresTabs: document.querySelectorAll("[data-attnres-tab]").length,
attnresPanels: document.querySelectorAll("[data-attnres-panel]").length,
nativeVisionCorrected: document.body.textContent.includes("MoonViT‑V2 从头训练") &&
document.body.textContent.includes("同一个 next-token prediction objective"),
staleVisionClaim: document.body.textContent.includes("先固定语言模型训练视觉组件"),
@@ -287,8 +289,9 @@ const mobile = await evaluate(`(() => {
tabs: root.querySelectorAll("[data-k3-tab]").length,
artifactTabs: document.querySelectorAll("[data-artifact-tab]").length,
artifactLayers: document.querySelectorAll("[data-layer-cell]").length,
attnresTabs: document.querySelectorAll("[data-attnres-tab]").length,
offenders: [...document.querySelectorAll("body *")]
.filter((node) => !node.closest(".paper-chain, .spec-table-wrap, .cache-strip, .architecture-explorer, [data-k3-lab], [data-k3-artifact-lab]"))
.filter((node) => !node.closest(".paper-chain, .spec-table-wrap, .cache-strip, .architecture-explorer, [data-k3-lab], [data-k3-artifact-lab], [data-attnres-lab]"))
.filter((node) => node.getBoundingClientRect().right > document.documentElement.clientWidth + 1)
.slice(0, 15)
.map((node) => ({
@@ -319,11 +322,12 @@ console.log(JSON.stringify(report, null, 2));
const numeric = (text) => Number.parseFloat(text.replaceAll(",", "").replace("−", "-"));
const failures = [];
if (!overview.title.includes("因果环节")) failures.push("K3 二轮标题异常");
if (overview.sections !== 32 || overview.tocLinks !== 32) failures.push("31 个编号专题加阅读链的目录结构异常");
if (overview.sections !== 33 || overview.tocLinks !== 33) failures.push("32 个编号专题加阅读链的目录结构异常");
if (overview.ledgers !== 32 || overview.reportMap !== 9) failures.push("32 张问题账或报告地图异常");
if (overview.figureAtlas !== 21 || overview.paperLinks !== 100 || overview.paperGroups < 12) failures.push("图表审计或 100 节点阅读链异常");
if (overview.labTabs !== 8 || overview.labPanels !== 8) failures.push("八联实验结构异常");
if (overview.artifactTabs !== 4 || overview.artifactPanels !== 4 || overview.artifactLayers !== 93 || !overview.artifactMismatch) failures.push("开放工件四视图、93 层条带或形状冲突异常");
if (overview.attnresTabs !== 5 || overview.attnresPanels !== 5) failures.push("AttnRes 独立实验五视图异常");
if (!overview.nativeVisionCorrected || overview.staleVisionClaim) failures.push("原生多模态纠错未生效或旧错误残留");
if (overview.documentOverflow > 1 || mobile.documentOverflow > 1) failures.push("桌面或移动端存在文档级横向溢出");
if (labs.memoryInitial.panel !== "memory" || numeric(labs.memoryInitial.additiveError) <= numeric(labs.memoryInitial.deltaError)) failures.push("Delta memory 初始递推异常");
@@ -348,7 +352,7 @@ if (artifacts.parameterChanged.shape !== "[96,128] F32" || !artifacts.parameterC
if (artifacts.reproductionInitial.panel !== "reproduction" || numeric(artifacts.reproductionInitial.speedup) !== 1.85 || numeric(artifacts.reproductionInitial.localMean) < 2.6 || !artifacts.reproductionInitial.exactSuite || numeric(artifacts.reproductionInitial.cv) < 2) failures.push("FlashKDA H20、本机 exact suite 或 router 初始探针异常");
if (numeric(artifacts.reproductionChanged.speedup) !== 3.27 || numeric(artifacts.reproductionChanged.flash) !== 0.7064 || numeric(artifacts.reproductionChanged.localMean) >= numeric(artifacts.reproductionInitial.localMean) || !artifacts.reproductionChanged.localMode.includes("FP32 state") || numeric(artifacts.reproductionChanged.cv) <= numeric(artifacts.reproductionInitial.cv) || numeric(artifacts.reproductionChanged.zero) <= numeric(artifacts.reproductionInitial.zero)) failures.push("GB200 benchmark、本机 varlen/state 或 synthetic router counterexample 未更新");
if (artifacts.keyboardSelected !== "tensors" || artifacts.keyboardVisible !== "tensors") failures.push("开放工件键盘 tab 导航异常");
if (!mobile.menuVisible || mobile.menuOpen !== "true" || mobile.tabs !== 8 || mobile.artifactTabs !== 4 || mobile.artifactLayers !== 93) failures.push("移动端导航或实验异常");
if (!mobile.menuVisible || mobile.menuOpen !== "true" || mobile.tabs !== 8 || mobile.artifactTabs !== 4 || mobile.artifactLayers !== 93 || mobile.attnresTabs !== 5) failures.push("移动端导航或实验异常");
if (mobile.offenders.length) failures.push(`移动端越界元素:${JSON.stringify(mobile.offenders)}`);
if (exceptions.length) failures.push(`浏览器异常:${exceptions.join(" | ")}`);