Spaces:
Running on Zero
Running on Zero
Replace the demo form with the decision workbench
Browse filesFiles changed (7)
- README.md+2-2
- app.py+44-153
- inference.py+27-13
- public/cases.json+1-1
- workbench/index.htmlAdded+49
- workbench/lab.cssAdded+181
- workbench/lab.jsAdded+278
11 unmodified lines121314151617181911 unmodified lines# Critique-then-Rerank · Live InferenceSelect one of four LEVIR-CC image pairs and run Beam-15 generation and two-stage state-locked reranking. The app does not accept uploads or serve archived predictions as live output. [Project page](https://thirteen7.github.io/Critique-then-Rerank/)Each case includes a bilingual task guide, side-by-side images, and a four-second T₁ → T₂ clip made from the original two frames. The live decision trace streams Beam-15 and the two stage decisions as they become available. The β control reuses live Stage 2 scores without another GPU call and does not replace the reported paper setting.For deployment, select ZeroGPU hardware in Space Settings. Set `CTR_MODEL_READ_TOKEN` as a **Space secret** using a fine-grained token with read access only to `thirteen7/Critique-then-Rerank`. Do not use an account-wide token. The pinned public RSCaMa and Elephant-1 checkpoints are downloaded directly from the Hub; they are not bundled. The first startup after configuration downloads the checkpoints before accepting GPU work.11 unmodified lines121314151617181911 unmodified lines# Critique-then-Rerank · Live InferenceThe Decision Lab walks through four LEVIR-CC pairs: joint visual encoding, Beam-15 generation, Elephant-1 state locking, and same-state reranking. [Project page](https://thirteen7.github.io/Critique-then-Rerank/)Inspect paper records immediately or run the same image pair on ZeroGPU and follow the streamed stages. Swipe, compare side by side, or play the original frames as a four-second clip. The β slider reranks the active Stage 2 pool without another GPU call; the final-caption view keeps the paper setting. The app accepts only the four listed pairs.For deployment, select ZeroGPU hardware in Space Settings. Set `CTR_MODEL_READ_TOKEN` as a **Space secret** using a fine-grained token with read access only to `thirteen7/Critique-then-Rerank`. Do not use an account-wide token. The pinned public RSCaMa and Elephant-1 checkpoints are downloaded directly from the Hub; they are not bundled. The first startup after configuration downloads the checkpoints before accepting GPU work.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412511 unmodified lines137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""Fixed-case Gradio interface for the LEVIR-CC live demo."""from html import escapeimport loggingimport mathimport osimport spacesimport gradio as grfrom PIL import Imagefrom inference import prepare, trace_casefrom pipeline import ROOT, decision, next_stage, profile, readLOGGER = logging.getLogger(__name__)PUBLIC = ROOT / 'public'CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}FIRST = next(iter(CASES))CONFIG = profile('levir')CHECKPOINTS = NoneHERO = '''<header class="observatory"><div class="eyebrow">REMOTE SENSING / LEVIR-CC <span>ZERO GPU</span></div><h1>Critique-then-Rerank</h1><p>One image pair, 15 captions, two decisions. See how the model first decides whether anything changed,then refines the caption without changing that decision.</p><p>选择一组双时相影像,观察模型如何锁定变化状态,再在同状态候选中精排。</p><a href="https://thirteen7.github.io/Critique-then-Rerank/">Project page / 项目主页 ↗</a></header>'''CSS = '''.gradio-container { max-width: 1100px !important; }.observatory { padding: clamp(1.25rem, 5vw, 3.5rem); border-radius: 1.25rem; color: #f0f8f4;background: radial-gradient(ellipse at 100% 0%, #245b51, #122520 65%); }.observatory h1 { color: inherit; font-size: clamp(2rem, 6vw, 4rem); line-height: 1.04; margin: 1rem 0; }.observatory p { color: #dbebe5; max-width: 58ch; margin: .65rem 0; }.observatory a { color: #b6f6dd; text-decoration: underline; }.eyebrow { font-family: monospace; letter-spacing: .14em; color: #b6f6dd; }.eyebrow span { display: inline-block; margin-inline-start: .75rem; color: #fff7ed; }#run-live { min-height: 3rem; }.decision-card { border: 1px solid var(--border-color-primary); border-radius: .75rem; padding: 1rem; }.decision-card h3 { margin: 0 0 .5rem; }.decision-card p { overflow-wrap: anywhere; }.decision-card.final { border-width: 2px; border-color: #0f766e; }.decision-card.routed { border-color: #d95d39; }.case-brief { padding: 1rem 1.25rem; border-inline-start: .25rem solid #0f766e;border-radius: .5rem; background: var(--background-fill-secondary); }.case-brief p { margin-block: .5rem; }.trace-status { font-family: monospace; color: var(--body-text-color-subdued); }.trace-status progress { display: block; inline-size: 100%; margin-top: .5rem; accent-color: #0f766e; }'''def case_view(case_name):record = CASES[case_name]images = [load_preview(PUBLIC / image) for image in record['media']]brief = (f'<section class="case-brief"><h2>{escape(record["title_en"])}</h2>'f'<p lang="zh-CN"><strong>{escape(record["title_zh"])}</strong></p>'f'<p>{escape(record["summary_en"])}</p><p lang="zh-CN">{escape(record["summary_zh"])}</p>''<small>Paper case guide / 论文案例导读</small></section>')return brief, *images, PUBLIC / record['clip']def load_preview(path):with Image.open(path) as image:return image.convert('RGB')def progress_card(case_name, step):labels = {'beam': (0, 'Reading T₁/T₂ and generating 15 candidates / 编码双时相影像并生成候选'),'stage1': (1, 'Stage 1 is selecting the change state / 第一阶段正在判断变化状态'),'stage2': (2, 'Stage 2 is scoring changed captions / 第二阶段正在比较变化候选'),'done': (3, 'Live result ready / 实时推理完成'),}count, label = labels[step]return (f'<div class="trace-status"><div role="status">{escape(case_name)} · {label}</div>'f'<progress aria-label="Inference stages / 推理阶段" value="{count}" max="3"></progress></div>')def cards(step, result):captions = result.get('captions', [])anchor = Nonechanged = Noneif result.get('stage1'):anchor = max(result['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage('levir', captions, anchor, CONFIG['templates'])state = 'Changed / 有变化' if changed else 'Unchanged / 无变化'if changed is False:route = 'Bypassed / 跳过精排'elif step != 'done':route = 'Waiting for decision / 等待决策'elif len(result['stage2']) > 1:route = f"Reranked {len(result['stage2'])} same-state candidates / 同状态精排 · β = {result['beta']:.2f}"elif result['stage2']:route = 'One eligible candidate / 仅一条合格候选'else:route = 'No eligible candidates; retained Stage 1 / 无合格候选,保留第一阶段结果'top = escape(captions[0]) if captions else 'Pending / 等待生成'gate = f'{state}</p><p lang="en">{escape(captions[anchor])}' if anchor is not None else 'Pending / 等待判断'final = escape(captions[result['final']]) if step == 'done' else '—'candidates = [[index + 1, caption] for index, caption in enumerate(captions)]return (progress_card(result['name'], step),f'<div class="decision-card"><h3>01 · Beam-15 Top-1</h3><p>{top}</p></div>',f'<div class="decision-card"><h3>02 · State Gate</h3><p>{gate}</p></div>',f'<div class="decision-card final {"routed" if changed else ""}">'f'<h3>03 · Final Caption</h3><p>{route}</p><p lang="en">{final}</p></div>', candidates)def calibration(beta, result):if not result or len(result.get('stage2', [])) < 2:return '**β calibration / 长度校准:** Requires at least two Stage 2 candidates. / 需有至少两条第二阶段候选。', []beta = float(beta)captions = result['captions']winner = decision('levir', result, beta, CONFIG['templates'])ranks = sorted(((index, math.log(max(prob, 1e-30)) - beta * len(captions[index].split()))for index, prob in result['stage2']), key=lambda pair: -pair[1])return (f"**{result['name']} · β = {beta:.2f}** — Beam #{winner + 1} wins / 当前首选。 "f"Changes only ranking; the reported live result uses β = {CONFIG['beta']:.2f}. / 仅改变排序,上方实时结果仍使用论文 β。",[[index + 1, captions[index], len(captions[index].split()), round(score, 5)] for index, score in ranks])def load_checkpoints():11 unmodified lines@spaces.GPU(duration=120)def run_live(case_name):if case_name not in CASES:raise gr.Error('Select a listed image pair. / 请选择列出的影像组。')if CHECKPOINTS is None:raise gr.Error('Model weights are not configured. / 尚未配置模型权重。')for step, result in trace_case(CASES[case_name], CHECKPOINTS):saved = result if step == 'done' else Nonenote, ranks = calibration(CONFIG['beta'], saved)yield (*cards(step, result), saved, gr.update(value=CONFIG['beta'], interactive=len(ranks) > 1), note, ranks)def build():with gr.Blocks(title='Critique-then-Rerank · Live', analytics_enabled=False) as app:gr.HTML(HERO)if CHECKPOINTS is None:gr.Markdown('**Live inference unavailable / 实时推理暂不可用。** ''This Space cannot access the model weights. / 当前 Space 未能读取模型权重。')case = gr.Radio([(f"{record['en']} / {record['zh']} · {name}", name)for name, record in CASES.items()], value=FIRST, label='Test pair / 选择样例')intro, before_img, after_img, clip_path = case_view(FIRST)brief = gr.HTML(intro)with gr.Tabs():with gr.Tab('T₁ / T₂ · Side by side / 并排'):with gr.Row():before = gr.Image(before_img, label='T₁ · Before / 变化前', interactive=False, buttons=[], height=300)after = gr.Image(after_img, label='T₂ · After / 变化后', interactive=False, buttons=[], height=300)with gr.Tab('T₁ → T₂ · Playback / 时序播放'):gr.Markdown('Each frame holds for two seconds. Playback shows only the two original observations. / ''每个时相停留两秒,只播放两张原始影像,不插帧。')clip = gr.Video(clip_path, label='T₁ → T₂', interactive=False, autoplay=False, loop=False,include_audio=False, buttons=[], height=360)run = gr.Button('Run live inference / 运行实时推理', variant='primary', elem_id='run-live',interactive=CHECKPOINTS is not None)gr.Markdown('### Live decision trace / 实时决策过程')progress = gr.HTML()with gr.Row():top, gate, final = gr.HTML(), gr.HTML(), gr.HTML()with gr.Accordion('Beam-15 candidates / 15 条候选', open=False):candidates = gr.Dataframe(headers=['Beam rank', 'Caption'], datatype=['number', 'str'], interactive=False)with gr.Accordion('Length calibration / β 长度校准', open=True):beta = gr.Slider(0.0, 0.20, value=CONFIG['beta'], step=0.02, label='β', interactive=False)note = gr.Markdown('Run a changed case to explore calibration. / 运行一组有变化的案例以查看排序。')ranks = gr.Dataframe(headers=['Beam rank', 'Caption', 'Words', 'Score'],datatype=['number', 'str', 'number', 'number'], interactive=False)scores = gr.State()case.change(case_view, case, [brief, before, after, clip], queue=False, api_visibility='private')beta.input(calibration, [beta, scores], [note, ranks], queue=False, api_visibility='private')run.click(run_live, case, [progress, top, gate, final, candidates, scores, beta, note, ranks], concurrency_limit=1,api_name='run_case', api_visibility='undocumented')return app.queue(max_size=8)if __name__ == '__main__':CHECKPOINTS = load_checkpoints()build().launch(css=CSS, theme=gr.themes.Soft(primary_hue='teal', neutral_hue='slate'),show_error=False)1234567891011121314151617181920212223242511 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Serve the decision workbench and its queued ZeroGPU trace."""import loggingimport osimport gradio as grimport spacesimport uvicornfrom fastapi import FastAPIfrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom inference import prepare, trace_casefrom judge.questions import CHANGED, GENERALfrom pipeline import ROOT, decision, next_stage, profile, readLOGGER = logging.getLogger(__name__)PUBLIC = ROOT / 'public'FRONTEND = ROOT / 'workbench'CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}CONFIG = profile('levir')CHECKPOINTS = Nonedef load_checkpoints():11 unmodified lines@spaces.GPU(duration=120)def run_live(case_name):if case_name not in CASES:raise 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():records = []for name, record in CASES.items():row = record['replay']captions = row['captions']anchor = max(row['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage('levir', captions, anchor, CONFIG['templates'])trace = {**row, 'name': name, 'anchor': anchor, 'changed': changed,'eligible': [index for index, _ in row['stage2']],'final': decision('levir', row, CONFIG['beta'], CONFIG['templates'])}records.append({**record, 'replay': trace})return {'cases': records, 'templates': CONFIG['templates'], 'beta': CONFIG['beta'],'tasks': [GENERAL, CHANGED], 'live': CHECKPOINTS is not None}def build():app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)app.mount('/workbench', StaticFiles(directory=FRONTEND), name='workbench')app.mount('/media/images', StaticFiles(directory=PUBLIC / 'images'), name='images')app.mount('/media/clips', StaticFiles(directory=PUBLIC / 'clips'), name='clips')@app.get('/')def index():return FileResponse(FRONTEND / 'index.html')app.get('/catalog')(catalog)with gr.Blocks(analytics_enabled=False) as api:case = gr.Textbox(visible=False)result = gr.JSON(visible=False)submit = gr.Button(visible=False)submit.click(run_live, case, result, api_name='run_case', api_visibility='undocumented', concurrency_limit=1)return gr.mount_gradio_app(app, api.queue(max_size=8), path='/engine', show_error=False)if __name__ == '__main__':CHECKPOINTS = load_checkpoints()uvicorn.run(build(), host='0.0.0.0', port=int(os.environ.get('GRADIO_SERVER_PORT', '7860')))
5 unmodified lines6789101157 unmodified lines69707172737475767778798081828384858687888990911 unmodified line939495969798991005 unmodified linesfrom importlib.machinery import SourceFileLoaderfrom pathlib import Pathimport sysfrom huggingface_hub import hf_hub_download, snapshot_download57 unmodified linesif not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():raise RuntimeError('A BF16-capable CUDA GPU is required.')install_elephant_model()initialize()dataset = 'levir'media_root = ROOT / 'public'config = profile(dataset)name = record['name']yield 'beam', {'name': name}features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')captions = beam(dataset, features, checkpoints.generator, 'cuda')[0]row = {'name': name, 'captions': captions}rows = {name: row}for stage in (1, 2):questions = list(stage1_questions(dataset, [record], rows) if stage == 1 elsestage2_questions(dataset, [record], rows, config['templates']))if not questions:continueyield f'stage{stage}', {**row}runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')try:row[f'stage{stage}'] = score(runtime, bundle, questions)[name]1 unmodified linedel bundlegc.collect()torch.cuda.empty_cache()anchor = max(row['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage(dataset, captions, anchor, config['templates'])yield 'done', {**row, 'anchor': anchor, 'changed': changed, 'beta': config['beta'],'final': decision(dataset, row, config['beta'], config['templates'])}5 unmodified lines678910111257 unmodified lines7071727374757677787980818283848586878889909192939495961 unmodified line98991001011021031041051061071081091101111121131145 unmodified linesfrom importlib.machinery import SourceFileLoaderfrom pathlib import Pathimport sysfrom time import perf_counterfrom huggingface_hub import hf_hub_download, snapshot_download57 unmodified linesif not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():raise RuntimeError('A BF16-capable CUDA GPU is required.')install_elephant_model()dataset = 'levir'media_root = ROOT / 'public'config = profile(dataset)name = record['name']row = {'name': name, 'timings': {}}yield 'encode', rowstarted = 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 'beam', rowstarted = perf_counter()row['captions'] = beam(dataset, features, checkpoints.generator, 'cuda')[0]row['timings']['beam'] = perf_counter() - startedrows = {name: row}first = list(stage1_questions(dataset, [record], rows))yield 'stage1', rowdef 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]1 unmodified linedel 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]_, changed = next_stage(dataset, row['captions'], anchor, config['templates'])row.update(anchor=anchor, changed=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 'gate', {key: value for key, value in row.items() if key != 'stage2'}if second:yield 'stage2', {key: value for key, value in row.items() if key != 'stage2'}score_stage(2, second)yield 'done', {**row, 'final': decision(dataset, row, config['beta'], config['templates'])}
1[{"name": "test_000033.png", "en": "False Positive Blocked", "zh": "误报拦截", "media": ["images/test_000033_A.png", "images/test_000033_B.png"], "title_en": "Stage 1 Blocks Hallucinated Construction", "title_zh": "第一阶段拦截无变化幻觉", "summary_en": "Beam-15 top-1 hallucinates a new building at the bottom of the scene. Stage 1 locks the state to Unchanged and skips Stage 2 by construction.", "summary_zh": "Beam-15 首句在底部幻觉出新建筑;第一阶段将状态锁定为“无变化”,结构上直接跳过第二阶段精排。", "clip": "clips/test_000033.mp4"}, {"name": "test_001549.png", "en": "Same-State Reranking", "zh": "同状态精排", "media": ["images/test_001549_A.png", "images/test_001549_B.png"], "title_en": "Stage 2 Refines Singular to Plural Houses", "title_zh": "第二阶段修正对象与复数表达", "summary_en": "Both Beam-15 top-1 and Stage 1 select a changed caption (\"a building\"). Stage 2 compares only changed candidates and promotes \"some houses\", aligning with the scene.", "summary_zh": "Beam-15 首句与第一阶段都选中变化句(a building);第二阶段仅在变化候选内重排,选中更贴合画面的 some houses。", "clip": "clips/test_001549.mp4"}, {"name": "test_001324.png", "en": "Length Calibration (β)", "zh": "长度惩罚权衡", "media": ["images/test_001324_A.png", "images/test_001324_B.png"], "title_en": "Drag β to Observe Concise vs. Verbose Reranking", "title_zh": "拖动 β 观察简洁与冗长候选的切换", "summary_en": "At β = 0.00, Stage 2 prefers the longer phrase (\"at the bottom side of the scene\"). With Val-selected β = 0.12, length calibration selects the concise top candidate without rewriting text.", "summary_zh": "当 β = 0.00 时第二阶段偏向较长表达(at the bottom side of the scene);启用验证集选定的 β = 0.12 后,无需重写文本即可重排回更简洁的候选句。", "clip": "clips/test_001324.mp4"}, {"name": "test_001095.png", "en": "Boundary / Failure Case", "zh": "边界与失败案例", "media": ["images/test_001095_A.png", "images/test_001095_B.png"], "title_en": "Honest Boundary: Missed Change Cannot Be Flipped", "title_zh": "算法边界:初筛漏报锁定后不可翻转", "summary_en": "A small corner house appears on the right and is present in Beam-15 top-1, but Stage 1 predicts Unchanged. Because state-locking is structural, Stage 2 cannot override a Stage 1 false negative.", "summary_zh": "画面右侧出现小范围房屋变化且位于 Beam-15 首句中,但第一阶段误判为无变化;由于状态锁定是结构保证,第二阶段无法挽回初筛漏报。", "clip": "clips/test_001095.mp4"}]1[{"name": "test_000033.png", "en": "False Positive Blocked", "zh": "误报拦截", "media": ["images/test_000033_A.png", "images/test_000033_B.png"], "title_en": "Stage 1 Blocks Hallucinated Construction", "title_zh": "第一阶段拦截无变化幻觉", "summary_en": "Beam-15 top-1 hallucinates a new building at the bottom of the scene. Stage 1 locks the state to Unchanged and skips Stage 2 by construction.", "summary_zh": "Beam-15 首句在底部幻觉出新建筑;第一阶段将状态锁定为“无变化”,结构上直接跳过第二阶段精排。", "clip": "clips/test_000033.mp4", "replay": {"captions": ["a building appears at the bottom of the scene", "a building is built at the bottom of the scene", "the scene is the same as before", "a small building is built at the bottom of the scene", "a small building appears at the bottom of the scene", "the scene is removed and a building is built at the bottom", "some buildings are built at the bottom of the scene", "some buildings appear at the bottom of the scene", "a villa is built at the bottom of the scene", "a house is built at the bottom of the scene", "the scene is removed and a building appears at the bottom", "two buildings appear at the bottom of the scene", "a building appears at the bottom right corner of the scene", "a building is built at the bottom right corner of the scene", "two buildings are built at the bottom of the scene"], "stage1": [[0, 0.03613479062914848], [1, 0.029035119339823723], [2, 0.7034565210342407], [3, 0.021242547780275345], [4, 0.02407095767557621], [5, 0.018169714137911797], [6, 0.020588982850313187], [7, 0.018169714137911797], [8, 0.024835053831338882], [9, 0.018169714137911797], [10, 0.014599774032831192], [11, 0.017610691487789154], [12, 0.015063220635056496], [13, 0.017610691487789154], [14, 0.021242547780275345]], "stage2": []}}, {"name": "test_001549.png", "en": "Same-State Reranking", "zh": "同状态精排", "media": ["images/test_001549_A.png", "images/test_001549_B.png"], "title_en": "Stage 2 Refines Singular to Plural Houses", "title_zh": "第二阶段修正对象与复数表达", "summary_en": "Both Beam-15 top-1 and Stage 1 select a changed caption (\"a building\"). Stage 2 compares only changed candidates and promotes \"some houses\", aligning with the scene.", "summary_zh": "Beam-15 首句与第一阶段都选中变化句(a building);第二阶段仅在变化候选内重排,选中更贴合画面的 some houses。", "clip": "clips/test_001549.mp4", "replay": {"captions": ["a building appears at the bottom right corner of the scene", "some houses appear at the bottom right corner of the scene", "a building appears at the bottom of the scene", "a house appears at the bottom right corner of the scene", "some houses appear at the bottom of the scene", "some buildings appear at the bottom right corner of the scene", "a house appears at the bottom of the scene", "some buildings appear at the bottom of the scene", "a villa appears at the bottom right corner of the scene", "a few houses appear at the bottom of the scene", "a few houses appear at the bottom right corner of the scene", "some houses are built at the bottom right corner of the scene", "a small building appears at the bottom right corner of the scene", "two houses appear at the bottom right corner of the scene", "a corner of houses appears at the bottom of the scene"], "stage1": [[0, 0.09699154645204544], [1, 0.09400742501020432], [2, 0.06069576367735863], [3, 0.08559473603963852], [4, 0.0646103024482727], [5, 0.08559473603963852], [6, 0.05031855031847954], [7, 0.05031855031847954], [8, 0.06666125357151031], [9, 0.05882834643125534], [10, 0.08040881901979446], [11, 0.051915835589170456], [12, 0.04303973913192749], [13, 0.06069576367735863], [14, 0.05031855031847954]], "stage2": [[11, 0.0644257590174675], [0, 0.09978457540273666], [12, 0.053410835564136505], [9, 0.03139860928058624], [2, 0.03557928651571274], [4, 0.04427913948893547], [3, 0.09085488319396973], [7, 0.04427913948893547], [1, 0.12418390810489655], [8, 0.060522403568029404], [13, 0.09978457540273666], [6, 0.023700913414359093], [10, 0.07771230489015579], [5, 0.1166599839925766], [14, 0.03342364728450775]]}}, {"name": "test_001324.png", "en": "Length Calibration (β)", "zh": "长度惩罚权衡", "media": ["images/test_001324_A.png", "images/test_001324_B.png"], "title_en": "Drag β to Observe Concise vs. Verbose Reranking", "title_zh": "拖动 β 观察简洁与冗长候选的切换", "summary_en": "At β = 0.00, Stage 2 prefers the longer phrase (\"at the bottom side of the scene\"). With Val-selected β = 0.12, length calibration selects the concise top candidate without rewriting text.", "summary_zh": "当 β = 0.00 时第二阶段偏向较长表达(at the bottom side of the scene);启用验证集选定的 β = 0.12 后,无需重写文本即可重排回更简洁的候选句。", "clip": "clips/test_001324.mp4", "replay": {"captions": ["a road is built at the bottom", "a road is built at the bottom side of the scene", "a road is built on the bottom side of the scene", "a road appears at the bottom", "a road is built on the bareland", "a road is built on the bottom", "a road is built at the bottom of the scene", "a road appears at the bottom of the scene", "a road appears at the bottom side of the scene", "a road is built at the bottom left corner of the scene", "a road and a road is built on the bottom", "a road appears at the bottom left corner of the scene", "a road are built at the bottom", "a road and a road is built on the bareland", "a road appears on the bareland"], "stage1": [[0, 0.0876748338341713], [1, 0.07737276703119278], [2, 0.07499226182699203], [3, 0.0876748338341713], [4, 0.04995561018586159], [5, 0.062170762568712234], [6, 0.0876748338341713], [7, 0.07737276703119278], [8, 0.08236288279294968], [9, 0.06828122586011887], [10, 0.04141465947031975], [11, 0.06025797501206398], [12, 0.045485105365514755], [13, 0.03890547156333923], [14, 0.05840403214097023]], "stage2": [[0, 0.09296959638595581], [14, 0.07707450538873672], [6, 0.09010922163724899], [4, 0.051342688500881195], [2, 0.07707450538873672], [11, 0.06801801919937134], [13, 0.022082215175032616], [8, 0.08204538375139236], [5, 0.05817888677120209], [1, 0.10210712999105453], [7, 0.08464978635311127], [10, 0.02502242848277092], [3, 0.07707450538873672], [12, 0.02835412509739399], [9, 0.0638970136642456]]}}, {"name": "test_001095.png", "en": "Boundary / Failure Case", "zh": "边界与失败案例", "media": ["images/test_001095_A.png", "images/test_001095_B.png"], "title_en": "Honest Boundary: Missed Change Cannot Be Flipped", "title_zh": "算法边界:初筛漏报锁定后不可翻转", "summary_en": "A small corner house appears on the right and is present in Beam-15 top-1, but Stage 1 predicts Unchanged. Because state-locking is structural, Stage 2 cannot override a Stage 1 false negative.", "summary_zh": "画面右侧出现小范围房屋变化且位于 Beam-15 首句中,但第一阶段误判为无变化;由于状态锁定是结构保证,第二阶段无法挽回初筛漏报。", "clip": "clips/test_001095.mp4", "replay": {"captions": ["a building is built on the right", "a building is built on the bareland", "the scene is the same as before", "a scene is built on the right", "some buildings are built on the right", "some buildings are built on the bareland", "a scene is built on the bareland", "two buildings are built on the right", "a large building is built on the right", "two buildings are built on the bareland", "a building is built on the right side of the scene", "a small building is built on the right", "a building is built on the right side", "a few buildings are built on the right", "a scene is built on the right side of the scene"], "stage1": [[0, 0.05586867779493332], [1, 0.024791575968265533], [2, 0.5642536878585815], [3, 0.03839794546365738], [4, 0.02898428961634636], [5, 0.022572988644242287], [6, 0.026390496641397476], [7, 0.025578545406460762], [8, 0.0360715277493], [9, 0.02055293880403042], [10, 0.031833015382289886], [11, 0.025578545406460762], [12, 0.0360715277493], [13, 0.028092535212635994], [14, 0.034961726516485214]], "stage2": []}}]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#101917"> <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"> <script type="module" src="./workbench/lab.js"></script></head><body> <header class="topbar"> <div class="wordmark"><svg viewBox="0 0 32 32" width="34" height="34" fill="none" aria-hidden="true"><path d="M3 13 16 6l13 7-13 7L3 13Z M3 19l13 7 13-7" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M16 1v8m0 14v8" stroke="currentColor" opacity=".5"/></svg><span>Critique-then-Rerank<small>DECISION LAB / RS-CC</small></span></div> <div class="toplinks"><a href="https://thirteen7.github.io/Critique-then-Rerank/" data-t="project">Project ↗</a><button id="language" type="button" aria-label="切换到中文">中文</button></div> </header> <main> <section class="hero" aria-labelledby="headline"> <div><p class="eyebrow"><span class="signal"></span> LEVIR-CC <span class="dim">/</span> ELEPHANT-1</p> <h1 id="headline" data-t="headline">From two images<br>to one decision.</h1> <p class="lede" data-t="lede">Follow the same location through time. See how 15 captions are generated, which option locks the change state, and how the final caption is selected.</p></div> <ol class="hero-index" aria-label="Pipeline stages"><li><b>01</b><span data-t="encode">Encode the pair</span></li><li><b>02</b><span data-t="generate">Generate captions</span></li><li><b>03</b><span data-t="lock">Lock the state</span></li><li><b>04</b><span data-t="rerank">Rerank within the state</span></li></ol> </section> <section class="cases" aria-labelledby="case-heading"> <div class="sectionbar"><h2 id="case-heading" data-t="choose">Choose a test pair</h2><span class="micro">04 PAIRS / LEVIR-CC</span></div> <div class="case-grid" id="case-grid"></div> </section> <div class="lab"> <aside class="observation panel" aria-labelledby="observation-title"> <div class="sectionbar"><h2 id="observation-title" data-t="observations">Bi-temporal observations</h2><code id="case-id"></code></div> <div id="viewer"></div> <div id="case-context" class="case-context"></div> </aside> <section class="decision panel" aria-labelledby="trace-title"> <div class="sectionbar"><h2 id="trace-title" data-t="trace">Decision trace</h2><span class="micro">T₁ / T₂ → CAPTION</span></div> <div class="toolbar"> <div class="transport"><button type="button" id="replay" data-t="play">▷ Replay trace</button><button type="button" id="live" data-t="live">Run on GPU ↗</button></div> <span id="source" class="chip"></span> </div> <p class="run-status" id="status" role="status"></p> <nav class="pipeline" id="pipeline" aria-label="Decision trace steps"></nav> <div id="inspector" class="inspector"></div> </section> </div> <noscript>This interactive trace requires JavaScript. / 交互演示需要 JavaScript。</noscript> </main> <footer><span>CRITIQUE-THEN-RERANK</span><span>LEVIR-CC · DECISION LAB</span></footer></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181:root { color-scheme: dark; --air: #101917; --panel: #172321; --deep: #101d19; --line: #36504a; --ink: #f1f6ec; --dim: #a5bcb4; --green: #a9f4ce; --warm: #ffba90; --mono: ui-monospace, 'JetBrains Mono', Consolas, monospace; font-family: Inter, system-ui, 'PingFang SC', 'Microsoft YaHei', sans-serif; background: var(--air); color: var(--ink);}*, *::before, *::after { box-sizing: border-box; }body { margin: 0; }button, a, input { font: inherit; }button { color: inherit; cursor: pointer; }button:disabled { cursor: default; opacity: .55; }:focus-visible { outline: 2px solid var(--warm); outline-offset: 3px; }a { color: var(--green); }p, h1, h2, h3, h4 { margin: 0; }img, video { display: block; width: 100%; }img { height: auto; }video { background: #0a110f; border-radius: 8px; aspect-ratio: 1; }button, details { border: 1px solid var(--line); border-radius: 7px; background: var(--deep); }button:not(:disabled):hover, button[aria-pressed='true'] { border-color: var(--green); }.topbar, main, footer { width: min(1370px, calc(100% - clamp(28px, 7vw, 110px))); margin-inline: auto; }.topbar { min-height: 76px; display: flex; justify-content: space-between; align-items: center; gap: 16px; border-bottom: 1px solid var(--line); }.wordmark, .toplinks { display: flex; align-items: center; gap: 12px; }.wordmark { font-weight: 680; letter-spacing: -.025em; line-height: 1.2; }.wordmark svg { color: var(--green); flex: none; }.wordmark small, .micro, .eyebrow, code, .pool-head, .inspect-head time, .route-root span, .comparison small, .signal, footer { font: 500 .72rem/1.35 var(--mono); letter-spacing: .08em; }.wordmark small { display: block; margin-top: 4px; color: var(--dim); }.toplinks a { text-decoration: none; font-size: .83rem; }.toplinks button { padding: .45rem .7rem; min-height: 38px; }.hero { position: relative; isolation: isolate; display: grid; grid-template-columns: minmax(0, 1fr) minmax(200px, .36fr); align-items: center; gap: clamp(24px, 6vw, 84px); margin-block: 22px 30px; padding: clamp(22px, 4vw, 58px); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; background: radial-gradient(ellipse at 85% 22%, #254139, var(--deep) 75%); }.hero::before { content: ''; position: absolute; inset: 0; z-index: -1; opacity: .55; background: linear-gradient(#91bfaf25 1px, transparent 1px), linear-gradient(90deg, #91bfaf25 1px, transparent 1px); background-size: 36px 36px; mask-image: linear-gradient(90deg, transparent, #000); }.eyebrow, .micro { color: var(--green); }.signal { display: inline-block; width: 7px; height: 7px; margin-right: 6px; border-radius: 50%; background: var(--green); box-shadow: 0 0 14px #a9f4ce70; }.dim { color: var(--dim); }h1 { max-width: 16ch; margin: .3em 0 .2em; font-size: clamp(2.35rem, 5.6vw, 5.4rem); line-height: 1.01; letter-spacing: -.065em; }[lang='zh-CN'] h1 { letter-spacing: -.032em; }.lede { max-width: 64ch; line-height: 1.62; color: var(--dim); }.hero-index { margin: 0; padding: 0; list-style: none; border-block: 1px solid var(--line); background: #142520c9; }.hero-index li { display: flex; align-items: center; gap: 13px; min-height: 42px; padding: 8px 12px; font-size: .87rem; }.hero-index li + li { border-top: 1px solid var(--line); }.hero-index b { font: 500 .72rem var(--mono); color: var(--green); }.sectionbar { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 6px 12px; margin-bottom: 12px; }.sectionbar h2 { font-size: 1.05rem; letter-spacing: -.02em; }.sectionbar code { color: var(--dim); }.case-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }.case { position: relative; display: grid; grid-template-columns: 57px minmax(0,1fr); align-items: center; gap: 10px; min-height: 80px; text-align: start; padding: 9px; background: var(--panel); }.case img { border-radius: 4px; }.case-number { position: absolute; inset: 13px auto auto 13px; background: #101917dc; color: var(--green); border-radius: 3px; padding: 2px 3px; font: .61rem var(--mono); }.case[aria-pressed='true'] { background: #223b32; box-shadow: inset 0 -2px var(--green); }.case strong { display: block; font-size: .88rem; line-height: 1.25; }.case small { display: block; font: .67rem var(--mono); color: var(--dim); margin-top: 5px; }.lab { display: grid; grid-template-columns: minmax(0, .82fr) minmax(0, 1.42fr); align-items: start; gap: 16px; margin-block: 18px 32px; }.panel { border: 1px solid var(--line); border-radius: 12px; background: var(--panel); padding: clamp(13px, 1.8vw, 24px); min-width: 0; }.view-mode, .toolbar, .transport { display: flex; flex-wrap: wrap; gap: 7px; }.view-mode { margin-bottom: 10px; }.view-mode button, .transport button { min-height: 40px; padding: 6px 10px; font-size: .81rem; }.view-mode button[aria-pressed='true'] { color: var(--green); background: #263b33; }.swipe, .frame { position: relative; overflow: hidden; border-radius: 8px; }.swipe:has(input:focus-visible) { outline: 2px solid var(--warm); outline-offset: 3px; }.swipe input[type='range'] { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; opacity: 0; cursor: ew-resize; }.swipe:focus-within .divider b { outline: 2px solid var(--air); }.swipe img, .frame img { aspect-ratio: 1; object-fit: contain; }.after { position: absolute; inset: 0; clip-path: inset(0 0 0 var(--split)); }.divider { position: absolute; inset: 0 auto 0 var(--split); width: 2px; background: var(--green); pointer-events: none; }.divider b { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); border-radius: 999px; color: var(--air); background: var(--green); padding: 3px 6px; white-space: nowrap; }.t1, .t2, .frame span { position: absolute; top: 10px; background: #101917ed; border: 1px solid #8bb4a4; color: var(--ink); border-radius: 5px; padding: 3px 7px; font: .82rem var(--mono); }.t1, .frame span { left: 10px; }.t2 { right: 10px; }.pair { display: grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap: 6px; }.range-label { display: flex; align-items: center; justify-content: space-between; margin-top: 12px; font-size: .84rem; }output { color: var(--green); font: 600 .9rem var(--mono); }input[type='range'] { width: 100%; min-height: 34px; margin: 0; accent-color: var(--green); cursor: pointer; }.case-context { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 15px; }.case-context h3 { font-size: 1.24rem; margin-block: 4px 6px; }.case-context p, .explain { color: var(--dim); line-height: 1.55; font-size: .91rem; }.toolbar { align-items: center; justify-content: space-between; }#live { background: var(--green); color: var(--air); font-weight: 700; }.chip { font: .69rem var(--mono); border: 1px solid var(--line); border-radius: 999px; padding: 6px 9px; color: var(--green); }.chip[data-source='live'] { color: var(--warm); border-color: #987153; }.run-status { margin-block: 8px 12px; min-height: 1.2rem; font-size: .8rem; color: var(--dim); }.pipeline { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 5px; }.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); }.pipeline strong { font-size: .78rem; line-height: 1.2; }.pipeline button[aria-current='step'] { border-color: var(--green); background: #263f35; }.pipeline .bypass { border-style: dashed; }.inspector { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--line); }.inspect-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }.inspect-head h3 { font-size: clamp(1.4rem, 2.1vw, 2rem); line-height: 1.13; margin-block: 4px 6px; letter-spacing: -.036em; }.inspect-head time { color: var(--green); white-space: nowrap; }.explain { margin-bottom: 13px; }.route-map { margin-block: 16px 12px; }.route-root { margin-inline: auto; width: max-content; display: grid; text-align: center; gap: 3px; border: 1px solid var(--line); border-radius: 6px; padding: 6px 15px; background: var(--deep); }.route-root span { color: var(--dim); }.route-map svg { display: block; width: 100%; height: 30px; }.route-map path { vector-effect: non-scaling-stroke; fill: none; stroke: var(--line); stroke-width: 2; stroke-dasharray: 4 4; }.route-map[data-changed='false'] path:first-child { stroke: var(--green); stroke-dasharray: none; }.route-map[data-changed='true'] path:last-child { stroke: var(--warm); stroke-dasharray: none; }.branches { display: grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap: 7px; }.branch { display: flex; flex-direction: column; gap: 5px; border: 1px dashed var(--line); border-radius: 7px; padding: 8px; color: var(--dim); text-align: center; font-size: .83rem; }.branch small { font: .7rem var(--mono); }[data-changed='false'] .unchanged, [data-changed='true'] .changed { border-style: solid; border-color: currentColor; }[data-changed='false'] .unchanged { color: var(--green); background: #203a30; }[data-changed='true'] .changed { color: var(--warm); background: #3b2e27; }.pool-head { display: flex; justify-content: space-between; gap: 8px; color: var(--dim); padding: 9px 5px; letter-spacing: .02em; }.pool, .beam-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 4px; max-height: 295px; overflow-y: auto; }.slot { display: grid; grid-template-columns: 31px minmax(0,1fr) 62px; align-items: center; gap: 7px; border: 1px solid var(--line); border-radius: 6px; background: var(--deep); padding: 7px 9px; font-size: .83rem; overflow-wrap: anywhere; }.slot small { display: block; margin-top: 3px; color: var(--dim); font: .68rem/1.35 var(--mono); }.slot code, .prob { color: var(--dim); }.prob { text-align: end; font: .72rem var(--mono); font-variant-numeric: tabular-nums; }.prob span { display: block; height: 3px; margin-top: 4px; border-radius: 2px; background: #3b5952; }.prob span::before { content: ''; display: block; width: var(--p); height: 100%; background: var(--green); }.winner { border-color: var(--green); background: #203a30; }.winner .prob, .winner code { color: var(--green); }.warm { background: #3b2e27; border-color: var(--warm); }.warm .prob, .warm code { color: var(--warm); }.encoding { display: grid; grid-template-columns: minmax(0,1fr) auto minmax(0,.75fr); gap: 12px; align-items: center; background: var(--deep); border: 1px solid var(--line); border-radius: 8px; padding: 12px; }.feature-pair { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }.feature-pair div { position: relative; }.feature-pair b { position: absolute; bottom: 4px; left: 4px; padding: 2px 4px; background: var(--air); font: .72rem var(--mono); }.flow-arrow { color: var(--green); }.tensor { display: grid; justify-items: center; gap: 5px; text-align: center; }.tensor i { width: 44px; aspect-ratio: 1; border: 1px solid var(--green); background: repeating-linear-gradient(transparent 0 7px,#69a391 7px 8px),repeating-linear-gradient(90deg,#26463b 0 7px,#69a391 7px 8px); transform: rotate(-10deg) skew(10deg); box-shadow: 4px 4px #497b6b, 8px 8px #345d51; margin-bottom: 8px; }.tensor small, .fine, .empty p { color: var(--dim); font-size: .78rem; line-height: 1.45; }.fine { margin-top: 8px; }.deck { position: relative; isolation: isolate; padding: 15px 10px 3px; margin-block: 12px; }.deck i { position: absolute; z-index: -1; inset: 6px 28px 7px; border: 1px solid #679485; border-radius: 8px; background: #264238; transform: rotate(-1.25deg); }.deck i:first-child { inset: 0 45px 7px; transform: rotate(1.5deg); }.deck div, .comparison div { display: grid; gap: 7px; padding: 12px; border: 1px solid var(--line); border-radius: 7px; background: var(--deep); }.deck small { font: .72rem var(--mono); color: var(--green); }.deck strong { font-size: 1rem; }details { margin-top: 9px; padding: 8px 10px; }summary { cursor: pointer; font-size: .8rem; color: var(--green); min-height: 22px; }details p { color: var(--dim); line-height: 1.5; font-size: .85rem; padding-top: 6px; }.beam-list li { display: flex; gap: 10px; padding-block: 5px; border-top: 1px solid var(--line); font-size: .84rem; }.eligible { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; margin: 9px 0; font-size: .8rem; color: var(--dim); }.eligible span { margin-right: 5px; }.eligible code { padding: 3px 4px; border: 1px dashed var(--line); border-radius: 3px; text-decoration: line-through; }.eligible .kept { border-style: solid; color: var(--warm); text-decoration: none; }.formula { padding: 10px; border: 1px solid var(--line); border-radius: 7px; background: var(--deep); }.formula > code { color: var(--warm); letter-spacing: 0; }.comparison { display: grid; gap: 7px; }.comparison small { color: var(--dim); }.comparison div:last-child { background: #203a30; border-color: var(--green); }.comparison div:last-child small { color: var(--green); }.comparison p { font-size: .95rem; }.empty { padding: 18px 12px; color: var(--dim); border-radius: 7px; background: var(--deep); border: 1px dashed var(--line); }.empty h4 { color: var(--ink); margin-block: 4px 8px; }footer { 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 { 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)); } .pipeline button { min-height: 53px; }}@media (max-width: 700px) { .hero, .lab { grid-template-columns: minmax(0,1fr); } .hero { margin-top: 12px; } .hero-index { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); } .hero-index li:nth-child(2) { border-top: 0; } .hero-index li { padding-inline: 6px; gap: 6px; } .swipe, video { max-width: 380px; margin-inline: auto; }}@media (max-width: 390px) { .toplinks { gap: 6px; } .wordmark { font-size: .82rem; } .wordmark small, .toplinks a { font-size: .66rem; } .case { grid-template-columns: 38px minmax(0,1fr); padding: 6px; gap: 6px; } .case-number { inset: 19px auto auto 7px; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278const byId = id => document.getElementById(id);const escape = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[char]));const steps = ['encode', 'generate', 'lock', 'rerank', 'output'];const labels = { project: ['Project ↗','项目主页 ↗'], headline: ['From two images to one decision.','从两张影像,到一次决策。'], lede: ['Follow the same location through time. See how 15 captions are generated, which option locks the change state, and how the final caption is selected.','追踪同一地点的两个时相,查看 15 条候选如何生成、哪个选项锁定变化状态,以及最后如何选出描述。'], choose: ['Choose a test pair','选择测试案例'], observations: ['Bi-temporal observations','双时相观测'], trace: ['Decision trace','决策过程'], encode: ['Encode the pair','编码双图'], generate: ['Generate captions','生成候选'], lock: ['Lock the state','锁定状态'], rerank: ['Same-state reranking','同状态精排'], output: ['Final caption','最终描述'], play: ['▷ Replay trace','▷ 播放论文记录'], pause: ['Ⅱ Pause replay','Ⅱ 暂停回放'], live: ['Run on GPU ↗','GPU 实跑 ↗'],};let lang = new URLSearchParams(location.search).get('lang') === 'zh' ? 'zh' : 'en';const text = (en, zh) => lang === 'zh' ? zh : en;const label = key => text(...labels[key]);let catalog, selected, trace, phase = 2, mode = 'archive', liveEvent, busy = false, follow = true, failure = '', timer;let view = 'swipe', divider = 50, beta = 0.12;
function translate() { document.documentElement.lang = text('en','zh-CN'); document.title = `Critique-then-Rerank · ${text('Decision Lab','决策工作台')}`; for (const node of document.querySelectorAll('[data-t]')) node.textContent = label(node.dataset.t); byId('language').textContent = text('中文','EN'); byId('language').setAttribute('aria-label', text('切换到中文','Switch to English'));}
const media = path => `./media/${path.split('/').map(encodeURIComponent).join('/')}`;const stateLabel = changed => changed ? text('Changed','有变化') : text('Unchanged','无变化');const rankLabel = index => `#${String(index + 1).padStart(2, '0')}`;const image = (path, later) => `<img src="${media(path)}" width="256" height="256" alt="${later ? text('T₂: later satellite image','T₂:后一时相遥感影像') : text('T₁: earlier satellite image','T₁:前一时相遥感影像')}">`;
function renderCases() { byId('case-grid').innerHTML = catalog.cases.map((item, index) => `<button type="button" class="case" data-case="${index}" aria-pressed="${item === selected}" ${busy ? 'disabled' : ''}> <span class="case-number">0${index + 1}</span>${image(item.media[1], true).replace(/alt="[^"]*"/, 'alt=""')} <span><strong>${escape(text(item.en, item.zh))}</strong><small>${escape(item.name.replace('.png',''))}</small></span></button>`).join('');}
function renderViewer() { byId('case-id').textContent = selected.name.replace('.png',''); const [before, after] = selected.media; const modes = [['swipe',text('Swipe','拉帘')],['pair',text('Side by side','并排')],['video',text('Playback','时序播放')]]; const frame = (path, later) => `<div class="frame">${image(path, later)}<span>${later ? 'T₂' : 'T₁'}</span></div>`; let stage; if (view === 'swipe') stage = `<div class="swipe" style="--split:${divider}%">${image(before, false)}<div class="after">${image(after, true)}</div><span class="t1">T₁</span><span class="t2">T₂</span><span class="divider" aria-hidden="true"><b>‹ ›</b></span> <input id="divider" type="range" min="0" max="100" value="${divider}" aria-valuetext="${divider}%"></div> <label class="range-label" for="divider">${text('Drag to compare T₁ / T₂','拖动对比 T₁ / T₂')}<output id="divider-value">${divider}%</output></label>`; if (view === 'pair') stage = `<div class="pair">${frame(before, false)}${frame(after, true)}</div>`; if (view === 'video') stage = `<video controls playsinline preload="metadata" poster="${media(before)}" src="${media(selected.clip)}" aria-label="${text('T₁ to T₂ playback','T₁ 到 T₂ 时序播放')}"></video><p class="fine">${text('Original frames only · 2 s per observation','仅播放两张原始影像 · 每个时相 2 秒')}</p>`; byId('viewer').innerHTML = `<div class="view-mode">${modes.map(([key, title]) => `<button type="button" data-view="${key}" aria-pressed="${view === key}">${title}</button>`).join('')}</div>${stage}`; byId('case-context').innerHTML = `<span class="micro">${text('CASE GUIDE','案例导读')}</span><h3>${escape(text(selected.title_en, selected.title_zh))}</h3><p>${escape(text(selected.summary_en, selected.summary_zh))}</p>`;}
function select(index) { if (busy) return; stopReplay(); selected = catalog.cases[index]; trace = selected.replay; phase = 2; mode = 'archive'; beta = catalog.beta; divider = 50; failure = ''; renderCases(); renderViewer(); render();}
function stopReplay() { clearInterval(timer); timer = undefined;}
function replay() { if (busy) return; if (timer) { stopReplay(); render(); return; } trace = selected.replay; mode = 'archive'; phase = 0; beta = catalog.beta; failure = ''; timer = setInterval(() => { phase += trace.changed === false && phase === 2 ? 2 : 1; if (phase === 4) stopReplay(); render(); }, 1650); render();}
function level() { return mode === 'archive' ? 4 : ({encode: 0, beam: 1, stage1: 2, gate: 2, stage2: 3, done: 4}[liveEvent] ?? -1);}
function render() { const reached = level(); const titles = [label('encode'), label('generate'), label('lock'), label('rerank'), label('output')]; const short = ['RSCaMa', 'Beam-15', 'Elephant-1 · S1', trace?.changed === false ? text('Bypass','跳过') : 'Elephant-1 · S2 + β', 'Caption']; const focused = document.activeElement?.dataset.step; byId('pipeline').innerHTML = titles.map((title, index) => `<button type="button" data-step="${index}" ${index > reached ? 'disabled' : ''} ${phase === index ? 'aria-current="step"' : ''} class="${index === 3 && trace?.changed === false ? 'bypass' : ''}"><small>0${index + 1} / ${short[index]}</small><strong>${title}</strong></button>`).join(''); if (focused !== undefined) byId('pipeline').querySelector(`[data-step="${focused}"]`)?.focus({preventScroll: true}); byId('source').textContent = mode === 'archive' ? text('Paper replay · no GPU','论文记录 · 无需 GPU') : text('ZeroGPU · live run','ZeroGPU · 实时运行'); byId('source').dataset.source = mode; byId('replay').textContent = label(timer ? 'pause' : 'play'); byId('replay').disabled = busy; byId('live').disabled = busy || !catalog.live; const status = failure || (mode === 'archive' ? (catalog.live ? text('Choose any step to inspect the recorded decision.', '可点击任意步骤查看论文记录。') : text('Paper replay is ready. GPU weights are unavailable.', '可查看论文回放。GPU 权重暂不可用。')) : ({ encode: text('Encoding T₁ and T₂ on GPU…','GPU 正在编码双时相影像…'), beam: text('Decoding the 15 caption beams…','正在解码 15 条候选…'), stage1: text('Stage 1 is scoring the caption slots…','第一阶段正在为候选槽位打分…'), gate: text('Change state locked. Routing the candidate pool…','状态已锁定,正在确定候选分流…'), stage2: text('Stage 2 is scoring the eligible pool…','第二阶段正在为同状态候选打分…'), 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">${text('The trace will open when the GPU starts.','GPU 开始运行后会打开决策记录。')}</div>` : inspect(); if (phase === 3 && trace?.stage2?.length > 1) updateRanking();}
function head(index, description) { const time = trace?.timings?.[['encode','beam','stage1','stage2'][index]]; return `<div class="inspect-head"><div><span class="micro">STEP 0${index + 1}</span><h3>${label(steps[index])}</h3></div>${time === undefined ? '' : `<time>${time.toFixed(2)} s</time>`}</div><p class="explain">${description}</p>`;}
function inspect() { if (phase === 0) return head(0, text('RSCaMa encodes the earlier and later views of the same location into joint visual features for the caption generator.','RSCaMa 将同一地点的前后影像编码为联合视觉特征,交给描述生成器。')) + ` <div class="encoding"><div class="feature-pair">${selected.media.map((path, index) => `<div>${image(path, index === 1)}<b>T${index + 1}</b></div>`).join('')}</div> <span class="flow-arrow" aria-hidden="true">→</span><div class="tensor"><i aria-hidden="true"></i><b>RSCaMa</b><small>${trace?.feature_shape ? trace.feature_shape.join(' × ') : text('Joint visual features','联合视觉特征')}</small></div></div> <p class="fine">${text('Feature icon is schematic. Both Elephant-1 stages also receive the original image pair when they run.','特征图标为示意;Elephant-1 两阶段执行时也会读取原始双时相影像。')}</p>`;
if (phase === 1) return head(1, text('The SCST RSCaMa decoder uses beam search to propose 15 captions. Beam #01 is the generator’s baseline; every beam goes to Stage 1.','SCST RSCaMa 通过束搜索生成 15 条描述。Beam #01 是生成器的基线输出,所有候选都进入第一阶段。')) + (trace?.captions ? ` <div class="deck"><i aria-hidden="true"></i><i aria-hidden="true"></i><div><small>BEAM ${rankLabel(0)} / TOP-1</small><strong lang="en">${escape(trace.captions[0])}</strong></div></div> <details><summary>${text('Inspect all Beam-15 candidates','查看全部 15 条候选')}</summary><ol class="beam-list">${trace.captions.map((caption, index) => `<li><code>${rankLabel(index)}</code><span lang="en">${escape(caption)}</span></li>`).join('')}</ol></details>` : pending());
if (phase === 2) return head(2, text('Elephant-1 sees both images and the 15 descriptions. The highest-probability slot becomes the anchor; its caption sets the change state.','Elephant-1 读取双图和 15 条描述,选择概率最高的槽位作为锚点,由这条描述锁定变化状态。')) + (trace?.stage1 ? ` <div class="route-map" data-changed="${trace.changed}"><div class="route-root"><span>ARGMAX · STAGE 1</span><strong>Beam ${rankLabel(trace.anchor)}</strong></div> <svg viewBox="0 0 400 43" preserveAspectRatio="none" aria-hidden="true"><path d="M200 0V19H100V43"/><path d="M200 0V19H300V43"/></svg> <div class="branches"><div class="branch unchanged"><small>${trace.changed ? '○' : '●'} ${stateLabel(false)}</small><b>${text('Output the anchor','直接输出锚点')}</b></div><div class="branch changed"><small>${trace.changed ? '●' : '○'} ${stateLabel(true)}</small><b>${text('Route to Stage 2','进入第二阶段')}</b></div></div></div> <div class="pool-head"><span>${text('Stage 1 slots · sorted by probability','第一阶段槽位 · 按概率排序')}</span><span>P(slot)</span></div> <ol class="pool">${trace.stage1.slice().sort((first, second) => second[1] - first[1]).map(([index, prob]) => { const isAnchor = index === trace.anchor; return `<li class="slot ${isAnchor ? 'winner' : ''}"><code>${rankLabel(index)}</code><div><span lang="en">${escape(trace.captions[index])}</span><small>caption_${index + 1} · ${stateLabel(!catalog.templates.includes(trace.captions[index]))}${isAnchor ? ` · ${text('ANCHOR','锚点')}` : ''}</small></div><div class="prob"><b>${(prob * 100).toFixed(2)}%</b><span style="--p:${prob * 100}%"></span></div></li>`; }).join('')}</ol>` : pending()) + task(0);
if (phase === 3) { if (trace.changed === false) return head(3, text('Stage 1 locked Unchanged. The anchor goes straight to the output.','第一阶段已锁定无变化,锚点直接作为最终输出。')) + `<div class="empty bypass-note"><span class="micro">BYPASS / UNCHANGED</span><h4>${text('No Stage 2 call','未调用第二阶段')}</h4><p>${text('There are no Stage 2 scores on this route. A wrong state lock also cannot be reversed downstream.','这条路径没有第二阶段得分。若第一阶段锁错状态,下游也无法翻转。')}</p></div>`; return head(3, text('Keep only distinct eligible change captions. Elephant-1 scores their factual fit; β trades off the slot score against caption length.','过滤无变化和重复候选。Elephant-1 对保留的变化描述打分,再用 β 在槽位得分和句子长度之间做权衡。')) + ` <div class="eligible"><span>${trace.eligible?.length ?? 0} / ${trace.captions?.length ?? 0} ${text('eligible','条保留')}</span>${trace.captions?.map((caption, index) => `<code class="${trace.eligible?.includes(index) ? 'kept' : ''}" title="${escape(caption)}">${rankLabel(index)}</code>`).join('') ?? ''}</div>` + (trace.stage2?.length > 1 ? `<div class="formula"><code>log(max(P(slot), 10⁻³⁰)) − β × words</code><label class="range-label" for="beta">${text('Length penalty β','长度惩罚 β')}<output id="beta-value">${beta.toFixed(2)}</output></label><input id="beta" type="range" min="0" max="0.20" step="0.02" value="${beta}"><p class="fine">${text('The slider explores this fixed candidate pool. The final tab uses the paper’s β.', '滑块只改变当前候选的排序;最终描述页仍使用论文 β。')}</p></div><div id="ranks"></div>` : liveEvent === 'done' || mode === 'archive' ? `<div class="empty">${trace.eligible?.length ? text('One eligible caption: selected directly.','仅一条合格候选,直接选择。') : text('No eligible captions: keep the Stage 1 anchor.','无合格候选,保留第一阶段锚点。')}</div>` : pending()) + task(1); }
return head(4, trace.changed ? text(`The change state remains locked. The final caption uses the paper setting β = ${catalog.beta.toFixed(2)}.`,`变化状态保持锁定。最终描述使用论文设置 β = ${catalog.beta.toFixed(2)}。`) : text('The Stage 1 anchor is the final output; Stage 2 was bypassed.','第一阶段锚点直接输出,第二阶段未执行。')) + `<div class="comparison">${[ [text('Generator baseline','生成器基线'),0], [text('Stage 1 anchor','第一阶段锚点'),trace.anchor], [label('output'),trace.final], ].map(([title, index]) => `<div><small>${title} · BEAM ${rankLabel(index)}</small><p lang="en">${escape(trace.captions[index])}</p></div>`).join('')}</div>`;}
const pending = () => `<div class="empty">${text('Waiting for this stage’s GPU output…','等待该阶段返回 GPU 结果…')}</div>`;const task = index => `<details class="task"><summary>${text('Inspect the actual task instruction','查看实际任务指令(英文)')}</summary><p lang="en">${escape(catalog.tasks[index])}</p></details>`;
function updateRanking() { const needle = byId('beta'); byId('beta-value').textContent = beta.toFixed(2); needle.setAttribute('aria-valuetext', beta.toFixed(2)); const ranked = trace.stage2.map(([index, probability], slot) => { const caption = trace.captions[index]; const words = caption.trim() ? caption.trim().split(/\s+/u).length : 0; const log = Math.log(Math.max(probability, 1e-30)); return {index, probability, slot, words, log, score: log - beta * words, caption}; }).sort((first, second) => second.score - first.score); byId('ranks').innerHTML = `<div class="pool-head"><span>${text('Eligible pool · sorted by calibrated score','同状态候选 · 按校准分排序')}</span><span>${text('Score','得分')}</span></div><ol class="pool">${ranked.map(({index, probability, slot, words, log, score, caption}, position) => `<li class="slot ${position === 0 ? 'winner warm' : ''}"> <code>${rankLabel(index)}</code><div><span lang="en">${escape(caption)}</span><small>item_${slot + 1} · P ${(probability * 100).toFixed(2)}% · ln P ${log.toFixed(3)} · ${words} ${text('words','词')} · −${(beta * words).toFixed(3)}</small></div><div class="prob"><b>${score.toFixed(4)}</b>${position === 0 ? `<small>${text('SELECTED','选中')}</small>` : ''}</div></li>`).join('')}</ol>`;}
async function run() { if (busy || !catalog.live) return; stopReplay(); busy = true; mode = 'live'; failure = ''; follow = true; trace = null; liveEvent = undefined; phase = 0; beta = catalog.beta; renderCases(); render(); let source; try { const endpoint = './engine/gradio_api/call/run_case'; const response = await fetch(endpoint, {method:'POST', headers:{'Content-Type':'application/json'}, 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'); source = new EventSource(`${endpoint}/${encodeURIComponent(eventId)}`); await new Promise((resolve, reject) => { const onTrace = event => { try { const [payload] = JSON.parse(event.data); if (payload.name !== selected.name || !['encode','beam','stage1','gate','stage2','done'].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(); if (liveEvent === 'gate' && trace.changed === false && follow) phase = 2; if (event.type === 'complete') resolve(); render(); } catch (error) { reject(error); } }; source.addEventListener('generating', onTrace); source.addEventListener('complete', onTrace); source.addEventListener('error', () => reject(new Error('Live stream failed'))); }); } catch { failure = text('Live run interrupted. Try again when GPU quota is available, or switch to paper replay.','实时推理中断。可在 GPU 配额可用时重试,或切换到论文记录。'); } finally { source?.close(); busy = false; renderCases(); render(); }}
byId('language').addEventListener('click', () => { lang = lang === 'en' ? 'zh' : 'en'; translate(); if (catalog) { renderCases(); renderViewer(); render(); }});byId('case-grid').addEventListener('click', event => { const button = event.target.closest('[data-case]'); if (button) { select(Number(button.dataset.case)); byId('case-grid').querySelector(`[data-case="${button.dataset.case}"]`)?.focus({preventScroll:true}); }});byId('viewer').addEventListener('click', event => { const button = event.target.closest('[data-view]'); if (button && button.dataset.view !== view) { view = button.dataset.view; renderViewer(); byId('viewer').querySelector(`[data-view="${view}"]`)?.focus({preventScroll:true}); }});byId('viewer').addEventListener('input', event => { if (event.target.id !== 'divider') return; divider = Number(event.target.value); byId('viewer').querySelector('.swipe').style.setProperty('--split', `${divider}%`); event.target.setAttribute('aria-valuetext', `${divider}%`); byId('divider-value').textContent = `${divider}%`;});byId('pipeline').addEventListener('click', event => { const button = event.target.closest('[data-step]'); if (!button) return; stopReplay(); follow = false; phase = Number(button.dataset.step); render();});byId('inspector').addEventListener('input', event => { if (event.target.id !== 'beta') return; beta = Number(event.target.value); updateRanking();});byId('replay').addEventListener('click', () => { if (catalog) replay(); });byId('live').addEventListener('click', () => { if (catalog) run(); });
translate();byId('live').disabled = byId('replay').disabled = true;try { const response = await fetch('./catalog'); if (!response.ok) throw new Error('Catalog unavailable'); catalog = await response.json(); select(0);} catch { byId('status').textContent = text('Cases could not load. Refresh to retry.', '未能加载案例,请刷新重试。');}README.md+2-2
app.py+44-153
inference.py+27-13
public/cases.json+1-1
workbench/index.htmlAdded+49
workbench/lab.cssAdded+181
workbench/lab.jsAdded+278