#!/usr/bin/env python3 """nDCG@10 vs checkpoint step for the Qwen3-Embedding-0.6B data-ablation runs, one graph per benchmark (AnaloBench: one per metric, 2026-10-08) (2026-10-07, user: see how every model's metric moves with the step; one graph per benchmark, the per-split graphs removed). Written to cleaned/train/graph.md ('### ' + graph). BRIGHT: y = nDCG@10 averaged over the StackExchange splits finished so far (each split = 101 sampled queries, whole split corpus; a split counts once every run has all STEPS in results/se101/abl_.json), x = training step. Colour = training data (fixed order), solid = with hard negatives, dashed = without; markers differ too, so identity is not colour alone. Grey dotted line = Qwen3-Embedding-0.6B before fine-tuning (its default query prompt, so only a reference). python plot_steps.py (run with .venv-qwen: matplotlib)""" import json, statistics from pathlib import Path import matplotlib, matplotlib.patches matplotlib.use('Agg') import matplotlib.pyplot as plt ROOT = Path(__file__).resolve().parents[2]; EXP = ROOT / 'experiments'; RES = EXP / 'bright_eval' / 'results' / 'se101'; OUT = ROOT / 'cleaned' / 'train' SPLITS = ['economics', 'psychology', 'biology', 'sustainable_living', 'robotics', 'stackoverflow', 'earth_science'] DATA = [('ours', '#2a78d6', 'o'), ('msmarco', '#eb6834', 's'), ('reasonir', '#1baf7a', '^'), ('specter', '#eda100', 'D')] # dataviz palette slots 1-4 STEPS = [40, 140, 200, 375] LBL = {'ours': 'ours-2500'} # 2026-10-08 (user): ablation 'ours' (2,506 pairs) shown as ours-2500 RN = lambda r: 'ours-2500' + r[4:] if r.startswith('ours') else r # 2026-10-08: canho/ours-6k run (5,469 pairs, same recipe; checkpoint every 10 steps), user: a step-wise line, not one point. Steps = the ablation # steps (375 not saved -> 380) + 310 (lowest eval loss) + 500/600/700 + 815 (last). Dataviz slot 7 violet, star markers; # the 310 point is labelled. x axis runs to 800 for this run. O6K_STEPS, O6K_C = [40, 140, 200, 310, 380, 500, 600, 700, 815], '#4a3aa7' XT, XMAX = [40, 140, 200, 310, 375, 500, 600, 700, 815], 850 def o6k_line(ax, get): pts = [(n, get(f'abl_ours6k_c{n}')) for n in O6K_STEPS]; pts = [(n, y) for n, y in pts if y is not None] if not pts: return 0 ax.plot([n for n, _ in pts], [y for _, y in pts], color=O6K_C, linewidth=2, marker='*', markersize=10, markeredgecolor=O6K_C, label='ours-6k (5,469 pairs)', zorder=4) for n, y in pts: if n == 310: ax.annotate(f'c310 (lowest eval loss)\n{y:.3f}', (n, y), xytext=(0, -10), textcoords='offset points', fontsize=6.5, color=INK2, va='top', ha='center', linespacing=1.1) return max(y for _, y in pts) INK, INK2, GRID, SURF = '#0b0b0b', '#52514e', '#e4e3df', '#fcfcfb' runs = [d for d, _, _ in DATA] + [d + '_nohn' for d, _, _ in DATA] S = {} for s in SPLITS: f = RES / f'abl_{s}.json' if f.exists(): x = json.load(open(f))['splits'][s] if all(f'abl_{r}_c{n}' in x for r in runs for n in STEPS): S[s] = x assert S, 'no finished split' mac = lambda m: statistics.mean(S[s][m]['nDCG@10'][0] for s in S) fig, ax = plt.subplots(figsize=(7.2, 4.8), dpi=150); fig.patch.set_facecolor(SURF); ax.set_facecolor(SURF) base = mac('qwen06b'); ax.axhline(base, color=INK2, linewidth=1, linestyle=(0, (1, 2))) ax.text(XMAX - 5, base, f'before ft\n{base:.3f}', color=INK2, fontsize=7, va='center', ha='right', linespacing=1.1) rows = [] for d, c, mk in DATA: for nohn in (False, True): r = d + ('_nohn' if nohn else ''); y = [mac(f'abl_{r}_c{n}') for n in STEPS]; rows.append((r, y)) ax.plot(STEPS, y, color=c, linewidth=2, linestyle=(0, (5, 3)) if nohn else '-', marker=mk, markersize=6, markerfacecolor=SURF if nohn else c, markeredgecolor=c, markeredgewidth=1.5, label=LBL.get(d, d) + (' (no hard neg)' if nohn else ''), zorder=3) o6k = {n: mac(f'abl_ours6k_c{n}') for n in O6K_STEPS if all(f'abl_ours6k_c{n}' in S[s] for s in S)} o6k_top = o6k_line(ax, lambda m: o6k.get(int(m.rsplit('_c', 1)[1]))) ax.set_xticks(XT); ax.set_xlim(0, XMAX); ax.set_ylim(0, max(o6k_top, *(max(y) for _, y in rows)) * 1.12) ax.set_xlabel('training step (checkpoint)', fontsize=8, color=INK2); ax.set_ylabel(f'nDCG@10 (mean of {len(S)} splits)', fontsize=8, color=INK2) ax.set_title(f'BRIGHT StackExchange ({len(S)}/7 splits) / Qwen3-Embedding-0.6B ft by training data', fontsize=9, color=INK, loc='left') ax.tick_params(labelsize=7, colors=INK2, length=0); ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True) for k in ('top', 'right', 'left'): ax.spines[k].set_visible(False) ax.spines['bottom'].set_color(GRID) ax.legend(fontsize=7, frameon=False, ncol=4, loc='upper center', bbox_to_anchor=(0.5, -0.14), handlelength=3.2, columnspacing=1.2); fig.tight_layout() (OUT / 'graphs').mkdir(parents=True, exist_ok=True); fig.savefig(OUT / 'graphs' / 'bright.png', facecolor=SURF); plt.close(fig) md = ['# 학습 step별 지표 변화 (Qwen3-Embedding-0.6B 학습 데이터 ablation)', '', '평가 데이터셋별 그래프:', f'- **BRIGHT StackExchange** (`xlangai/BRIGHT`, {len(S)}/7 split, split마다 101 query, split corpus 전체 검색) — nDCG@10 그래프 1개', *(['- **AnaloBench** (`jhu-clsp/AnaloBench`, 길이 S1·S10·S30 평균; T2 = 질의마다 200개 story bank 검색, T1 = 보기 4개 중 선택) — 지표마다 그래프 1개' '(nDCG@10, MAP, MRR, P@3, P@5, R@3, R@5, T1 acc), 최대 512 / 1024 token 나란히'] if (EXP / 'analobench_eval' / 'results' / 'eval.json').exists() else []), *(['- **우리 평가셋 190쌍** (HF `dangerousmanbyeonggeonlee/ours-test-190`, eval20x26 pool: 정답 1 + negative 150) — 지표마다 그래프 1개(R@1, R@5, R@10, MRR@10), main / cross_domain 나란히'] if (EXP / 'ours190_eval' / 'results' / 'eval.json').exists() else []), '', '`cleaned/evaluation/plot_steps.py`로 생성. BRIGHT는 그래프 하나, AnaloBench는 지표마다 하나: 세로축 지표, 가로축 학습 step(평가한 checkpoint 40·140·200·375; 140 = ours eval loss 최저),', '선 하나 = 학습 데이터 하나(색 = 데이터, 실선 = hard negative 있음, 점선 = 없음). 회색 점선 = fine-tuning 전 0.6B(BRIGHT는 모델 기본 query prompt라 참고용, AnaloBench는 같은 `Query:`).', '보라 별 선 = ours-6k(canho/ours-6k 5,469쌍, 같은 레시피, 2026-10-08): step 40·140·200·310(eval loss 최저)·380(375는 저장 안 됨)·500·600·700·815(마지막). 데이터가 2.2배라 같은 step이 다른 epoch(ours-6k step 310 ≈ ablation step 140 ≈ epoch 1.9).', '', f'### BRIGHT StackExchange ({len(S)}/7 split: {", ".join(S)})', '', f'메인 지표 nDCG@10, 완료된 split의 평균(split마다 101 query, split corpus 전체 검색; 설정은 `cleaned/README.md` ablation의 BRIGHT 절). split별 값·95% CI는 README 표.', '', '![BRIGHT](graphs/bright.png)', '', '| 학습 데이터 | ' + ' | '.join(f'step {n}' for n in STEPS) + ' |', '|---|' + '---|' * len(STEPS)] md += [f'| {RN(r)} | ' + ' | '.join(f'{v:.3f}' for v in y) + ' |' for r, y in rows] + [f'| fine-tuning 전 (참고) | ' + ' | '.join(f'{base:.3f}' for _ in STEPS) + ' |'] # AnaloBench (2026-10-08, user: one graph per metric): experiments/analobench_eval/results/eval.json, y = mean over S1/S10/S30, left panel # max 512 tokens, right panel 1024 (S1/S10 fit in 512, so only S30 differs). Same lines/colours as BRIGHT; grey dotted = 0.6B before ft, same 'Query:'. AB = EXP / 'analobench_eval' / 'results' / 'eval.json' if AB.exists(): ab = json.load(open(AB)); AK = ['nDCG@10', 'MAP', 'MRR', 'P@3', 'P@5', 'R@3', 'R@5', 'T1 acc'] md += ['', '### AnaloBench (`jhu-clsp/AnaloBench`, 지표마다 그래프 하나)', '', '`cleaned/evaluation/analobench/`(설정은 `cleaned/README.md` ablation의 AnaloBench 절). 세로축 = S1·S10·S30 평균, 왼쪽 최대 512 token, 오른쪽 1024 token', '(S1·S10은 모두 512 안이라 두 쪽 값이 같고 S30만 다름). T2 지표(nDCG@10, 논문 지표 MAP·MRR·P@3·P@5·R@3·R@5)는 질의마다 200개 bank, T1 acc는 T1-Full(보기 4개).', '선·색은 BRIGHT와 같고, 회색 점선 = fine-tuning 전 0.6B(같은 `Query:` prompt).', ''] for k in AK: fig, axs = plt.subplots(1, 2, figsize=(10, 4.6), dpi=150, sharey=True); fig.patch.set_facecolor(SURF); top = 0 for ax, x in zip(axs, (512, 1024)): M = ab[f'm{x}']['mean']; ax.set_facecolor(SURF); base = M['qwen06b'][k]; ax.axhline(base, color=INK2, linewidth=1, linestyle=(0, (1, 2))) ax.text(XMAX - 5, base, f'before ft\n{base:.3f}', color=INK2, fontsize=7, va='center', ha='right', linespacing=1.1) for d, c, mk in DATA: for nohn in (False, True): r = d + ('_nohn' if nohn else ''); y = [M[f'abl_{r}_c{n}'][k] for n in STEPS]; top = max(top, *y, base) ax.plot(STEPS, y, color=c, linewidth=2, linestyle=(0, (5, 3)) if nohn else '-', marker=mk, markersize=6, markerfacecolor=SURF if nohn else c, markeredgecolor=c, markeredgewidth=1.5, label=LBL.get(d, d) + (' (no hard neg)' if nohn else ''), zorder=3) top = max(top, o6k_line(ax, lambda m: M[m][k] if m in M else None)) ax.set_xticks(XT); ax.set_xlim(0, XMAX); ax.set_title(f'max {x} tokens', fontsize=8, color=INK2, loc='left') ax.set_xlabel('training step (checkpoint)', fontsize=8, color=INK2); ax.tick_params(labelsize=7, colors=INK2, length=0) ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True); ax.spines['bottom'].set_color(GRID) for sp in ('top', 'right', 'left'): ax.spines[sp].set_visible(False) axs[0].set_ylim(0, top * 1.12); axs[0].set_ylabel(f'{k} (mean of S1/S10/S30)', fontsize=8, color=INK2) fig.suptitle(f'AnaloBench {k} / Qwen3-Embedding-0.6B ft by training data', fontsize=9, color=INK, x=0.01, ha='left') h, l = axs[0].get_legend_handles_labels(); fig.legend(h, l, fontsize=7, frameon=False, ncol=4, loc='lower center', handlelength=3.2, columnspacing=1.2) fig.tight_layout(rect=(0, 0.1, 1, 1)); f = 'analobench_' + k.replace('@', '').replace(' ', '_').lower() + '.png' fig.savefig(OUT / 'graphs' / f, facecolor=SURF); plt.close(fig) md += [f'#### {k}', '', f'![AnaloBench {k}](graphs/{f})', '', '| 학습 데이터 | ' + ' | '.join(f'{x} · step {n}' for x in (512, 1024) for n in STEPS) + ' |', '|---|' + '---|' * 8] md += [f'| {RN(r)} | ' + ' | '.join(f"{ab[f'm{x}']['mean'][f'abl_{r}_c{n}'][k]:.3f}" for x in (512, 1024) for n in STEPS) + ' |' for r in [d + t for d, _, _ in DATA for t in ('', '_nohn')]] md += [f'| fine-tuning 전 (참고) | ' + ' | '.join(f"{ab[f'm{x}']['mean']['qwen06b'][k]:.3f}" for x in (512, 1024) for n in STEPS) + ' |', f'| random | ' + ' | '.join(f"{ab[f'm{x}']['mean']['random'][k]:.3f}" for x in (512, 1024) for n in STEPS) + ' |', ''] o6 = [n for n in O6K_STEPS if f'abl_ours6k_c{n}' in ab['m512']['mean']] if o6: md += ['| ours-6k (5,469쌍) | ' + ' | '.join(f'step {n}' for n in o6) + ' |', '|---|' + '---|' * len(o6)] + \ [f'| max {x} | ' + ' | '.join(f"{ab[f'm{x}']['mean'][f'abl_ours6k_c{n}'][k]:.3f}" for n in o6) + ' |' for x in (512, 1024)] + [''] # Our eval set, 190 pairs with the eval20x26 pools (2026-10-08, user: step-wise curves): experiments/ours190_eval/results/eval.json # (cleaned/evaluation/ours190/). One graph per metric, left panel main pool (151), right cross_domain (101). Lines: ours-6k (violet, as above), # ablation ours (blue, slot 1), step-1 run (slot 5 magenta, ckpt 40 / 210). Grey reference lines: Qwen3-Embedding-0.6B before ft (dotted) and # Qwen3-Embedding-8B (dash-dot); every other model is in the table under each graph and in cleaned/README.md. OE = EXP / 'ours190_eval' / 'results' / 'eval.json' if OE.exists(): oe = json.load(open(OE))['summary']; OK = ['R@1', 'R@5', 'R@10', 'MRR@10'] md += ['', '### 우리 평가셋 190쌍 (eval20x26 pool, 지표마다 그래프 하나)', '', '`cleaned/evaluation/ours190/`(설정은 `cleaned/README.md` "ours-6k 학습"의 평가 소절). HF `dangerousmanbyeonggeonlee/ours-test-190`: 1,300쌍 평가셋 중 기존 20x26에서 온 190쌍, query마다', '정답 1 + negative 150(q_side·pos_side·other 각 50). 왼쪽 main(151개), 오른쪽 cross_domain(q_side 제외 101개). 보라 = ours-6k(5,469쌍), 파랑 = ablation ours(2,506쌍),', '분홍 = step-1(1,389쌍, ckpt 40·210). 회색 점선 = fine-tuning 전 0.6B(모델 기본 prompt), 회색 점·선 = Qwen3-Embedding-8B. 나머지 비교 모델은 README 표.', ''] for k in OK: fig, axs = plt.subplots(1, 2, figsize=(10, 4.6), dpi=150, sharey=True); fig.patch.set_facecolor(SURF); top = 0 for ax, v in zip(axs, ('main', 'cross_domain')): M = oe[v]; ax.set_facecolor(SURF); g = lambda m: M[m][k][0] if m in M else None for m, ls, nm in (('qwen06b', (0, (1, 2)), 'before ft'), ('qwen3', (0, (4, 2, 1, 2)), 'Qwen3 8B')): if m in M: ax.axhline(g(m), color=INK2, linewidth=1, linestyle=ls); ax.text(XMAX - 5, g(m), f'{nm}\n{g(m):.3f}', color=INK2, fontsize=7, va='center', ha='right', linespacing=1.1); top = max(top, g(m)) for ms, c, mk, lab in (([(n, f'abl_ours_c{n}') for n in STEPS], '#2a78d6', 'o', 'ours-2500 (2,506 pairs)'), ([(40, 'qwen06b_ft40'), (210, 'qwen06b_ft210')], '#e87ba4', 's', 'step-1 (1,389 pairs)')): pts = [(n, g(m)) for n, m in ms if g(m) is not None] if pts: ax.plot([n for n, _ in pts], [y for _, y in pts], color=c, linewidth=2, marker=mk, markersize=6, label=lab, zorder=3); top = max(top, *(y for _, y in pts)) top = max(top, o6k_line(ax, g)) ax.set_xticks(XT); ax.set_xlim(0, XMAX); ax.set_title(f"{v} (pool {M['pool_size']}, {M['n']} queries)", fontsize=8, color=INK2, loc='left') ax.set_xlabel('training step (checkpoint)', fontsize=8, color=INK2); ax.tick_params(labelsize=7, colors=INK2, length=0) ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True); ax.spines['bottom'].set_color(GRID) for sp in ('top', 'right', 'left'): ax.spines[sp].set_visible(False) axs[0].set_ylim(0, top * 1.15); axs[0].set_ylabel(k, fontsize=8, color=INK2) fig.suptitle(f'Our eval set (190 pairs, eval20x26 pools) {k} / Qwen3-Embedding-0.6B ft', fontsize=9, color=INK, x=0.01, ha='left') h, l = axs[0].get_legend_handles_labels(); fig.legend(h, l, fontsize=7, frameon=False, ncol=3, loc='lower center', handlelength=3.2, columnspacing=1.2) fig.tight_layout(rect=(0, 0.08, 1, 1)); f = 'ours190_' + k.replace('@', '').lower() + '.png' fig.savefig(OUT / 'graphs' / f, facecolor=SURF); plt.close(fig) rows_ = [('ours-6k (5,469쌍)', [(n, f'abl_ours6k_c{n}') for n in O6K_STEPS]), ('ours-2500 (2,506쌍)', [(n, f'abl_ours_c{n}') for n in STEPS]), ('step-1 (1,389쌍)', [(40, 'qwen06b_ft40'), (210, 'qwen06b_ft210')])] md += [f'#### {k}', '', f'![ours190 {k}](graphs/{f})', '', '| run | pool | ' + ' | '.join(f'step {n}' for n in sorted({n for _, ms in rows_ for n, _ in ms})) + ' |', '|---|---|' + '---|' * len({n for _, ms in rows_ for n, _ in ms})] allst = sorted({n for _, ms in rows_ for n, _ in ms}) for nm, ms in rows_: d = dict(ms) for v in ('main', 'cross_domain'): md.append(f'| {nm} | {v} | ' + ' | '.join(f"{oe[v][d[n]][k][0]:.3f}" if n in d and d[n] in oe[v] else '' for n in allst) + ' |') md += [f"| fine-tuning 전 0.6B / Qwen3 8B (참고) | main | {oe['main']['qwen06b'][k][0]:.3f} / {oe['main']['qwen3'][k][0]:.3f}" + ' |' * len(allst), f"| fine-tuning 전 0.6B / Qwen3 8B (참고) | cross_domain | {oe['cross_domain']['qwen06b'][k][0]:.3f} / {oe['cross_domain']['qwen3'][k][0]:.3f}" + ' |' * len(allst), ''] # Data size (2026-10-08, user: show that more of our data gives lower loss and a better score): the three Qwen3-Embedding-0.6B runs on our data # only, same recipe (32 q/step) — step-1 1,389 / ours-2500 2,506 / ours-6k 5,469 pairs. Graph 1 = our eval set (190 pairs) R@1 / R@5 / R@10 bars # by number of training pairs (below); graph 2 = train loss per step (thin = every logged step, thick = mean of 5 logs; user: show # how the loss falls, so no eval-loss panel). Ordinal blue ramp (dataviz sequential steps 250 / 450 / 650): # darker + thicker + bigger marker = more data, and every line is labelled with its pair count. Losses: experiments/data_scaling/train_loss.json. SC = [('step1', '1,389 pairs (step-1)', '#86b6ef', 's', 1.6, [(40, 'qwen06b_ft40'), (210, 'qwen06b_ft210')]), ('ours2500', '2,506 pairs (ours-2500)', '#2a78d6', 'o', 2.1, [(n, f'abl_ours_c{n}') for n in STEPS]), ('ours6k', '5,469 pairs (ours-6k)', '#104281', 'D', 2.6, [(n, f'abl_ours6k_c{n}') for n in O6K_STEPS])] TL = EXP / 'data_scaling' / 'train_loss.json' scal = [] if OE.exists() and TL.exists(): tl = json.load(open(TL)); k = 'MRR@10' def box(ax, head, rows, x0, y0): # key-value box in axes coords: run marker (colour + shape) + pair count + value; largest data first ax.add_patch(matplotlib.patches.Rectangle((x0 - 0.015, y0 - 0.065 * len(rows) - 0.06), 0.47, 0.065 * len(rows) + 0.075, transform=ax.transAxes, facecolor=SURF, edgecolor=GRID, linewidth=0.8, zorder=5)) ax.text(x0, y0, head, transform=ax.transAxes, fontsize=7.5, color=INK2, va='top', zorder=6) for i, (r, txt) in enumerate(rows): _, lab, c, mk, lw, _ = next(t for t in SC if t[0] == r); yy = y0 - 0.065 * (i + 1) ax.plot([x0 + 0.012], [yy - 0.018], transform=ax.transAxes, marker=mk, markersize=7, color=c, markeredgecolor=SURF, clip_on=False, zorder=6) ax.text(x0 + 0.035, yy, f'{lab.split(" (")[0]}: {txt}', transform=ax.transAxes, fontsize=7.5, color=INK, va='top', fontweight='bold' if r == 'ours6k' else 'normal', zorder=6) # Graph 1, 2026-10-08 (user: discrete, x = number of training pairs, y = R@1 / R@5 / R@10, one bar graph per metric; the step-wise MRR@10 # line graph removed; then: main pool only, cross_domain panel removed, and the R@5 graph gets a second panel = BRIGHT StackExchange # nDCG@10 (BRIGHT's official metric), macro mean over the 7 splits (results/se101/eval_se_abl.json, no CI for the mean)). # Bar = the run's best evaluated checkpoint for that metric (step-1 40/210, ours-2500 40/140/200/375, ours-6k 40/.../815), written below # the bar; whisker = 95% query-bootstrap CI (our eval set only). Dotted = Qwen3-Embedding-0.6B before fine-tuning. BR = json.load(open(EXP / 'bright_eval' / 'results' / 'se101' / 'eval_se_abl.json'))['macro'] BR_MS = {'step1': [(40, 'qwen06b_ft40'), (210, 'qwen06b_ft210')], 'ours2500': [(n, f'abl_ours_c{n}') for n in STEPS], 'ours6k': [(n, f'abl_ours6k_c{n}') for n in O6K_STEPS]} def bars(ax, vals, base, ylab, title): # vals: per run (step, y, lo, hi) in SC order, lo/hi None = no CI top = 0; ax_pad = max(v[1] if v[3] is None else v[3] for v in vals) * 0.015 for i, ((r, lab, c, *_), (n, y, lo, hi)) in enumerate(zip(SC, vals)): ax.bar(i, y, width=0.62, color=c, edgecolor=SURF, linewidth=2, zorder=3); t = y if hi is None else hi; top = max(top, t) if hi is not None: ax.errorbar(i, y, yerr=[[y - lo], [hi - y]], fmt='none', ecolor=INK2, elinewidth=1, capsize=4, zorder=4) ax.text(i, t + ax_pad, f'{y:.3f}', ha='center', va='bottom', fontsize=8.5, color=INK, fontweight='bold' if r == 'ours6k' else 'normal') ax.text(i, 0.006, f'step {n}', ha='center', va='bottom', fontsize=7, color=SURF if r != 'step1' else INK, zorder=5) ax.set_facecolor(SURF); ax.set_ylim(0, max(top, base) * 1.15); ax.axhline(base, color=INK2, linewidth=1, linestyle=(0, (1, 2)), zorder=2) ax.text(2.95, base + top * 0.01, f'before ft\n{base:.3f}', color=INK2, fontsize=6.5, va='bottom', ha='right', linespacing=1.1) ax.set_xticks(range(len(SC))); ax.set_xticklabels([lab.split(' (')[0] for _, lab, *_ in SC], fontsize=8, color=INK) ax.set_xlim(-0.55, 2.95); ax.tick_params(axis='y', labelsize=7, colors=INK2, length=0); ax.tick_params(axis='x', length=0) ax.set_xlabel('number of training pairs (our data)', fontsize=8, color=INK2); ax.set_ylabel(ylab, fontsize=8, color=INK2) ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True); ax.spines['bottom'].set_color(GRID) for sp in ('top', 'right', 'left'): ax.spines[sp].set_visible(False) ax.set_title(title, fontsize=8, color=INK2, loc='left') best = {}; M = oe['main'] for k in ('R@1', 'R@5', 'R@10'): for r, lab, c, mk, lw, ms in SC: n, m = max(((n, m) for n, m in ms if m in M), key=lambda t: M[t[1]][k][0]); best[(k, r)] = (n, *M[m][k]) two = k == 'R@5' fig, axs = plt.subplots(1, 2 if two else 1, figsize=(9.6 if two else 5.6, 4.6), dpi=150); fig.patch.set_facecolor(SURF); axs = axs if two else [axs] bars(axs[0], [best[(k, r)] for r, *_ in SC], M['qwen06b'][k][0], f'{k} (our eval set, 190 pairs)', f"our eval set, main pool ({M['pool_size']} docs, {M['n']} queries), 95% CI") if two: for r, *_ in SC: n, m = max(BR_MS[r], key=lambda t: BR[t[1]]['nDCG@10']); best[('bright', r)] = (n, BR[m]['nDCG@10'], None, None) bars(axs[1], [best[('bright', r)] for r, *_ in SC], BR['qwen06b']['nDCG@10'], 'nDCG@10 (BRIGHT StackExchange, mean of 7 splits)', 'BRIGHT StackExchange, 7 splits x 101 queries (mean, no CI)') fig.suptitle(f'{k}{" (left) / BRIGHT nDCG@10 (right)" if two else ""} by number of training pairs\nQwen3-Embedding-0.6B fine-tuned on our data, best checkpoint', fontsize=9, color=INK, x=0.01, ha='left', linespacing=1.3) fig.tight_layout(); fig.savefig(OUT / 'graphs' / f"scaling_{k.replace('@', '').lower()}.png", facecolor=SURF); plt.close(fig) # 2026-10-08 (user): BRIGHT R@5 as its own bar graph below the R@5 graph (same runs, best checkpoint by BRIGHT R@5, macro mean of 7 splits) for r, *_ in SC: n, m = max(BR_MS[r], key=lambda t: BR[t[1]]['R@5']); best[('bright_r5', r)] = (n, BR[m]['R@5'], None, None) fig, ax = plt.subplots(figsize=(5.6, 4.6), dpi=150); fig.patch.set_facecolor(SURF) bars(ax, [best[('bright_r5', r)] for r, *_ in SC], BR['qwen06b']['R@5'], 'R@5 (BRIGHT StackExchange, mean of 7 splits)', 'BRIGHT StackExchange, 7 splits x 101 queries (mean, no CI)') fig.suptitle('BRIGHT R@5 by number of training pairs\nQwen3-Embedding-0.6B fine-tuned on our data, best checkpoint', fontsize=9, color=INK, x=0.01, ha='left', linespacing=1.3) fig.tight_layout(); fig.savefig(OUT / 'graphs' / 'scaling_bright_r5.png', facecolor=SURF); plt.close(fig) # 2026-10-08 (user): AnaloBench bars for the three runs. Max 1024 tokens, mean of S1/S10/S30 (results/eval.json m1024.mean; no CI for the mean), # left nDCG@10 (AnaloBench T2 main metric here), right R@5. step-1 = qwen06b_ft encoded with its saved training prompt (as BRIGHT / our eval # set); the 'Query:' encoding (qwen06b_ft_qp) is only in the graph.md table. Best of the evaluated checkpoints per metric. AB_MS = {'step1': [(40, 'qwen06b_ft40'), (210, 'qwen06b_ft210')], 'ours2500': BR_MS['ours2500'], 'ours6k': BR_MS['ours6k']} AM = ab['m1024']['mean'] fig, axs = plt.subplots(1, 2, figsize=(9.6, 4.6), dpi=150); fig.patch.set_facecolor(SURF) for ax, kk in zip(axs, ('nDCG@10', 'R@5')): for r, *_ in SC: n, m = max(AB_MS[r], key=lambda t: AM[t[1]][kk]); best[('ab', kk, r)] = (n, AM[m][kk], None, None) bars(ax, [best[('ab', kk, r)] for r, *_ in SC], AM['qwen06b'][kk], f'{kk} (AnaloBench, mean of S1/S10/S30)', f'AnaloBench T2 {kk}, max 1024 tokens (mean, no CI)') fig.suptitle('AnaloBench nDCG@10 (left) / R@5 (right) by number of training pairs\nQwen3-Embedding-0.6B fine-tuned on our data, best checkpoint', fontsize=9, color=INK, x=0.01, ha='left', linespacing=1.3) fig.tight_layout(); fig.savefig(OUT / 'graphs' / 'scaling_analobench.png', facecolor=SURF); plt.close(fig) at = lambda r, s: next(v for st, v in tl[r]['train'] if st == s) # 2026-10-08 (user): train loss over each whole run (not clipped), the three runs as three lines in one graph; marker + value = each run's last step fig, ax = plt.subplots(figsize=(9, 4.8), dpi=150); fig.patch.set_facecolor(SURF); ax.set_facecolor(SURF); per = [] for r, lab, c, mk, lw, _ in SC: x, y = zip(*tl[r]['train']); sm = [statistics.mean(y[max(0, i - 2):i + 3]) for i in range(len(y))] ax.plot(x, y, color=c, linewidth=0.7, alpha=0.35, zorder=2); ax.plot(x, sm, color=c, linewidth=lw, label=f'{lab}, {x[-1]} steps', zorder=3) ax.plot([x[-1]], [sm[-1]], marker=mk, markersize=4 + lw, color=c, markeredgecolor=SURF, zorder=4) per.append((lab, x[-1], y[0], y[-1])) ax.set_xticks([0, 100, 210, 300, 375, 500, 600, 700, 815]); ax.set_xlim(0, XMAX); ax.set_ylim(0, None) ax.tick_params(labelsize=7, colors=INK2, length=0); ax.set_xlabel('training step (32 queries / step, same recipe, 5 epochs each)', fontsize=8, color=INK2) ax.set_ylabel('train loss (InfoNCE)', fontsize=8, color=INK2); ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True); ax.spines['bottom'].set_color(GRID) for sp in ('top', 'right', 'left'): ax.spines[sp].set_visible(False) box(ax, 'train loss: step 1 -> last step', [(r, f"{tl[r]['train'][0][1]:.2f} -> {tl[r]['train'][-1][1]:.3f} (step {tl[r]['train'][-1][0]})") for r, *_ in SC[::-1]], 0.5, 0.9) ax.set_title('thin = logged every 5 steps, thick = mean of 5 logs; each line runs to its last step', fontsize=8, color=INK2, loc='left') fig.suptitle('Train loss over the whole run by data size / Qwen3-Embedding-0.6B fine-tuned on our data', fontsize=9, color=INK, x=0.01, ha='left') h, l = ax.get_legend_handles_labels(); fig.legend(h, l, fontsize=7.5, frameon=False, ncol=3, loc='lower center', handlelength=3, columnspacing=1.6) fig.tight_layout(rect=(0, 0.07, 1, 1)); fig.savefig(OUT / 'graphs' / 'train_loss_all.png', facecolor=SURF); plt.close(fig) scal = ['### 학습 데이터 수별 비교 (우리 데이터로 학습한 Qwen3-Embedding-0.6B 3개 run)', '', '같은 레시피(32 query/step, lr 6e-6 cosine, 5 epoch, hard negative 9)로 우리 데이터만 바꿔 학습한 run 3개: step-1 **1,389쌍**, ours-2500 **2,506쌍**, ours-6k **5,469쌍**.', '색이 진할수록 데이터가 많다. 평가는 우리 평가셋 190쌍(위와 같은 HF `dangerousmanbyeonggeonlee/ours-test-190`).', 'loss는 `experiments/data_scaling/train_loss.json`(`extract_loss.py`: step-1은 HF ckpt210의 `trainer_state.json`, 나머지는 각 run의 `logging.jsonl`).', '', '#### 그래프 1: 평가 점수 (우리 평가셋 190쌍, R@1 · R@5 · R@10)', '', '가로축 = 학습 데이터 수, 막대 = run마다 평가한 checkpoint 중 그 지표에서 가장 높은 값(막대 아래 step), 오차 막대 = query bootstrap 95% CI. 우리 평가셋은 main pool(151개).', 'R@5 그래프 오른쪽 = BRIGHT StackExchange nDCG@10(BRIGHT 공식 지표, 7 split × 101 query 평균, split corpus 전체 검색; 평균이라 CI 없음, split별 CI는 README).', '평가한 checkpoint: 1,389쌍 40·210, 2,506쌍 40·140·200·375, 5,469쌍 40·140·200·310·380·500·600·700·815(BRIGHT도 같음). 점선 = fine-tuning 전 0.6B.', ''] for k in ('R@1', 'R@5', 'R@10'): f = f"scaling_{k.replace('@', '').lower()}.png" scal += [f'**{k}**' + (' + BRIGHT nDCG@10' if k == 'R@5' else ''), '', f'![{k}](graphs/{f})', '', '| 학습 데이터 | 우리 평가셋 ' + k + ' (step) [95% CI]' + (' | BRIGHT nDCG@10 (step) |' if k == 'R@5' else ' |'), '|---|---|' + ('---|' if k == 'R@5' else '')] scal += [f'| {lab} | {best[(k, r)][1]:.3f} ({best[(k, r)][0]}) [{best[(k, r)][2]:.3f}, {best[(k, r)][3]:.3f}]' + (f" | {best[('bright', r)][1]:.3f} ({best[('bright', r)][0]}) |" if k == 'R@5' else ' |') for r, lab, *_ in SC] scal += [f"| fine-tuning 전 (참고) | {M['qwen06b'][k][0]:.3f}" + (f" | {BR['qwen06b']['nDCG@10']:.3f} |" if k == 'R@5' else ' |'), ''] if k == 'R@5': scal += ['**BRIGHT R@5**', '', '![BRIGHT R@5](graphs/scaling_bright_r5.png)', '', '| 학습 데이터 | BRIGHT R@5 (step) |', '|---|---|'] scal += [f"| {lab} | {best[('bright_r5', r)][1]:.3f} ({best[('bright_r5', r)][0]}) |" for r, lab, *_ in SC] + [f"| fine-tuning 전 (참고) | {BR['qwen06b']['R@5']:.3f} |", ''] qp = lambda kk: max(AM[m][kk] for m in ('qwen06b_ft40_qp', 'qwen06b_ft210_qp')) scal += ['**AnaloBench** (`jhu-clsp/AnaloBench` T2: 질의마다 200개 story bank 검색, 최대 1024 token, S1·S10·S30 평균; 평균이라 CI 없음)', '', '![AnaloBench](graphs/scaling_analobench.png)', '', '1,389쌍(step-1)은 checkpoint에 저장된 학습 지시문을 query prompt로 썼다(BRIGHT·우리 평가셋과 같음; 나머지 두 run은 학습 때와 같은 `Query:`). 표의 괄호 = 같은 checkpoint를 `Query:`로 인코딩한 값(참고).', '', '| 학습 데이터 | nDCG@10 (step) | R@5 (step) |', '|---|---|---|'] scal += [f"| {lab} | {best[('ab', 'nDCG@10', r)][1]:.3f} ({best[('ab', 'nDCG@10', r)][0]})" + (f" (`Query:` {qp('nDCG@10'):.3f})" if r == 'step1' else '') + f" | {best[('ab', 'R@5', r)][1]:.3f} ({best[('ab', 'R@5', r)][0]})" + (f" (`Query:` {qp('R@5'):.3f})" if r == 'step1' else '') + ' |' for r, lab, *_ in SC] scal += [f"| fine-tuning 전 (참고) | {AM['qwen06b']['nDCG@10']:.3f} | {AM['qwen06b']['R@5']:.3f} |", ''] scal += [ '#### 그래프 2: train loss (전체 step)', '', '각 run을 처음부터 끝까지(5 epoch: 210 / 375 / 815 step) 한 그래프에. 가는 선 = 5 step마다 기록된 값, 굵은 선 = 5개 이동평균, 끝의 마커 = 마지막 step(값은 상자).', '', '![train loss all](graphs/train_loss_all.png)', '', '| 학습 데이터 | 전체 step | train loss step 1 / 100 / 200 / 375 / 500 / 700 / 마지막 |', '|---|---|---|'] g = lambda r, n: f'{at(r, n):.3f}' if n <= tl[r]['train'][-1][0] else '—' scal += [f"| {lab} | {tl[r]['train'][-1][0]} | {' / '.join(g(r, n) for n in (1, 100, 200, 375, 500, 700))} / {tl[r]['train'][-1][1]:.3f} |" for r, lab, *_ in SC] scal += [''] scal += ['읽을 때 주의:', '- 세 run 모두 끝까지 train loss가 내려가고, 5,469쌍 run은 epoch마다 한 단계씩 내려가 step 700 무렵 0.07 안팎에 이르고(그 뒤는 거의 평평), 세 run 중 가장 낮은 값(0.068)에서 끝난다. 같은 step에서는 데이터가 많을수록 높다(같은 문장을 덜 반복해서 봄).', '- 그래프 1의 막대는 지표마다 따로 고른 최고 checkpoint다(평가셋에서 고름, 지표마다 step이 다를 수 있음). run마다 평가한 checkpoint 수가 다르다(2 / 4 / 9개).', '- AnaloBench도 데이터 수 순서가 아니다: 2,506쌍(nDCG@10 0.439) > 5,469쌍(0.422) > 1,389쌍(0.348, `Query:`로 인코딩하면 0.417). 1,389쌍만 학습 prompt가 달라 직접 비교가 어렵다.', '- BRIGHT nDCG@10은 데이터 수 순서가 아니다: 1,389쌍 0.194(step 40) > 5,469쌍 0.178(step 40) > 2,506쌍 0.173(step 40). 세 run 모두 step 40이 최고이고 그 뒤로 떨어진다(README BRIGHT 절).', '- step-1 checkpoint는 query prompt가 학습 지시문, 나머지 둘은 `Query:`이다. 세 데이터는 생성 시점이 다른 우리 데이터 버전이다(데이터 수 말고도 다른 점).', '- 190 query라 CI가 넓다(오차 막대). 우리 평가셋 R@1은 1,389쌍(0.242)이 2,506쌍(0.221)보다 조금 높고, R@5·R@10은 데이터 수 순서대로 오른다.', ''] i = md.index(next(x for x in md if x.startswith('### BRIGHT'))); md[i:i] = scal # 2026-10-08 (user): the 8 ablation runs (4 training datasets x with / without hard negatives, 2,506 pairs each) as bars, one bar per run = # its best evaluated checkpoint (40/140/200/375), one graph per benchmark: BRIGHT StackExchange nDCG@10 (macro of the finished splits, as the # line graph) and AnaloBench nDCG@10 (max 1024 tokens, mean of S1/S10/S30). Colour = data, hatched light bar = no hard negatives. if AB.exists(): AM8 = ab['m1024']['mean'] B0 = mac('qwen06b') # BRIGHT before ft (the name base is reused by the later sections) BEST8 = {'bright': {r: max(((n, mac(f'abl_{r}_c{n}')) for n in STEPS), key=lambda t: t[1]) for r in runs}, 'ab': {r: max(((n, AM8[f'abl_{r}_c{n}']['nDCG@10']) for n in STEPS), key=lambda t: t[1]) for r in runs}} B8 = [('bright', 'bright_best.png', f'nDCG@10 (BRIGHT StackExchange, mean of {len(S)} splits)', f'BRIGHT StackExchange, {len(S)} splits x 101 queries', B0), ('ab', 'analobench_best.png', 'nDCG@10 (AnaloBench, mean of S1/S10/S30)', 'AnaloBench T2, max 1024 tokens', AM8['qwen06b']['nDCG@10'])] order = [(d, c, nohn) for d, c, _ in DATA for nohn in (False, True)] for key, f, ylab, title, b0 in B8: fig, ax = plt.subplots(figsize=(8.4, 4.6), dpi=150); fig.patch.set_facecolor(SURF); ax.set_facecolor(SURF); top = 0 for i, (d, c, nohn) in enumerate(order): r = d + ('_nohn' if nohn else ''); n, y = BEST8[key][r]; x = i + (i // 2) * 0.5; top = max(top, y) ax.bar(x, y, width=0.8, color=SURF if nohn else c, edgecolor=c, hatch='///' if nohn else None, linewidth=1.5, zorder=3) ax.text(x, y + 0.004, f'{y:.3f}', ha='center', va='bottom', fontsize=8, color=INK, fontweight='bold' if d == 'ours' else 'normal') ax.text(x, 0.006, f'step {n}', ha='center', va='bottom', fontsize=6.5, color=INK if nohn else SURF, zorder=5, bbox=dict(facecolor=SURF, edgecolor='none', pad=0.6) if nohn else None) xs = [i + (i // 2) * 0.5 for i in range(len(order))] ax.set_xticks(xs); ax.set_xticklabels([LBL.get(d, d) + ('\nno hard neg' if nohn else '\nhard neg') for d, _, nohn in order], fontsize=7, color=INK) ax.axhline(b0, color=INK2, linewidth=1, linestyle=(0, (1, 2)), zorder=2) ax.text(xs[-1] + 0.6, b0, f'before ft\n{b0:.3f}', color=INK2, fontsize=6.5, va='center', ha='left', linespacing=1.1) ax.set_xlim(-0.6, xs[-1] + 1.5); ax.set_ylim(0, max(top, b0) * 1.15); ax.set_ylabel(ylab, fontsize=8, color=INK2) ax.tick_params(axis='y', labelsize=7, colors=INK2, length=0); ax.tick_params(axis='x', length=0) ax.grid(axis='y', color=GRID, linewidth=0.8); ax.set_axisbelow(True); ax.spines['bottom'].set_color(GRID) for sp in ('top', 'right', 'left'): ax.spines[sp].set_visible(False) ax.set_title(f'{title} (mean, no CI); bar = best of checkpoints 40/140/200/375, step below', fontsize=8, color=INK2, loc='left') fig.suptitle(f"{'BRIGHT' if key == 'bright' else 'AnaloBench'} nDCG@10 by training data (2,506 pairs each) / Qwen3-Embedding-0.6B, best checkpoint", fontsize=9, color=INK, x=0.01, ha='left') fig.tight_layout(); fig.savefig(OUT / 'graphs' / f, facecolor=SURF); plt.close(fig) sec = ['### 학습 데이터별 최고 점수 (ablation 8개 run, 막대그래프)', '', '학습 데이터 4종(ours-2500 / msmarco / reasonir / specter, 모두 2,506쌍) × hard negative 있음/없음 = 8개 run. 막대 하나 = run 하나,', '값 = 평가한 checkpoint(40·140·200·375) 중 그 벤치마크에서 가장 높은 점수(막대 아래 step). 색 = 데이터, 빗금 = hard negative 없음, 점선 = fine-tuning 전 0.6B.', '지표는 둘 다 nDCG@10: BRIGHT = StackExchange 7 split × 101 query 평균, AnaloBench = T2 최대 1024 token, S1·S10·S30 평균(평균이라 CI 없음).', 'checkpoint를 평가셋 점수로 고른 값이라 낙관적이다. reasonir hq 정답은 BRIGHT 문서라 BRIGHT에 누수가 있다(README ablation 주의).', '', '![BRIGHT best](graphs/bright_best.png)', '', '![AnaloBench best](graphs/analobench_best.png)', '', '| 학습 데이터 | hard negative | BRIGHT nDCG@10 (step) | AnaloBench nDCG@10 (step) |', '|---|---|---|---|'] sec += [f"| {LBL.get(d, d)} | {'없음' if nohn else '있음'} | {BEST8['bright'][r][1]:.3f} ({BEST8['bright'][r][0]}) | {BEST8['ab'][r][1]:.3f} ({BEST8['ab'][r][0]}) |" for d, _, nohn in order for r in [d + ('_nohn' if nohn else '')]] sec += [f"| fine-tuning 전 (참고) | | {B0:.3f} | {AM8['qwen06b']['nDCG@10']:.3f} |", ''] i = md.index(next(x for x in md if x.startswith('### BRIGHT'))); md[i:i] = sec (OUT / 'graph.md').write_text('\n'.join(md) + '\n'); print('splits', list(S))