-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
482 lines (449 loc) · 20.2 KB
/
Copy pathapp.js
File metadata and controls
482 lines (449 loc) · 20.2 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
const state = {
data: null,
caseIndex: 0,
mode: "replay",
liveCase: null,
liveObjectUrls: [],
apiBase: "http://127.0.0.1:8001",
running: false,
revealed: false,
step: 0,
};
const labels = {
fixed4: "Fixed 4",
fixed8: "Fixed 8",
fixed12: "Fixed 12",
adaptive: "Adaptive",
optimized: "Adaptive+",
};
const viewNames = ["正面 / FRONT", "左侧 / LEFT", "背面 / BACK", "右侧 / RIGHT"];
const $ = (selector) => document.querySelector(selector);
function escapeHtml(value = "") {
return value.replace(/[&<>'"]/g, (character) => ({
"&": "&", "<": "<", ">": ">", "'": "'", '"': """,
})[character]);
}
function currentCase() {
if (state.mode === "live" && state.liveCase) return state.liveCase;
return state.data.cases[state.caseIndex];
}
function traceRun(sample) {
return sample.runs.adaptive || sample.runs.optimized;
}
function outcomeRun(sample) {
return sample.runs.optimized || sample.runs.adaptive;
}
function setHeadlineMetrics() {
const pair = state.data.paired;
$("#headline-saving").textContent = `-${(pair.latent_step_reduction * 100).toFixed(1)}%`;
$("#headline-accuracy").textContent = `${pair.accuracy_delta_percentage_points.toFixed(2)} pp`;
$("#headline-samples").textContent = pair.paired_samples.toLocaleString();
$("#headline-p").textContent = pair.mcnemar_exact_p.toFixed(3);
}
function renderViews(sample) {
$("#view-grid").innerHTML = sample.images.map((path, index) => `
<button class="view-card" type="button" data-index="${index}" aria-label="放大视角 ${index + 1}">
<img src="${path}" alt="多视角输入 ${index + 1}" />
<span>${String(index + 1).padStart(2, "0")} · ${viewNames[index] || "VIEW"}</span>
</button>
`).join("");
document.querySelectorAll(".view-card").forEach((button) => {
button.addEventListener("click", () => openImage(Number(button.dataset.index)));
});
}
function renderOptions(sample) {
$("#option-grid").innerHTML = sample.options.map((option) => {
let classes = "option";
let marker = "";
if (state.revealed && sample.ground_truth && option.key === sample.ground_truth) {
classes += " is-truth";
marker = "GROUND TRUTH";
}
const wrongPredictions = new Set(
[sample.runs.fixed12.prediction, outcomeRun(sample).prediction]
.filter((prediction) => prediction !== sample.ground_truth),
);
if (state.revealed && sample.ground_truth && wrongPredictions.has(option.key)) classes += " is-wrong-prediction";
return `
<div class="${classes}">
<span class="option-key">${option.key}</span>
<span class="option-text">${escapeHtml(option.text)}</span>
<span class="option-state">${marker}</span>
</div>
`;
}).join("");
}
function railHtml(type, activeSteps = 0, exitStep = null) {
return Array.from({ length: 12 }, (_, index) => {
const step = index + 1;
const classes = ["latent-node"];
if (type === "fixed" && step <= activeSteps) classes.push("is-active");
if (type === "fixed" && step > activeSteps) classes.push("is-muted");
if (type === "adaptive" && step <= activeSteps) classes.push("is-active");
if (type === "adaptive" && exitStep && step === exitStep) classes.push("is-exit");
if (type === "adaptive" && exitStep && step > exitStep) classes.push("is-muted");
return `<span class="${classes.join(" ")}">${step}</span>`;
}).join("");
}
function renderRails(sample, activeSteps = 0) {
const trace = traceRun(sample);
const outcome = outcomeRun(sample);
const exitStep = state.revealed ? trace.steps : null;
$("#fixed-rail").innerHTML = railHtml("fixed", sample.runs.fixed12.steps, null);
$("#adaptive-rail").innerHTML = railHtml("adaptive", activeSteps, exitStep);
$("#fixed-exit").textContent = `${sample.runs.fixed12.steps} steps`;
$("#adaptive-exit").textContent = state.revealed
? `${outcome.compute_steps ?? trace.steps} total steps`
: "-- steps";
}
function chartGeometry(distances) {
const width = 720;
const height = 210;
const inset = { left: 45, right: 20, top: 18, bottom: 30 };
const maxY = Math.max(0.36, ...distances) * 1.06;
const x = (index) => inset.left + (index / 11) * (width - inset.left - inset.right);
const y = (value) => inset.top + (1 - value / maxY) * (height - inset.top - inset.bottom);
return { width, height, inset, maxY, x, y };
}
function renderChart(sample, visibleSteps = 0) {
const distances = traceRun(sample).distances || [];
const geometry = chartGeometry(distances);
const shown = distances.slice(0, visibleSteps);
const points = shown.map((value, index) => `${geometry.x(index)},${geometry.y(value)}`).join(" ");
const areaPoints = shown.length
? `${geometry.x(0)},${geometry.height - geometry.inset.bottom} ${points} ${geometry.x(shown.length - 1)},${geometry.height - geometry.inset.bottom}`
: "";
const thresholdY = geometry.y(state.data.meta.epsilon);
const circles = shown.map((value, index) => `
<circle class="signal-point ${index === shown.length - 1 ? "is-current" : ""}"
cx="${geometry.x(index)}" cy="${geometry.y(value)}" r="4" />
`).join("");
const xLabels = [0, 3, 7, 11].map((index) => `
<text class="signal-axis-text" x="${geometry.x(index)}" y="198" text-anchor="middle">${index + 1}</text>
`).join("");
$("#signal-chart").innerHTML = `
<svg viewBox="0 0 ${geometry.width} ${geometry.height}" role="img" aria-label="latent hidden-state convergence distances">
<line class="signal-threshold" x1="${geometry.inset.left}" x2="${geometry.width - geometry.inset.right}" y1="${thresholdY}" y2="${thresholdY}" />
<text class="signal-axis-text" x="6" y="${thresholdY + 3}">0.04</text>
${areaPoints ? `<polygon class="signal-area" points="${areaPoints}" />` : ""}
${points ? `<polyline class="signal-line" points="${points}" />` : ""}
${circles}
${xLabels}
</svg>
`;
}
function updateInspector(sample, step) {
const inspector = $("#step-inspector");
const trace = traceRun(sample);
const distance = (trace.distances || [])[step - 1];
const isBelow = Number.isFinite(distance) && distance < state.data.meta.epsilon;
const isExit = step === trace.steps && trace.exit_reason === "converged";
inspector.querySelector("strong").textContent = String(step || 0).padStart(2, "0");
const values = inspector.querySelectorAll("dd");
values[0].textContent = Number.isFinite(distance) ? distance.toFixed(4) : "--";
values[1].textContent = isExit ? "EXIT: CONVERGED" : isBelow ? "below threshold" : step ? "continue" : "waiting";
}
function resultCard(name, run) {
const kind = ["adaptive", "optimized"].includes(name) ? "adaptive" : "fixed";
const exitNames = {
converged: "hidden-state converged",
cascade_vote: "hard-case budget vote",
max_steps: "full latent budget",
model_end: "model ended latent phase",
};
const exitLabel = exitNames[run.exit_reason] || run.exit_reason || "--";
const verdict = run.correct === null || run.correct === undefined
? { className: "neutral", text: "NO REFERENCE" }
: run.correct
? { className: "correct", text: "CORRECT" }
: { className: "wrong", text: "INCORRECT" };
const timeLabel = state.mode === "live" ? "GPU TIME" : "RECORDED TIME";
const memoryMetric = Number.isFinite(run.peak_vram_gib)
? `<div><span>PEAK VRAM</span><strong>${run.peak_vram_gib.toFixed(2)} GiB</strong></div>`
: "";
const confidence = run.choice_confidence;
const confidenceMetric = Number.isFinite(confidence?.confidence)
? `<div><span>${confidence.source === "budget_vote" ? "VOTE AGREEMENT" : "CHOICE CONF."}</span><strong>${(confidence.confidence * 100).toFixed(1)}%</strong></div>`
: "";
const stepValue = run.compute_steps ?? run.steps;
const stepLabel = name === "optimized" && run.run_count > 1 ? "TOTAL LATENT" : "LATENT PADS";
return `
<article class="result-card ${kind}">
<div class="result-card-head">
<div>
<div class="result-card-name">${labels[name]}</div>
<div class="result-card-sub">${state.mode === "live" ? "LIVE CHECKPOINT INFERENCE" : "RECORDED CHECKPOINT INFERENCE"}</div>
</div>
<span class="verdict ${verdict.className}">${verdict.text}</span>
</div>
<div class="result-answer"><span>PREDICTION</span><strong>${run.prediction || "--"}</strong></div>
<div class="result-metrics">
<div><span>${stepLabel}</span><strong>${stepValue}</strong></div>
<div><span>${timeLabel}</span><strong>${run.latency_s.toFixed(2)} s</strong></div>
<div><span>EXIT</span><strong>${escapeHtml(exitLabel)}</strong></div>
${memoryMetric}
${confidenceMetric}
</div>
</article>
`;
}
function renderComparison(sample) {
const researchName = sample.runs.optimized ? "optimized" : "adaptive";
$("#ground-truth").textContent = sample.ground_truth ? `Ground truth ${sample.ground_truth}` : "Reference not provided";
$("#comparison-cards").innerHTML = resultCard("fixed12", sample.runs.fixed12) + resultCard(researchName, sample.runs[researchName]);
$("#reasoning-columns").innerHTML = ["fixed12", researchName].map((name) => `
<div class="reasoning-column">
<strong>${labels[name].toUpperCase()}</strong>
<p>${escapeHtml(sample.runs[name].reasoning || sample.runs[name].answer || "No tagged reasoning returned.")}</p>
</div>
`).join("");
}
function renderBenchmark() {
$("#benchmark-grid").innerHTML = state.data.overall.map((row) => `
<article class="benchmark-card ${row.condition === "adaptive" ? "is-adaptive" : ""}">
<div class="benchmark-name">${labels[row.condition].toUpperCase()} ${row.condition === "adaptive" ? "<span>PROPOSED</span>" : ""}</div>
<div class="benchmark-value">${(row.accuracy * 100).toFixed(2)}%</div>
<div class="benchmark-caption">HOLDOUT ACCURACY · n=${row.samples}</div>
<div class="metric-track"><span style="width:${row.accuracy * 100}%"></span></div>
<div class="benchmark-meta"><span>${row.correct}/${row.samples} correct</span><span>${row.mean_latent_steps.toFixed(2)} steps</span></div>
</article>
`).join("");
}
function renderCase() {
const sample = currentCase();
state.revealed = false;
state.step = 0;
$("#case-id").textContent = sample.slug.toUpperCase();
$("#question-text").textContent = sample.question;
$("#case-note").textContent = sample.note || "当前结果来自服务器上的 Stage-1 checkpoint 实时推理。";
$("#playback-status").className = "playback-status";
$("#playback-status").innerHTML = "<span></span>就绪";
renderViews(sample);
renderOptions(sample);
renderRails(sample, 0);
renderChart(sample, 0);
updateInspector(sample, 0);
renderComparison(sample);
}
function sleep(milliseconds) {
return new Promise((resolve) => window.setTimeout(resolve, milliseconds));
}
async function animateTrace(button = null) {
if (state.running) return;
state.running = true;
state.revealed = false;
const sample = currentCase();
const trace = traceRun(sample);
const outcome = outcomeRun(sample);
const status = $("#playback-status");
if (button) button.disabled = true;
status.className = "playback-status is-running";
status.innerHTML = `<span></span>${state.mode === "live" ? "正在绘制本次 GPU trace" : "正在回放原始 trace"}`;
renderOptions(sample);
for (let step = 1; step <= trace.steps; step += 1) {
state.step = step;
renderRails(sample, step);
renderChart(sample, step);
updateInspector(sample, step);
await sleep(window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 10 : 210);
}
state.revealed = true;
renderRails(sample, trace.steps);
renderOptions(sample);
renderComparison(sample);
status.className = "playback-status is-done";
const completion = outcome.escalated
? `困难样本,已追加 ${outcome.run_count - 1} 次预算投票`
: trace.exit_reason === "converged"
? "收敛且通过门控,提前退出"
: "未收敛,使用完整预算";
status.innerHTML = `<span></span>${completion}`;
if (button) {
button.disabled = false;
button.querySelector("span:last-child").textContent = "重播真实推理轨迹";
}
state.running = false;
}
function playTrace() {
return animateTrace($("#run-button"));
}
function openImage(index) {
const sample = currentCase();
const modal = $("#image-modal");
$("#modal-image").src = sample.images[index];
$("#modal-image").alt = `多视角输入 ${index + 1}`;
$("#modal-caption").textContent = `${String(index + 1).padStart(2, "0")} · ${viewNames[index] || "VIEW"} · ${state.mode === "live" ? "LIVE GPU INPUT" : "REAL MINDCUBE INPUT"}`;
modal.hidden = false;
$("#modal-close").focus();
}
function closeImage() {
$("#image-modal").hidden = true;
}
function setLiveProgress(message, className = "") {
const progress = $("#live-progress");
progress.textContent = message;
progress.className = `live-progress ${className}`.trim();
}
function resetLiveOutput() {
$("#fixed-rail").innerHTML = railHtml("fixed", 12, 12);
$("#adaptive-rail").innerHTML = railHtml("adaptive", 0, null);
$("#fixed-exit").textContent = "12 steps";
$("#adaptive-exit").textContent = "-- steps";
$("#signal-chart").innerHTML = "";
const inspector = $("#step-inspector");
inspector.querySelector("strong").textContent = "00";
const values = inspector.querySelectorAll("dd");
values[0].textContent = "--";
values[1].textContent = "waiting";
$("#playback-status").className = "playback-status";
$("#playback-status").innerHTML = "<span></span>等待 GPU 推理";
}
function setMode(mode) {
if (state.running || !state.data) return;
state.mode = mode;
const live = mode === "live";
$("#replay-mode").classList.toggle("is-active", !live);
$("#live-mode").classList.toggle("is-active", live);
$("#replay-mode").setAttribute("aria-pressed", String(!live));
$("#live-mode").setAttribute("aria-pressed", String(live));
$("#replay-picker").hidden = live;
$("#live-composer").hidden = !live;
$("#replay-shell").hidden = live;
$("#comparison-section").hidden = live && !state.liveCase;
$("#workbench-title").textContent = live ? "实时 GPU 推理" : "真实样例对比";
$("#run-origin").innerHTML = `<span></span>${live ? "LIVE RTX 5090 ENDPOINT" : "REAL EXPERIMENT REPLAY"}`;
if (live) {
if (state.liveCase) renderCase();
else resetLiveOutput();
checkGpuHealth();
} else {
renderCase();
}
}
async function checkGpuHealth() {
const indicator = $("#gpu-health");
indicator.className = "gpu-health";
indicator.innerHTML = "<i></i>连接 GPU";
try {
const response = await fetch(`${state.apiBase}/health`, { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const health = await response.json();
indicator.className = health.gpu_available ? "gpu-health is-online" : "gpu-health is-error";
indicator.innerHTML = `<i></i>${health.gpu_available ? escapeHtml(health.gpu || "GPU ONLINE") : "GPU 不可用"}`;
setLiveProgress(
health.model_loaded ? "Checkpoint 已驻留显存,可以直接运行。" : "GPU 在线;首次请求将加载 checkpoint,预计需要几十秒。",
);
} catch (_) {
indicator.className = "gpu-health is-error";
indicator.innerHTML = "<i></i>接口未连接";
setLiveProgress("未连接实时接口。请确认服务器 API 与本地 SSH 隧道均已启动。", "is-error");
}
}
function renderUploadPreviews() {
state.liveObjectUrls.forEach((url) => URL.revokeObjectURL(url));
const files = [...$("#live-images").files];
state.liveObjectUrls = files.map((file) => URL.createObjectURL(file));
$("#upload-previews").innerHTML = files.length
? files.slice(0, 4).map((file, index) => `
<div class="upload-preview">
<img src="${state.liveObjectUrls[index]}" alt="待推理视角 ${index + 1}" />
<span>${String(index + 1).padStart(2, "0")} · ${escapeHtml(file.name)}</span>
</div>
`).join("")
: '<div class="upload-empty">尚未选择图片</div>';
if (files.length) setLiveProgress(`已选择 ${files.length} 张图片;将按当前顺序送入模型。`);
}
function responseError(payload, status) {
if (typeof payload?.detail === "string") return payload.detail;
if (Array.isArray(payload?.detail)) return payload.detail.map((item) => item.msg).join(";");
return `实时接口返回 HTTP ${status}`;
}
async function runLiveInference(event) {
event.preventDefault();
if (state.running) return;
const form = $("#live-form");
if (!form.reportValidity()) return;
const files = [...$("#live-images").files];
if (files.length < 2 || files.length > 4) {
setLiveProgress("请选择 2–4 张同一场景的多视角图片。", "is-error");
return;
}
const payload = new FormData(form);
files.forEach((file) => payload.append("images", file, file.name));
const submit = $("#live-submit");
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), 300000);
state.running = true;
submit.disabled = true;
submit.querySelector("span:last-child").textContent = "5090 推理中…";
setLiveProgress("正在运行 Fixed-12 基线与 Adaptive+;困难样本会自动追加 4/8 步投票。", "is-running");
$("#playback-status").className = "playback-status is-running";
$("#playback-status").innerHTML = "<span></span>服务器正在生成真实 trace";
try {
const response = await fetch(`${state.apiBase}/infer/compare`, {
method: "POST",
body: payload,
signal: controller.signal,
});
const result = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(responseError(result, response.status));
state.liveCase = {
slug: "LIVE-GPU",
question: result.question,
options: result.options,
ground_truth: result.reference_answer,
images: [...state.liveObjectUrls],
note: `RTX 5090 实时运行完成;识别为 ${result.task_type}(${result.task_route_source}),Adaptive+ ${result.runs.optimized.escalated ? `触发 ${result.runs.optimized.run_count} 路推理` : "未触发追加预算"};对比请求总耗时 ${result.total_latency_s.toFixed(2)} 秒。`,
runs: result.runs,
};
state.running = false;
renderCase();
$("#comparison-section").hidden = false;
setLiveProgress("推理完成。下方显示本次答案、耗时、显存与收敛轨迹。", "is-done");
await animateTrace();
$("#comparison-section").scrollIntoView({ behavior: "smooth", block: "nearest" });
} catch (error) {
state.running = false;
resetLiveOutput();
const message = error.name === "AbortError" ? "推理超过 5 分钟,已停止等待。" : error.message;
setLiveProgress(message, "is-error");
} finally {
window.clearTimeout(timeout);
submit.disabled = false;
submit.querySelector("span:last-child").textContent = "运行 GPU 对比";
}
}
async function init() {
try {
const response = await fetch("data/demo-data.json");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
state.data = await response.json();
$("#case-select").innerHTML = state.data.cases.map((sample, index) => `
<option value="${index}">${String(index + 1).padStart(2, "0")} · ${escapeHtml(sample.label)}</option>
`).join("");
setHeadlineMetrics();
renderBenchmark();
renderCase();
renderUploadPreviews();
} catch (error) {
document.body.innerHTML = `<main class="load-error"><h1>Demo data failed to load.</h1><p>${escapeHtml(error.message)}</p><p>Run this directory through a local HTTP server instead of opening index.html directly.</p></main>`;
}
}
$("#case-select").addEventListener("change", (event) => {
if (state.running) return;
state.caseIndex = Number(event.target.value);
renderCase();
});
$("#replay-mode").addEventListener("click", () => setMode("replay"));
$("#live-mode").addEventListener("click", () => setMode("live"));
$("#live-images").addEventListener("change", renderUploadPreviews);
$("#live-form").addEventListener("submit", runLiveInference);
$("#run-button").addEventListener("click", playTrace);
$("#modal-close").addEventListener("click", closeImage);
$("#image-modal").addEventListener("click", (event) => {
if (event.target === $("#image-modal")) closeImage();
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") closeImage();
});
init();