feat: isolate DeepSeek role marker head token

This commit is contained in:
wuyang
2026-07-29 20:44:43 +08:00
parent 8ef2d33437
commit ea49ed0511
15 changed files with 3676450 additions and 33 deletions
@@ -0,0 +1,232 @@
import { createHash } from "node:crypto";
import { readFileSync, statSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
const root = resolve(import.meta.dirname, "..");
const mainPath = resolve(
root,
"src/data/deepseek-v2-lite-routing-role-marker-head-control.json",
);
const reproPath = resolve(
root,
"src/data/deepseek-v2-lite-routing-role-marker-head-control-repro.json",
);
const boundaryPath = resolve(
root,
"src/data/deepseek-v2-lite-routing-history-boundary-token-control.json",
);
const outputPath = resolve(
root,
"src/data/deepseek-v2-lite-routing-role-marker-head-control-compact.json",
);
const sha256 = (path) => createHash("sha256")
.update(readFileSync(path))
.digest("hex");
const mainSha256 = sha256(mainPath);
const reproSha256 = sha256(reproPath);
const mainBytes = statSync(mainPath).size;
const reproBytes = statSync(reproPath).size;
const exact = mainSha256 === reproSha256 && mainBytes === reproBytes;
if (!exact) {
throw new Error("role-marker formal run and rerun are not byte-exact");
}
const role = JSON.parse(readFileSync(mainPath, "utf8"));
const boundary = JSON.parse(readFileSync(boundaryPath, "utf8"));
const roleEdges = [
"system_official",
"system_target_assistant",
"system_target_x",
"system_suffix_user",
"target_assistant_at_s0",
"target_assistant_at_s1",
"target_x_at_s0",
"target_x_at_s1",
"suffix_user_at_s0",
"suffix_user_at_s1",
];
const aggregateAlignment = (layer, domain, edge) => {
const rows = layer.prompts
.filter((prompt) => prompt.domain === domain)
.map((prompt) => prompt.alignments[edge]);
const aligned = rows.reduce(
(sum, row) => sum + row.aligned_tokens,
0,
);
const setExact = rows.reduce(
(sum, row) => sum + row.set_topk_exact,
0,
);
const orderedExact = rows.reduce(
(sum, row) => sum + row.ordered_topk_exact,
0,
);
const weightedJaccard = rows.reduce(
(sum, row) => sum + row.mean_jaccard * row.aligned_tokens,
0,
);
return {
aligned,
setExactRate: setExact / aligned,
orderedExactRate: orderedExact / aligned,
meanJaccard: weightedJaccard / aligned,
};
};
const sourceById = new Map(
boundary.corpus_contract.selected.map((source) => [source.id, source]),
);
const tokenContract = {
compared: 0,
messageHashExact: 0,
renderedHashExact: 0,
tokenIdHashExact: 0,
targetContractExact: 0,
};
for (const source of role.corpus_contract.selected) {
const priorSource = sourceById.get(source.id);
if (!priorSource) throw new Error(`boundary source missing: ${source.id}`);
for (const system of [0, 1]) {
const current = source.conditions[`s${system}_official`];
const previous = priorSource.conditions[`s${system}_eos`];
tokenContract.compared += 1;
tokenContract.messageHashExact += (
current.messages_sha256 === previous.messages_sha256
);
tokenContract.renderedHashExact += (
current.rendered_sha256 === previous.rendered_sha256
);
tokenContract.tokenIdHashExact += (
current.token_ids_sha256 === previous.token_ids_sha256
);
tokenContract.targetContractExact += (
current.tokens === previous.tokens
&& current.content_tokens === previous.content_tokens
&& current.aligned_content_tokens
=== previous.aligned_content_tokens
);
}
}
const crossBatch = role.layers.slice(1).map((layer) => {
const previousLayer = boundary.layers.find(
(candidate) => candidate.layer === layer.layer,
);
const previousById = new Map(
previousLayer.prompts.map((prompt) => [prompt.id, prompt]),
);
const counts = {
compared: 0,
fullRouteHashExact: 0,
targetRouteHashExact: 0,
fullLoadExact: 0,
targetLoadExact: 0,
};
for (const prompt of layer.prompts) {
const previousPrompt = previousById.get(prompt.id);
if (!previousPrompt) {
throw new Error(`boundary prompt missing: ${prompt.id}`);
}
for (const system of [0, 1]) {
const current = prompt.conditions[`s${system}_official`];
const previous = previousPrompt.conditions[`s${system}_eos`];
counts.compared += 1;
counts.fullRouteHashExact += (
current.topk_sha256 === previous.topk_sha256
);
counts.targetRouteHashExact += (
current.content_topk_sha256 === previous.content_topk_sha256
);
counts.fullLoadExact += (
JSON.stringify(current.full_load)
=== JSON.stringify(previous.full_load)
);
counts.targetLoadExact += (
JSON.stringify(current.content_load)
=== JSON.stringify(previous.content_load)
);
}
}
return { layer: layer.layer, ...counts };
});
const compact = {
schemaVersion: 1,
source: {
mainSha256,
reproSha256,
mainBytes,
reproBytes,
exact,
},
domains: role.corpus_contract.domains,
labels: role.corpus_contract.domain_labels,
inference: role.inference_contract,
contract: {
tokenIds: role.role_marker_head_contract.role_token_ids,
validation: role.role_marker_head_contract.render_validation,
official: role.boundary.official_serialization_by_role_head,
tokenContractAgainstBoundaryRun: tokenContract,
},
crossBatch,
layers: role.layers.slice(1).map((layer) => ({
layer: layer.layer,
alignment: Object.fromEntries(
role.corpus_contract.domains.map((domain) => [
domain,
Object.fromEntries(
roleEdges.map((edge) => [
edge,
aggregateAlignment(layer, domain, edge),
]),
),
]),
),
scopes: Object.fromEntries(
["target_content", "full_input"].map((scope) => [
scope,
{
modes: Object.fromEntries(
["prompt_balanced", "token_weighted"].map((mode) => {
const control = (
layer.statistics[scope].modes[mode].role_marker_control
);
return [
mode,
Object.fromEntries(
role.corpus_contract.domains.map((domain) => [
domain,
{
distances: control[domain].system_edge_distances,
contrasts: (
control[domain].system_edge_distance_contrasts
),
cvEdges: control[domain].metric_system_edges.cv,
cvContrasts: (
control[domain].metric_system_edge_contrasts.cv
),
direct: control[domain].direct_substitutions,
},
]),
),
];
}),
),
},
]),
),
})),
};
writeFileSync(
outputPath,
`${JSON.stringify(compact, null, 2)}\n`,
"utf8",
);
process.stdout.write(
`${outputPath}\n${mainSha256}\n${mainBytes} bytes source → `
+ `${statSync(outputPath).size} bytes compact\n`,
);
+98 -4
View File
@@ -581,6 +581,71 @@ await evaluate(`(() => {
await pause(120);
await screenshot("/tmp/llm-atlas-deepseek-boundary-results-desktop.png");
const artifactRole = await evaluate(`(() => {
const root = document.querySelector("[data-dsv2-lab]");
root.querySelector('[data-artifact-tab="role"]').click();
const read = () => ({
panel: root.querySelector("[data-artifact-panel]:not([hidden])").dataset.artifactPanel,
levelCards: root.querySelectorAll(".role-level-grid > article").length,
domainCards: root.querySelectorAll("[data-role-domain-grid] > article").length,
domains: [...root.querySelectorAll("[data-role-domain-grid] > article")].map((node) => ({
label: node.querySelector(":scope > span").textContent.trim(),
values: [...node.querySelectorAll(".role-tv-ladder > b")].map((cell) => ({
name: cell.querySelector("small").textContent.trim(),
value: cell.querySelector("strong").textContent.trim(),
})),
effect: node.querySelector(":scope > strong").textContent.trim(),
className: node.querySelector(":scope > strong").className,
ci: node.querySelector(":scope > p").textContent.trim(),
stability: node.querySelector(":scope > small").textContent.trim(),
direct: node.querySelector(":scope > em").textContent.trim(),
interaction: node.querySelector(":scope > u").textContent.trim(),
cv: node.querySelector(":scope > i").textContent.trim(),
})),
summary: [...root.querySelectorAll('[data-artifact-panel="role"] .role-summary article b')].map((node) => node.textContent.trim()),
depthRows: root.querySelectorAll("[data-role-depth-map] > div").length,
depthCells: root.querySelectorAll("[data-role-depth-map] > div > span").length,
depthTitle: root.querySelector("[data-role-depth-title]").textContent.trim(),
exact: root.querySelector(".role-ledger .exact b").textContent.trim(),
causalCards: root.querySelectorAll(".role-causal-ledger > article").length,
batchCells: root.querySelectorAll(".role-batch-audit > div:last-child > span").length,
batchValues: [...root.querySelectorAll(".role-batch-audit > div:last-child > span i")].map((node) => node.textContent.trim()),
note: root.querySelector("[data-role-note]").textContent.trim(),
targetHead: root.querySelector("[data-role-target-head]").textContent.trim(),
suffixHead: root.querySelector("[data-role-suffix-head]").textContent.trim(),
activeLayer: root.querySelector("[data-role-layer].active").textContent.trim(),
activeScope: root.querySelector('[data-role-scope][aria-pressed="true"]').dataset.roleScope,
activeMode: root.querySelector('[data-role-mode][aria-pressed="true"]').dataset.roleMode,
activeContrast: root.querySelector('[data-role-contrast][aria-pressed="true"]').dataset.roleContrast,
});
const layer1Assistant = read();
root.querySelector('[data-role-layer="5"]').click();
root.querySelector('[data-role-contrast="target_x_minus_official"]').click();
const layer5X = read();
root.querySelector('[data-role-contrast="suffix_user_minus_official"]').click();
const layer5Suffix = read();
root.querySelector('[data-role-scope="full_input"]').click();
const layer5FullSuffix = read();
root.querySelector('[data-role-mode="token_weighted"]').click();
const layer5FullToken = read();
root.querySelector('[data-role-layer="1"]').click();
root.querySelector('[data-role-scope="target_content"]').click();
root.querySelector('[data-role-mode="prompt_balanced"]').click();
root.querySelector('[data-role-contrast="target_assistant_minus_official"]').click();
return { layer1Assistant, layer5X, layer5Suffix, layer5FullSuffix, layer5FullToken, restored: read() };
})()`);
await evaluate(`(() => {
document.querySelector("[data-dsv2-lab]").scrollIntoView({ block: "start", behavior: "instant" });
window.scrollBy(0, -82);
})()`);
await pause(180);
await screenshot("/tmp/llm-atlas-deepseek-role-desktop.png");
await evaluate(`(() => {
document.querySelector(".role-domain-grid").scrollIntoView({ block: "center", behavior: "instant" });
})()`);
await pause(120);
await screenshot("/tmp/llm-atlas-deepseek-role-results-desktop.png");
const artifactEvidence = await evaluate(`(() => {
const root = document.querySelector("[data-dsv2-lab]");
root.querySelector('[data-artifact-tab="evidence"]').click();
@@ -678,6 +743,13 @@ const mobile = await evaluate(`(() => {
boundaryTokenCards: artifact.querySelectorAll(".boundary-token-grid > article").length,
boundaryDomainCards: artifact.querySelectorAll("[data-boundary-domain-grid] > article").length,
boundaryDepthCells: artifact.querySelectorAll("[data-boundary-depth-map] > div > span").length,
roleLayers: artifact.querySelectorAll("[data-role-layer]").length,
roleScopes: artifact.querySelectorAll("[data-role-scope]").length,
roleModes: artifact.querySelectorAll("[data-role-mode]").length,
roleContrasts: artifact.querySelectorAll("[data-role-contrast]").length,
roleLevelCards: artifact.querySelectorAll(".role-level-grid > article").length,
roleDomainCards: artifact.querySelectorAll("[data-role-domain-grid] > article").length,
roleDepthCells: artifact.querySelectorAll("[data-role-depth-map] > div > span").length,
offenders: [...document.querySelectorAll("body *")]
.filter((node) => !node.closest(".paper-chain, .advantage-table, .precision-table, .mapping-table, [data-deepseek-lab], [data-dsv2-lab]"))
.filter((node) => node.getBoundingClientRect().right > document.documentElement.clientWidth + 1)
@@ -761,8 +833,22 @@ await evaluate(`(() => {
})()`);
await pause(120);
await screenshot("/tmp/llm-atlas-deepseek-boundary-results-mobile.png");
await evaluate(`(() => {
const artifact = document.querySelector("[data-dsv2-lab]");
artifact.querySelector('[data-artifact-tab="role"]').click();
artifact.scrollIntoView({ block: "start", behavior: "instant" });
window.scrollBy(0, -70);
})()`);
await pause(180);
await screenshot("/tmp/llm-atlas-deepseek-role-mobile.png");
await evaluate(`(() => {
document.querySelector(".role-domain-grid").scrollIntoView({ block: "start", behavior: "instant" });
window.scrollBy(0, -72);
})()`);
await pause(120);
await screenshot("/tmp/llm-atlas-deepseek-role-results-mobile.png");
const report = { overview, capacity, cache, codesign, rl, artifactRoute, artifactLoad, artifactCache, artifactAbsorb, artifactCorpus, artifactTemplate, artifactHistory, artifactDistance, artifactBoundary, artifactEvidence, home, papers, mobile, exceptions };
const report = { overview, capacity, cache, codesign, rl, artifactRoute, artifactLoad, artifactCache, artifactAbsorb, artifactCorpus, artifactTemplate, artifactHistory, artifactDistance, artifactBoundary, artifactRole, artifactEvidence, home, papers, mobile, exceptions };
console.log(JSON.stringify(report, null, 2));
const numeric = (text) => Number.parseFloat(text.replaceAll(",", ""));
@@ -772,8 +858,8 @@ if (overview.sections !== 26 || overview.tocLinks !== 26) failures.push("二十
if (overview.ledgers !== 24 || overview.waves !== 10) failures.push("二十四张问题账或十次转向结构异常");
if (overview.paperLinks !== 60 || overview.branches !== 5 || overview.followups !== 1) failures.push("论文链、旁支或公开后续标记异常");
if (overview.labTabs !== 4 || overview.labPanels !== 4) failures.push("四联实验结构异常");
if (overview.artifactTabs !== 10 || overview.artifactPanels !== 10 || overview.artifactLayers !== 27) failures.push("真实权重十联实验结构异常");
if (overview.heroLabs !== "14 个可操作实验") failures.push("DeepSeek 实验总数账异常");
if (overview.artifactTabs !== 11 || overview.artifactPanels !== 11 || overview.artifactLayers !== 27) failures.push("真实权重十一联实验结构异常");
if (overview.heroLabs !== "15 个可操作实验") failures.push("DeepSeek 实验总数账异常");
if (overview.navLinks !== 20 || home.navLinks !== 20 || mobile.mobileLinks !== 20 || overview.activeNav !== "DeepSeek") failures.push("全站导航未同步 DeepSeek");
if (overview.documentOverflow > 1 || mobile.documentOverflow > 1) failures.push("桌面或移动端存在文档级横向溢出");
if (capacity.initial.panel !== "capacity" || capacity.initial.total !== "32.1× FFN" || capacity.initial.active !== "1.13× FFN") failures.push("V3 稀疏容量初始账异常");
@@ -835,12 +921,20 @@ if (artifactBoundary.layer4Period.domains[2].effect !== "PERIOD − EOS · ΔTV
if (artifactBoundary.layer4Newline.activeContrast !== "newline_minus_eos" || artifactBoundary.layer4Newline.trackToken !== "↵" || !artifactBoundary.layer4Newline.depthTitle.includes("换行")) failures.push("换行边界替换切换异常");
if (artifactBoundary.layer4Full.activeScope !== "full_input" || !artifactBoundary.layer4Full.note.includes("完整输入") || artifactBoundary.layer4Full.domains[0].values[0].value === artifactBoundary.layer4Newline.domains[0].values[0].value) failures.push("边界控制完整输入 scope 异常");
if (artifactBoundary.layer4FullToken.activeMode !== "token_weighted" || artifactBoundary.restored.activeLayer !== "L1" || artifactBoundary.restored.activeScope !== "target_content" || artifactBoundary.restored.activeMode !== "prompt_balanced" || artifactBoundary.restored.activeContrast !== "x_minus_eos") failures.push("边界控制聚合口径或恢复状态异常");
if (artifactRole.layer1Assistant.panel !== "role" || artifactRole.layer1Assistant.levelCards !== 4 || artifactRole.layer1Assistant.domainCards !== 4 || artifactRole.layer1Assistant.depthRows !== 4 || artifactRole.layer1Assistant.depthCells !== 24 || artifactRole.layer1Assistant.exact !== "BYTE-EXACT" || artifactRole.layer1Assistant.causalCards !== 3 || artifactRole.layer1Assistant.batchCells !== 6) failures.push("角色词头单 ID 控制结构或独立复跑闸门异常");
if (artifactRole.layer1Assistant.domains[0].values.map((cell) => cell.value).join("/") !== "0.056/0.059/0.062/0.056" || artifactRole.layer1Assistant.domains[0].effect !== "U→A − OFFICIAL · ΔTV +0.003" || !artifactRole.layer1Assistant.domains[0].ci.includes("-0.003, +0.007")) failures.push("L1 英文角色词头 system-edge 统计异常");
if (!artifactRole.layer1Assistant.domains[0].stability.includes("S0 79.7% · S1 84.6%") || !artifactRole.layer1Assistant.domains[0].direct.includes("S0 0.024 · S1 0.021") || artifactRole.layer1Assistant.summary.join("|") !== ".0222 / .0218|.0263 / .0253|34,488 / 34,488|12↑12↓ / 13↑11↓") failures.push("角色词头直接效应、对齐率或总账异常");
if (artifactRole.layer5X.activeContrast !== "target_x_minus_official" || artifactRole.layer5X.targetHead !== "x" || !artifactRole.layer5X.depthTitle.includes("普通 token")) failures.push("角色词头 U→x 层或 contrast 切换异常");
if (artifactRole.layer5Suffix.domains.some((domain) => domain.effect !== "SUFFIX A→U − OFFICIAL · ΔTV +0.000") || artifactRole.layer5Suffix.targetHead !== "User" || artifactRole.layer5Suffix.suffixHead !== "User" || !artifactRole.layer5Suffix.domains.every((domain) => domain.direct.includes("S0 0.000 · S1 0.000"))) failures.push("后置角色词头 causal suffix 负对照异常");
if (artifactRole.layer5FullSuffix.activeScope !== "full_input" || !artifactRole.layer5FullSuffix.note.includes("suffix 自身") || artifactRole.layer5FullSuffix.domains[0].values[0].value === artifactRole.layer5Suffix.domains[0].values[0].value) failures.push("角色词头完整输入 scope 异常");
if (artifactRole.layer5FullToken.activeMode !== "token_weighted" || artifactRole.restored.activeLayer !== "L1" || artifactRole.restored.activeScope !== "target_content" || artifactRole.restored.activeMode !== "prompt_balanced" || artifactRole.restored.activeContrast !== "target_assistant_minus_official" || artifactRole.restored.targetHead !== "Assistant" || artifactRole.restored.suffixHead !== "Assistant") failures.push("角色词头聚合口径或恢复状态异常");
if (artifactRole.layer1Assistant.batchValues.join("|") !== "256 / 256|180 / 256|149 / 256|102 / 256|72 / 256|73 / 256") failures.push("角色词头 BF16 batch-content 审计异常");
if (artifactEvidence.panel !== "evidence" || artifactEvidence.layers !== 27 || artifactEvidence.executed !== 7 || artifactEvidence.split !== 1 || artifactEvidence.unloaded !== 19 || artifactEvidence.exact !== "31 / 31") failures.push("真实工件执行边界或复跑闸门异常");
if (!artifactEvidence.dependency.includes("Transformers 5.5") || !artifactEvidence.dependency.includes("4.41.2") || !artifactEvidence.boundary.includes("完整 27 层生成")) failures.push("依赖版本或未覆盖边界异常");
if (artifactEvidence.keyboardSelected !== "load" || artifactEvidence.keyboardVisible !== "load") failures.push("真实工件实验键盘 tab 导航异常");
if (home.releaseCards !== 17 || !home.firstRelease.includes("47 页不再压成摘要") || home.firstHref !== "/k3/" || home.paperCount !== "486") failures.push("首页 DeepSeek 首发入口或论文数异常");
if (papers.total !== 486 || !papers.hasFilter || papers.visible < 20 || !papers.hasCoder || !papers.hasEngram) failures.push("论文库 DeepSeek 聚光异常");
if (!mobile.menuVisible || mobile.menuOpen !== "true" || mobile.tabs !== 4 || mobile.artifactTabs !== 10 || mobile.artifactHeatCells !== 64 || mobile.corpusCohorts !== 3 || mobile.lengthDeltaCards !== 4 || mobile.templateLayers !== 6 || mobile.templateScopes !== 2 || mobile.templateModes !== 2 || mobile.templateDomainCards !== 4 || mobile.templateDepthCells !== 24 || mobile.historyLayers !== 6 || mobile.historyScopes !== 2 || mobile.historyModes !== 2 || mobile.historyEffects !== 3 || mobile.historyDomainCards !== 4 || mobile.historyDepthCells !== 24 || mobile.distanceLayers !== 6 || mobile.distanceScopes !== 2 || mobile.distanceModes !== 2 || mobile.distanceContrasts !== 2 || mobile.distanceDomainCards !== 4 || mobile.distanceDepthCells !== 24 || mobile.boundaryLayers !== 6 || mobile.boundaryScopes !== 2 || mobile.boundaryModes !== 2 || mobile.boundaryContrasts !== 3 || mobile.boundaryTokenCards !== 4 || mobile.boundaryDomainCards !== 4 || mobile.boundaryDepthCells !== 24) failures.push("移动端导航或实验异常");
if (!mobile.menuVisible || mobile.menuOpen !== "true" || mobile.tabs !== 4 || mobile.artifactTabs !== 11 || mobile.artifactHeatCells !== 64 || mobile.corpusCohorts !== 3 || mobile.lengthDeltaCards !== 4 || mobile.templateLayers !== 6 || mobile.templateScopes !== 2 || mobile.templateModes !== 2 || mobile.templateDomainCards !== 4 || mobile.templateDepthCells !== 24 || mobile.historyLayers !== 6 || mobile.historyScopes !== 2 || mobile.historyModes !== 2 || mobile.historyEffects !== 3 || mobile.historyDomainCards !== 4 || mobile.historyDepthCells !== 24 || mobile.distanceLayers !== 6 || mobile.distanceScopes !== 2 || mobile.distanceModes !== 2 || mobile.distanceContrasts !== 2 || mobile.distanceDomainCards !== 4 || mobile.distanceDepthCells !== 24 || mobile.boundaryLayers !== 6 || mobile.boundaryScopes !== 2 || mobile.boundaryModes !== 2 || mobile.boundaryContrasts !== 3 || mobile.boundaryTokenCards !== 4 || mobile.boundaryDomainCards !== 4 || mobile.boundaryDepthCells !== 24 || mobile.roleLayers !== 6 || mobile.roleScopes !== 2 || mobile.roleModes !== 2 || mobile.roleContrasts !== 3 || mobile.roleLevelCards !== 4 || mobile.roleDomainCards !== 4 || mobile.roleDepthCells !== 24) failures.push("移动端导航或实验异常");
if (mobile.offenders.length) failures.push(`移动端越界元素:${JSON.stringify(mobile.offenders)}`);
if (exceptions.length) failures.push(`浏览器异常:${exceptions.join(" | ")}`);