Spaces:
Running on Zero
Running on Zero
Show live inference nodes and per-stage timings
Browse filesFiles changed (5)
- app.py+1-2
- inference.py+43-16
- workbench/index.html+7-3
- workbench/lab.css+30-1
- workbench/lab.js+87-11
39 unmodified lines404142434445464739 unmodified linesraise gr.Error('Select a listed image pair.')if CHECKPOINTS is None:raise gr.Error('GPU weights are unavailable.')for step, result in trace_case(CASES[case_name], CHECKPOINTS):yield {'step': step, **result}def catalog():39 unmodified lines4041424344454639 unmodified linesraise gr.Error('Select a listed image pair.')if CHECKPOINTS is None:raise gr.Error('GPU weights are unavailable.')yield from trace_case(CASES[case_name], CHECKPOINTS)def catalog():
61 unmodified lines6263646566675 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611761 unmodified linesdef trace_case(record, checkpoints):import torchfrom caption.runner import beam, image_features, initializefrom judge.questions import stage1_questions, stage2_questions5 unmodified linesdataset = 'levir'media_root = ROOT / 'public'config = profile(dataset)name = record['name']row = {'name': name, 'timings': {}}started = perf_counter()initialize()features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')row['feature_shape'] = list(features.shape)row['timings']['encode'] = perf_counter() - startedyield 'encode', row.copy()started = perf_counter()row['captions'] = beam(dataset, features, checkpoints.generator, 'cuda')[0]row['timings']['beam'] = perf_counter() - startedyield 'beam', row.copy()rows = {name: row}first = list(stage1_questions(dataset, [record], rows))def score_stage(stage, questions):started = perf_counter()runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')try:row[f'stage{stage}'] = score(runtime, bundle, questions)[name]finally:del bundlegc.collect()torch.cuda.empty_cache()row['timings'][f'stage{stage}'] = perf_counter() - startedscore_stage(1, first)anchor = max(row['stage1'], key=lambda pair: pair[1])[0]row['anchor'] = anchoryield 'stage1', row.copy()_, changed = next_stage(dataset, row['captions'], anchor, config['templates'])row['changed'] = changedyield 'gate', row.copy()if changed:second = list(stage2_questions(dataset, [record], rows, config['templates']))row['eligible'] = list(second[0]['native_candidate_indices'].values()) if second else [index for index, _ in row['stage2']]yield 'filter', {key: value for key, value in row.items() if key != 'stage2'}if second:score_stage(2, second)yield 'stage2', row.copy()yield 'done', {**row, 'final': decision(dataset, row, config['beta'], config['templates'])}61 unmodified lines6263646566676869707172737475767778795 unmodified lines85868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314461 unmodified linesdef trace_case(record, checkpoints):name = record['name']timings = {}row = {'name': name, 'timings': timings}def active(activity):return {'name': name, 'activity': activity, 'timings': timings.copy()}def finished(step, **extra):return {**row, 'timings': timings.copy(), 'step': step, **extra}yield active('runtime')started = perf_counter()import torchfrom caption.runner import beam, image_features, initializefrom judge.questions import stage1_questions, stage2_questions5 unmodified linesdataset = 'levir'media_root = ROOT / 'public'config = profile(dataset)initialize()timings['runtime'] = perf_counter() - startedyield active('encode')started = perf_counter()features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')row['feature_shape'] = list(features.shape)timings['encode'] = perf_counter() - startedyield finished('encode')yield active('beam')started = perf_counter()row['captions'] = beam(dataset, features, checkpoints.generator, 'cuda')[0]timings['beam'] = perf_counter() - startedyield finished('beam')rows = {name: row}first = list(stage1_questions(dataset, [record], rows))def score_stage(stage, questions):key = f'stage{stage}'yield active(f'{key}_load')started = perf_counter()runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')timings[f'{key}_load'] = perf_counter() - startedtry:yield active(f'{key}_score')started = perf_counter()row[key] = score(runtime, bundle, questions)[name]timings[f'{key}_score'] = perf_counter() - startedfinally:del bundlegc.collect()torch.cuda.empty_cache()timings[key] = timings[f'{key}_load'] + (perf_counter() - started)yield from score_stage(1, first)anchor = max(row['stage1'], key=lambda pair: pair[1])[0]row['anchor'] = anchoryield finished('stage1')yield active('gate')_, changed = next_stage(dataset, row['captions'], anchor, config['templates'])row['changed'] = changedyield finished('gate')if changed:yield active('filter')second = list(stage2_questions(dataset, [record], rows, config['templates']))row['eligible'] = list(second[0]['native_candidate_indices'].values()) if second else [index for index, _ in row['stage2']]yield {key: value for key, value in finished('filter').items() if key != 'stage2'}if second:yield from score_stage(2, second)yield finished('stage2')yield active('output')started = perf_counter()final = decision(dataset, row, config['beta'], config['templates'])timings['output'] = perf_counter() - startedyield finished('done', final=final)
5 unmodified lines67891011121328 unmodified lines424344454647485 unmodified lines<meta name="theme-color" content="#f7f8f6"><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cpath d='M3 12 16 5l13 7-13 7L3 12Zm0 7 13 7 13-7' fill='none' stroke='%230f766e' stroke-width='2.5'/%3E%3C/svg%3E"><title>Critique-then-Rerank · Decision Lab</title><link rel="stylesheet" href="./workbench/lab.css?v=decision-story"><script type="module" src="./workbench/lab.js?v=zerogpu-session"></script></head><body><header class="topbar">28 unmodified lines<div class="toolbar"><div class="transport"><button type="button" id="live" data-t="live">Run on GPU</button><button type="button" id="replay" data-t="play">▷ Step through</button></div></div><p class="run-status" id="status" role="status"></p><div id="run-output"></div><a class="trace-link" href="#decision-trace" data-t="followTrace">Follow the decision trace ↓</a></section>5 unmodified lines67891011121328 unmodified lines42434445464748495051525 unmodified lines<meta name="theme-color" content="#f7f8f6"><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cpath d='M3 12 16 5l13 7-13 7L3 12Zm0 7 13 7 13-7' fill='none' stroke='%230f766e' stroke-width='2.5'/%3E%3C/svg%3E"><title>Critique-then-Rerank · Decision Lab</title><link rel="stylesheet" href="./workbench/lab.css?v=live-nodes"><script type="module" src="./workbench/lab.js?v=live-nodes"></script></head><body><header class="topbar">28 unmodified lines<div class="toolbar"><div class="transport"><button type="button" id="live" data-t="live">Run on GPU</button><button type="button" id="replay" data-t="play">▷ Step through</button></div></div><section class="live-monitor" aria-labelledby="monitor-title"><div class="monitor-head"><h4 id="monitor-title" data-t="monitor">Runtime monitor</h4><span id="run-elapsed" class="elapsed" hidden><span data-t="elapsed">Elapsed</span> <time id="run-clock"></time></span></div><ol class="live-nodes" id="live-nodes" role="list"></ol><div class="monitor-status"><p class="run-status" id="status" role="status"></p><progress id="live-progress" aria-labelledby="monitor-title" hidden></progress></div></section><div id="run-output"></div><a class="trace-link" href="#decision-trace" data-t="followTrace">Follow the decision trace ↓</a></section>
116 unmodified lines11711811912012112212382 unmodified lines20620720820921021121221311 unmodified lines225226227228116 unmodified lines#live:not(:disabled):hover { background: #0c615a; }.chip { font: .69rem var(--mono); border: 1px solid var(--line); border-radius: 999px; padding: 6px 9px; color: var(--green); background: var(--deep); }.chip[data-source='live'] { color: var(--warm); border-color: var(--warm); background: var(--warm-wash); }.run-status { margin-block: 8px 12px; min-height: 1.2rem; font-size: .8rem; color: var(--dim); }.pipeline { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 6px; }.pipeline button { min-width: 0; min-height: 65px; padding: 7px; text-align: start; display: flex; flex-direction: column; justify-content: space-between; gap: 5px; }.pipeline small { font: .64rem/1.2 var(--mono); color: var(--dim); }82 unmodified linesfooter { border-top: 1px solid var(--line); display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px; color: var(--dim); padding-block: 16px 22px; }@media (prefers-reduced-motion: no-preference) {.deck > div, .route-root, .branches, .comparison > div:last-child, .explorer-pool .winner, .pipeline [data-state='done'][aria-current='step'] { animation: arrive .24s ease-out both; }@keyframes arrive { from { opacity: .35; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }}@media (max-width: 960px) {.case-grid { grid-template-columns: repeat(2, minmax(0,1fr)); }.pipeline { grid-template-columns: repeat(3, minmax(0,1fr)); }11 unmodified lines.case { grid-template-columns: 38px minmax(0,1fr); padding: 6px; gap: 6px; }.case-number { inset: 19px auto auto 7px; }.protocol > div { padding: 8px 6px; }}116 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514682 unmodified lines22923023123223323423523623723823911 unmodified lines251252253254255256257116 unmodified lines#live:not(:disabled):hover { background: #0c615a; }.chip { font: .69rem var(--mono); border: 1px solid var(--line); border-radius: 999px; padding: 6px 9px; color: var(--green); background: var(--deep); }.chip[data-source='live'] { color: var(--warm); border-color: var(--warm); background: var(--warm-wash); }.live-monitor { margin-block: 12px; padding: clamp(10px, 1.4vw, 16px); border: 1px solid var(--line); border-radius: 9px; background-color: var(--deep); background-image: radial-gradient(#94b5a652 1px, transparent 1px); background-size: 14px 14px; }.monitor-head { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 12px; margin-bottom: 10px; }.monitor-head h4 { color: var(--green); font: 700 .75rem/1.35 var(--mono); letter-spacing: .07em; text-transform: uppercase; }.elapsed { color: var(--dim); font: .72rem/1.35 var(--mono); }.elapsed time { color: var(--ink); font-weight: 700; }.live-nodes { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 13px; list-style: none; margin: 0; padding: 0; }.live-nodes li { position: relative; min-width: 0; min-height: 63px; display: grid; align-content: start; gap: 4px; border: 1px solid var(--line); border-radius: 7px; padding: 7px; background: var(--panel); overflow-wrap: anywhere; }.live-nodes li:not(:nth-child(3n))::after { content: ''; position: absolute; top: 16px; left: 100%; width: 14px; height: 2px; background: var(--line); }.live-nodes li[data-state='done']::after { background: var(--green); }.live-nodes li > div { display: flex; align-items: center; gap: 5px; }.node-port { display: grid; place-items: center; flex: none; inline-size: 19px; block-size: 19px; border: 1px solid var(--line); border-radius: 5px; color: var(--dim); font: .65rem/1 var(--mono); }.live-nodes strong { font-size: .77rem; line-height: 1.15; }.live-nodes small { color: var(--dim); font-size: .69rem; line-height: 1.25; }.node-timing { color: var(--dim); font: .65rem/1.25 var(--mono); }.live-nodes [data-state='done'] { border-color: #8bb9a6; background: var(--green-wash); }.live-nodes [data-state='done'] .node-port { background: var(--green); border-color: var(--green); color: var(--panel); }.live-nodes [data-state='running'], .pipeline [data-state='running'] { opacity: 1; border-color: var(--green); background: var(--panel); outline: 2px solid #0f766e33; outline-offset: 1px; }.live-nodes [data-state='running'] .node-port { color: var(--green); border-color: var(--green); background: var(--green-wash); }.live-nodes [data-state='running'] small { color: var(--green); font-weight: 700; }.live-nodes [data-state='skipped'], .live-nodes [data-state='direct'] { border-style: dashed; background: #eff1ef; color: var(--dim); }.live-nodes [data-state='failed'] { border-color: var(--warm); background: var(--warm-wash); }.monitor-status { min-height: 36px; margin-top: 8px; padding: 7px 9px; border-radius: 6px; background: var(--panel); }.run-status { font-size: .8rem; line-height: 1.45; color: var(--dim); }#live-progress { display: block; width: 100%; height: 4px; margin-top: 6px; accent-color: var(--green); }.pipeline { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 6px; }.pipeline button { min-width: 0; min-height: 65px; padding: 7px; text-align: start; display: flex; flex-direction: column; justify-content: space-between; gap: 5px; }.pipeline small { font: .64rem/1.2 var(--mono); color: var(--dim); }82 unmodified linesfooter { border-top: 1px solid var(--line); display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px; color: var(--dim); padding-block: 16px 22px; }@media (prefers-reduced-motion: no-preference) {.deck > div, .route-root, .branches, .comparison > div:last-child, .explorer-pool .winner, .pipeline [data-state='done'][aria-current='step'] { animation: arrive .24s ease-out both; }.live-nodes [data-state='running'] .node-port { animation: node-signal 1.65s ease-in-out infinite; }@keyframes arrive { from { opacity: .35; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }@keyframes node-signal { 50% { box-shadow: 0 0 0 3px #0f766e32; } }}@media (prefers-reduced-motion: reduce) { #live-progress { display: none; } }@media (max-width: 960px) {.case-grid { grid-template-columns: repeat(2, minmax(0,1fr)); }.pipeline { grid-template-columns: repeat(3, minmax(0,1fr)); }11 unmodified lines.case { grid-template-columns: 38px minmax(0,1fr); padding: 6px; gap: 6px; }.case-number { inset: 19px auto auto 7px; }.protocol > div { padding: 8px 6px; }.live-nodes { grid-template-columns: repeat(2, minmax(0, 1fr)); }.live-nodes li:nth-child(n)::after { display: none; }.live-nodes li:nth-child(odd)::after { display: block; }}
3 unmodified lines4567899 unmodified lines1920212223242 unmodified lines272829303132112 unmodified lines1451461471481491501 unmodified line15215315415515615715815916012 unmodified lines173174175176177178179180181182183184185186187188189190191131 unmodified lines3233243253263273281 unmodified line3303313323333343353362 unmodified lines3393403413423433443453469 unmodified lines3563573583593603613 unmodified linesconst escape = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[char]));const steps = ['encode', 'generate', 'score', 'lock', 'filter', 'rerank', 'output'];const events = ['encode', 'beam', 'stage1', 'gate', 'filter', 'stage2', 'done'];const labels = {project: ['Project ↗','项目主页 ↗'], headline: ['The best caption isn’t always ranked first.','排名第一的,不一定是最好的描述。'],lede: ['Critique-then-Rerank looks at both images to decide whether the scene changed, then selects the caption that best describes the change.','Critique-then-Rerank 先看双时相影像判断场景是否变化,再从现有候选中选出最符合影像的描述。'],9 unmodified linesencode: ['Encode the pair','编码双图'], generate: ['Generate Beam-15','生成 Beam-15'], score: ['Score all candidates','全候选评分'], lock: ['Route by state','按状态分流'], filter: ['Filter the pool','过滤候选池'],rerank: ['Compare + calibrate','精排与长度校准'], output: ['Map to original Beam ID','回映原始 Beam ID'],play: ['▷ Step through','▷ 逐步演示'], pause: ['Ⅱ Pause','Ⅱ 暂停演示'], live: ['Run on GPU','开始 GPU 推理'],};const inferenceHash = '#trace-title';const hubOrigin = 'https://huggingface.co';2 unmodified linesconst text = (en, zh) => lang === 'zh' ? zh : en;const label = key => text(...labels[key]);let catalog, selected, trace, phase = 3, mode = 'archive', liveEvent, busy = false, follow = true, failure = null, timer;let view = 'swipe', divider = 50, beta = 0.12;let activeTask = 0, alternate = false, verifySwap = false, rankedView = false;112 unmodified linesreturn mode === 'archive' ? steps.length - 1 : events.indexOf(liveEvent);}function render() {const reached = level();const completed = timer ? phase : reached;1 unmodified lineconst focused = document.activeElement?.dataset.step;const early = trace?.changed === false && completed >= 3;const direct = trace?.changed === true && completed >= 4 && trace.eligible?.length <= 1;byId('pipeline').innerHTML = steps.map((step, index) => {const skipped = (index === 4 || index === 5) && early;const state = skipped ? 'skipped' : (direct && index === 5) ? 'direct' : index <= completed ? 'done' : 'pending';const title = skipped ? text('Skipped — Early Exit','已跳过 — 提前退出') : state === 'direct' ? text('No Stage 2 call','未调用 Stage 2') : label(step);return `<button type="button" data-step="${index}" data-state="${state}" ${index > completed && !skipped ? 'disabled' : ''} ${phase === index && reached >= 0 ? 'aria-current="step"' : ''}><small>0${index + 1} / ${short[index]}</small><strong>${title}</strong></button>`;}).join('');12 unmodified linesbyId('live').disabled = busy || !catalog.live;const status = failure ? failureMessage(failure) : (mode === 'archive'? (catalog.live ? text('Select a step to see how the model made its decision.', '点击任意步骤,查看模型如何做出决策。') : text('Explore the case below. Live inference is temporarily unavailable.', '可以继续查看案例,实时推理暂不可用。')): ({encode: text('Images encoded. Generating candidates…','双图编码完成,正在生成候选…'),beam: text('Beam-15 ready. Stage 1 is scoring the pool…','Beam-15 已生成,第一阶段正在评分…'),stage1: text('Stage 1 scored all candidates.','第一阶段已完成全候选评分。'),gate: trace?.changed ? text('Changed locked. Filtering the pool…','已锁定有变化,正在过滤候选…') : text('Unchanged locked. Stage 2 skipped.','已锁定无变化,跳过第二阶段。'),filter: text('Change pool ready. Comparing the eligible captions…','变化候选池已就绪,正在比较保留的描述…'),stage2: text('Stage 2 scored the pool. Mapping the final choice…','第二阶段评分完成,正在回映最终选择…'),done: text('Inference complete. Inspect any step.','推理完成,可回看任意步骤。'),}[liveEvent] ?? text('Queued for a ZeroGPU lease…','正在等待 ZeroGPU 分配…')));if (byId('status').textContent !== status) byId('status').textContent = status;byId('inspector').innerHTML = reached < 0 ? `<div class="empty">${failure? text('No live result. Choose Step through to explore this pair without using GPU quota.', '���次没有实时结果。点击「逐步演示」可查看这组影像的推理流程,不消耗 GPU 配额。'): text('The trace will open when the GPU starts.','GPU 开始运行后会打开决策记录。')}</div>` : inspect();if (phase === 5 && trace?.stage2?.length > 1) updateRanking();}131 unmodified linesfollow = true;trace = null;liveEvent = undefined;phase = 0;beta = catalog.beta;renderCases();1 unmodified linelet source;try {const endpoint = './gradio_api/call/run_case';const response = await fetch(endpoint, {method:'POST', headers:await zeroGpuHeaders(), redirect:'error', body:JSON.stringify({data:[selected.name]})});if (!response.ok) throw new Error('Queue rejected the run');const {event_id: eventId} = await response.json();if (!eventId) throw new Error('Missing event id');2 unmodified linesconst onTrace = event => {try {const [payload] = JSON.parse(event.data);if (payload.name !== selected.name || !events.includes(payload.step)) throw new Error('Invalid trace');if (event.type === 'complete' && payload.step !== 'done') throw new Error('Incomplete trace');trace = payload;liveEvent = payload.step;if (follow) phase = level();9 unmodified linesfailure = error?.kind === 'quota' ? error : {kind: 'interrupted'};} finally {source?.close();busy = false;renderCases();render();3 unmodified lines4567891011121314151617181920212223249 unmodified lines343536373839402 unmodified lines43444546474849112 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line20620720820921021121221321421521612 unmodified lines229230231232233234235236237238239240241242243244245246247131 unmodified lines3793803813823833843853863871 unmodified line3893903913923933943953963973983992 unmodified lines4024034044054064074084094104114124134144154164174184194209 unmodified lines4304314324334344354364373 unmodified linesconst escape = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[char]));const steps = ['encode', 'generate', 'score', 'lock', 'filter', 'rerank', 'output'];const events = ['encode', 'beam', 'stage1', 'gate', 'filter', 'stage2', 'done'];const activities = {submit: [0, -1, 'Submitting the GPU request…', '正在提交 GPU 请求…'],wait: [0, -1, 'Waiting for ZeroGPU to start the request…', '正在等待 ZeroGPU 调度并启动…'],runtime: [0, -1, 'GPU assigned. Initializing the inference runtime…', '已分配 GPU,正在初始化推理运行环境…'],encode: [1, 0, 'Loading RSCaMa and encoding the image pair…', '正在加载 RSCaMa 并编码双时相影像…'],beam: [2, 1, 'Loading the SCST decoder and generating Beam-15…', '正在加载 SCST 解码器并生成 Beam-15…'],stage1_load: [3, 2, 'Stage 1 · Loading Elephant-1 and its ranking adapter…', '第一阶段 · 正在加载 Elephant-1 与排序适配器…'],stage1_score: [3, 2, 'Stage 1 · Scoring all 15 candidates…', '第一阶段 · 正在为全部 15 条候选评分…'],gate: [3, 3, 'Locking the change state from the highest-scoring caption…', '正在根据最高分描述锁定变化状态…'],filter: [4, 4, 'Filtering no-change and duplicate captions…', '正在过滤无变化与重复描述…'],stage2_load: [4, 5, 'Stage 2 · Loading Elephant-1 and its change adapter…', '第二阶段 · 正在加载 Elephant-1 与变化适配器…'],stage2_score: [4, 5, 'Stage 2 · Comparing the eligible change captions…', '第二阶段 · 正在比较保留的变化描述…'],output: [5, 6, 'Selecting the final caption and mapping to its original Beam ID…', '正在选定最终描述并回映至原始 Beam ID…'],};const monitorNodes = [['ZeroGPU','ZeroGPU'], ['Image encoding','影像编码'], ['Beam-15','Beam-15'], ['Stage 1','第一阶段'], ['Stage 2','第二阶段'], ['Caption','最终描述']];const labels = {project: ['Project ↗','项目主页 ↗'], headline: ['The best caption isn’t always ranked first.','排名第一的,不一定是最好的描述。'],lede: ['Critique-then-Rerank looks at both images to decide whether the scene changed, then selects the caption that best describes the change.','Critique-then-Rerank 先看双时相影像判断场景是否变化,再从现有候选中选出最符合影像的描述。'],9 unmodified linesencode: ['Encode the pair','编码双图'], generate: ['Generate Beam-15','生成 Beam-15'], score: ['Score all candidates','全候选评分'], lock: ['Route by state','按状态分流'], filter: ['Filter the pool','过滤候选池'],rerank: ['Compare + calibrate','精排与长度校准'], output: ['Map to original Beam ID','回映原始 Beam ID'],play: ['▷ Step through','▷ 逐步演示'], pause: ['Ⅱ Pause','Ⅱ 暂停演示'], live: ['Run on GPU','开始 GPU 推理'],monitor: ['Runtime monitor','实时运行监控'], elapsed: ['Elapsed','已用时'],};const inferenceHash = '#trace-title';const hubOrigin = 'https://huggingface.co';2 unmodified linesconst text = (en, zh) => lang === 'zh' ? zh : en;const label = key => text(...labels[key]);let catalog, selected, trace, phase = 3, mode = 'archive', liveEvent, busy = false, follow = true, failure = null, timer;let liveActivity, runTimes, clockTimer;let view = 'swipe', divider = 50, beta = 0.12;let activeTask = 0, alternate = false, verifySwap = false, rankedView = false;112 unmodified linesreturn mode === 'archive' ? steps.length - 1 : events.indexOf(liveEvent);}function updateClock() {const showing = mode === 'live' && Boolean(runTimes);byId('run-elapsed').hidden = !showing;if (!showing) return;const seconds = Math.floor(((runTimes.ended ?? performance.now()) - runTimes.started) / 1000);const clock = byId('run-clock');clock.dateTime = `PT${seconds}S`;clock.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;}function renderMonitor(completed, early, direct) {const current = mode === 'live' ? activities[liveActivity]?.[0] : undefined;const timing = mode === 'live' ? runTimes?.timings ?? {} : {};const duration = (key, title) => Number.isFinite(timing[key]) ? `${title} ${timing[key].toFixed(1)} s` : '';const breakdown = stage => [duration(`${stage}_load`, text('Load','加载')), duration(`${stage}_score`, text('Score','评分'))].filter(Boolean).join(' · ');const wait = runTimes?.gpuStarted - runTimes?.submitted;const details = [[Number.isFinite(wait) ? text(`Start wait ${(wait / 1000).toFixed(1)} s`, `启动等待 ${(wait / 1000).toFixed(1)} 秒`) : '', duration('runtime', text('Init','初始化'))].filter(Boolean).join(' · '),duration('encode', text('Load + encode','加载与编��')),duration('beam', text('Load + decode','加载与解码')),breakdown('stage1'), breakdown('stage2'),completed >= 6 && mode === 'live' ? `Beam ${rankLabel(trace.final)}` : '',];const done = [completed >= 0 || (Number.isFinite(runTimes?.gpuStarted) && current !== 0), completed >= 0, completed >= 1, completed >= 3, completed >= 5 && !early && !direct, completed >= 6];byId('live-nodes').innerHTML = monitorNodes.map(([en, zh], index) => {const state = mode !== 'live' ? 'pending' : index === 4 && early ? 'skipped' : index === 4 && direct ? 'direct': index === current ? (failure ? 'failed' : 'running') : done[index] ? 'done' : 'pending';const stateText = {pending: text('Pending','待运行'), running: text('In progress','进行中'), done: text('Done','完成'),skipped: text('Skipped — Early Exit','已跳过 — 提前退出'), direct: text('No Stage 2 call','未调用 Stage 2'), failed: text('Interrupted','已中断'),}[state];return `<li data-state="${state}" ${state === 'running' ? 'aria-current="step"' : ''}><div><span class="node-port" aria-hidden="true">${{done:'✓', failed:'!', skipped:'–', direct:'–'}[state] ?? `0${index + 1}`}</span><strong>${text(en, zh)}</strong></div><small>${stateText}</small>${mode === 'live' && details[index] ? `<span class="node-timing">${details[index]}</span>` : ''}</li>`;}).join('');byId('live-progress').hidden = !busy || liveEvent === 'done';updateClock();}function render() {const reached = level();const completed = timer ? phase : reached;1 unmodified lineconst focused = document.activeElement?.dataset.step;const early = trace?.changed === false && completed >= 3;const direct = trace?.changed === true && completed >= 4 && trace.eligible?.length <= 1;const activeStep = mode === 'live' && busy ? activities[liveActivity]?.[1] : undefined;renderMonitor(completed, early, direct);byId('pipeline').innerHTML = steps.map((step, index) => {const skipped = (index === 4 || index === 5) && early;const state = skipped ? 'skipped' : (direct && index === 5) ? 'direct' : index === activeStep ? 'running' : index <= completed ? 'done' : 'pending';const title = skipped ? text('Skipped — Early Exit','已跳过 — 提前退出') : state === 'direct' ? text('No Stage 2 call','未调用 Stage 2') : label(step);return `<button type="button" data-step="${index}" data-state="${state}" ${index > completed && !skipped ? 'disabled' : ''} ${phase === index && reached >= 0 ? 'aria-current="step"' : ''}><small>0${index + 1} / ${short[index]}</small><strong>${title}</strong></button>`;}).join('');12 unmodified linesbyId('live').disabled = busy || !catalog.live;const status = failure ? failureMessage(failure) : (mode === 'archive'? (catalog.live ? text('Select a step to see how the model made its decision.', '点击任意步骤,查看模型如何做出决策。') : text('Explore the case below. Live inference is temporarily unavailable.', '可以继续查看案例,实时推理暂不可用。')): (liveActivity ? text(...activities[liveActivity].slice(2)) : ({encode: text('Images encoded.','双图编码完成。'),beam: text('Beam-15 ready.','Beam-15 已生成。'),stage1: text('Stage 1 scored all candidates.','第一阶段已完成全候选评分。'),gate: trace?.changed ? text('Changed locked.','已锁定有变化。') : text('Unchanged locked. Stage 2 skipped.','已锁定无变化,跳过第二阶段。'),filter: text('Change pool ready.','变化候选池已就绪。'),stage2: text('Stage 2 scored the pool.','第二阶段已完成评分。'),done: text('Inference complete. Inspect any step.','推理完成,可回看任意步骤。'),}[liveEvent] ?? '')));if (byId('status').textContent !== status) byId('status').textContent = status;byId('inspector').innerHTML = reached < 0 ? `<div class="empty">${failure? text('No live result. Choose Step through to explore this pair without using GPU quota.', '���次没有实时结果。点击「逐步演示」可查看这组影像的推理流程,不消耗 GPU 配额。'): text('The trace opens as soon as the first step finishes.','第一步完成后即可查看决策记录。')}</div>` : inspect();if (phase === 5 && trace?.stage2?.length > 1) updateRanking();}131 unmodified linesfollow = true;trace = null;liveEvent = undefined;liveActivity = 'submit';runTimes = {started: performance.now()};clockTimer = setInterval(updateClock, 1000);phase = 0;beta = catalog.beta;renderCases();1 unmodified linelet source;try {const endpoint = './gradio_api/call/run_case';const headers = await zeroGpuHeaders();liveActivity = 'wait';runTimes.submitted = performance.now();render();const response = await fetch(endpoint, {method:'POST', headers, redirect:'error', body:JSON.stringify({data:[selected.name]})});if (!response.ok) throw new Error('Queue rejected the run');const {event_id: eventId} = await response.json();if (!eventId) throw new Error('Missing event id');2 unmodified linesconst onTrace = event => {try {const [payload] = JSON.parse(event.data);if (payload?.name !== selected.name) throw new Error('Invalid trace');const activity = payload.activity;if (activity === undefined ? !events.includes(payload.step): payload.step !== undefined || !Object.hasOwn(activities, activity) || activity === 'submit' || activity === 'wait') throw new Error('Invalid trace');if (event.type === 'complete' && payload.step !== 'done') throw new Error('Incomplete trace');if (activity === 'runtime') runTimes.gpuStarted ??= performance.now();runTimes.timings = payload.timings;if (activity) {liveActivity = activity;render();return;}liveActivity = undefined;trace = payload;liveEvent = payload.step;if (follow) phase = level();9 unmodified linesfailure = error?.kind === 'quota' ? error : {kind: 'interrupted'};} finally {source?.close();runTimes.ended = performance.now();clearInterval(clockTimer);busy = false;renderCases();render();
app.py+1-2
inference.py+43-16
workbench/index.html+7-3
workbench/lab.css+30-1
workbench/lab.js+87-11