OutOfSightOutOfPlace / code /paper /scripts /make_figures.py
Giulio Trovato
Upload OutOfSightOutOfPlace
c6a1af0 verified
Raw History Blame Contribute Delete
18.2 kB
#!/usr/bin/env python3
"""Figures and auto-generated tables for the paper (run from the repo root through Slurm: paper/scripts/make_figures.slurm).
Reads the set-size two-video runs (occlusion_memory_benchmark/memory_v2/dataset_sizes/vlm_runs/pairs-vllm-<model>, all
models scored with vLLM, fp32 output layer, next-token scoring), the 1-object wording runs (k1places-vllm-<model>), one
layout file and three videos of the set-size dataset. Writes PDFs to paper/figures/ and LaTeX tables to paper/tables/.
Per pair of videos (one question, the same two videos in both orders): g = log P("Video 1") - log P("Video 2") in each
order; bias b = (g_A + g_B) / 2; signal s = (g_A - g_B) / 2 signed so that s > 0 points to the changed video.
Right in both orders <=> s > |b|. "Scores point right" <=> s > 0.
"""
import collections
import json
import re
import subprocess
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
M2 = Path('occlusion_memory_benchmark/memory_v2')
RUNS = M2 / 'dataset_sizes' / 'vlm_runs'
FIG, TAB = Path('paper/figures'), Path('paper/tables')
FFMPEG = '.local/video/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2'
FAMILIES = {
'Qwen3-VL': [('2B', 'qwen3_vl_2b'), ('8B', 'qwen3_vl_8b'), ('30B-A3B', 'qwen3_vl_30b_a3b'), ('32B', 'qwen3_vl_32b')],
'InternVL3.5': [('2B', 'internvl35_2b'), ('8B', 'internvl35_8b'), ('38B', 'internvl35_38b')],
}
# ordinal blue ramp (dataviz reference palette, steps 250 -> 700): model size within a family, light = small
# model-size colours (dataviz reference blue ramp, steps 250 -> 700) are set in fig_sizes
INK, INK2, MUTED, GRID = '#0b0b0b', '#52514e', '#8a8984', '#e4e3df'
ORANGE, BLUE = '#eb6834', '#2a78d6'
# AAAI-27 page: column 3.3125in, text width 7in; text inside figures must be at least 9pt at the printed size.
# Every figure is drawn at its printed width (COL or TEXT), so the font sizes below are the printed sizes.
COL, TEXT, FS = 3.3125, 7.0, 9
plt.rcParams.update({'font.family': 'serif', 'font.serif': ['STIXGeneral'], 'mathtext.fontset': 'stix',
'font.size': FS, 'axes.titlesize': FS, 'axes.labelsize': FS, 'xtick.labelsize': FS,
'ytick.labelsize': FS, 'legend.fontsize': FS, 'legend.title_fontsize': FS,
'axes.edgecolor': MUTED, 'axes.labelcolor': INK2, 'xtick.color': INK2, 'ytick.color': INK2,
'axes.linewidth': 0.6, 'xtick.major.width': 0.6, 'ytick.major.width': 0.6, 'pdf.fonttype': 42})
def pairs(tag):
"""{(question, blocks, k): [(b, s), ...]} for one run."""
g = collections.defaultdict(list)
for line in open(RUNS / tag / 'pairs.jsonl'):
r = json.loads(line)
key = (int(r['layout'][1]), r['occluders'], r['timing'], r['path'], r['history'], r['property'], tuple(sorted(r['videos'])))
for a in r['answers']:
s = {c: x['sum'] for c, x in zip(a['candidates'], a['scores'])}
g[key + (a['q'],)].append((s['Video 1'] - s['Video 2'], a['truth']))
out = collections.defaultdict(list)
for k, d in g.items():
if len(d) != 2:
continue
(g1, t1), (g2, t2) = d
out[(k[-1], k[1], k[0])].append(((g1 + g2) / 2, ((g1 if t1 == 'Video 1' else -g1) + (g2 if t2 == 'Video 1' else -g2)) / 2))
return out
def both(v):
return 100 * np.mean([s > abs(b) for b, s in v])
def points(v):
return 100 * np.mean([s > 0 for b, s in v])
def save(fig, name, width, **kw):
"""PDF for the paper, PNG preview in .scratch/paper_preview for checking the layout. Prints the PDF size and the
scale LaTeX applies to fit it to `width` (in inches), i.e. by how much the 9pt text shrinks or grows in print."""
fig.savefig(FIG / f'{name}.pdf', bbox_inches='tight', pad_inches=0.02, **kw)
Path('.scratch/paper_preview').mkdir(parents=True, exist_ok=True)
fig.savefig(f'.scratch/paper_preview/{name}.png', bbox_inches='tight', pad_inches=0.02, dpi=150); plt.close(fig)
box = [float(x) for x in re.search(rb'/MediaBox \[([^\]]+)\]', (FIG / f'{name}.pdf').read_bytes()).group(1).split()]
w, h = (box[2] - box[0]) / 72, (box[3] - box[1]) / 72
print(f'{name}.pdf: {w:.2f} x {h:.2f} in, printed at {width:.2f} in wide: scale {width / w:.3f}, '
f'{FS}pt text prints at {FS * width / w:.1f}pt', flush=True)
def style(ax):
ax.spines[['top', 'right']].set_visible(False)
ax.grid(axis='y', color=GRID, linewidth=0.5); ax.set_axisbelow(True)
def fig_sizes(data):
"""Right in both orders vs number of objects, one column wide: rows = change x block setting, columns = families."""
# Left margin kept small: one two-line row label (rotated) plus the tick numbers; the y quantity is named in the
# caption. One legend for both families: the same colour means the same size class in both columns, and the
# mixture-of-experts model gets its own marker.
rows = [('colors', 'on', 'colours\nhidden'), ('places', 'on', 'places\nhidden'),
('colors', 'off', 'colours\nvisible'), ('places', 'off', 'places\nvisible')]
size_style = {'2B': ('#86b6ef', 'o'), '8B': ('#3987e5', 'o'), '30B-A3B': ('#1c5cab', 'D'),
'32B': ('#0d366b', 'o'), '38B': ('#0d366b', 'o')}
fig, axes = plt.subplots(4, 2, figsize=(COL - 0.1, 4.0), sharex=True, sharey=True)
fig.subplots_adjust(left=0.135, right=0.995, bottom=0.085, top=0.905, wspace=0.12, hspace=0.18)
for c, (fam, models) in enumerate(FAMILIES.items()):
for r, (q, occ, label) in enumerate(rows):
ax = axes[r, c]; style(ax)
ax.axhline(25, color=MUTED, linewidth=0.8, linestyle=(0, (3, 2)))
for size, tag in models:
col, mk = size_style[size]
y = [both(data[tag][(q, occ, k)]) for k in range(1, 6)]
ax.plot(range(1, 6), y, color=col, linewidth=1.3, marker=mk, markersize=3.4 if mk == 'o' else 3.0,
markeredgecolor='white', markeredgewidth=0.5)
ax.set_ylim(-6, 106); ax.set_xlim(0.7, 5.3); ax.set_xticks(range(1, 6)); ax.set_yticks([0, 50, 100])
ax.set_yticks([25, 75], minor=True); ax.tick_params(axis='y', which='minor', length=0)
ax.tick_params(axis='both', length=2.5, pad=1.5)
ax.grid(axis='y', which='minor', color=GRID, linewidth=0.5)
if c == 0:
ax.set_ylabel(label, color=INK, labelpad=2, linespacing=1.0)
axes[0, c].set_title(fam, color=INK, pad=3)
axes[-1, c].set_xlabel('number of objects', labelpad=1)
handles = [plt.Line2D([], [], color=size_style[s][0], marker=size_style[s][1], linewidth=1.3,
markersize=3.4 if size_style[s][1] == 'o' else 3.0, markeredgecolor='white',
markeredgewidth=0.5) for s in ('2B', '8B', '30B-A3B', '32B')]
fig.legend(handles, ['2B', '8B', '30B-A3B', '32B / 38B'], ncol=4, frameon=False, loc='upper center',
bbox_to_anchor=(0.565, 1.0), handlelength=1.4, columnspacing=0.9, handletextpad=0.35,
borderaxespad=0.0, borderpad=0.0)
save(fig, 'fig_sizes', COL)
def fig_scores_vs_answers(data):
"""Pooled over 1-5 objects, hidden (blocks on): answer right in both orders vs scores pointing right. One column."""
rows = [(f'{fam} {size}', tag) for fam, models in FAMILIES.items() for size, tag in models]
fig, axes = plt.subplots(1, 2, figsize=(COL, 2.2), sharey=True)
for ax, (q, title) in zip(axes, [('colors', 'colours, hidden'), ('places', 'places, hidden')]):
style(ax); ax.grid(axis='y', visible=False); ax.grid(axis='x', which='both', color=GRID, linewidth=0.5)
for i, (name, tag) in enumerate(rows):
v = [x for k in range(1, 6) for x in data[tag][(q, 'on', k)]]
a, p = both(v), points(v)
ax.plot([a, p], [i, i], color=GRID, linewidth=2.0, solid_capstyle='round', zorder=1)
ax.scatter([a], [i], s=20, marker='o', color=ORANGE, edgecolor='white', linewidth=0.5, zorder=3,
label='answers: right in both orders' if i == 0 else None)
ax.scatter([p], [i], s=20, marker='D', color=BLUE, edgecolor='white', linewidth=0.5, zorder=3,
label='scores: point to the changed video' if i == 0 else None)
ax.axvline(25, color=ORANGE, linewidth=0.7, linestyle=(0, (3, 2)), alpha=0.8)
ax.axvline(50, color=BLUE, linewidth=0.7, linestyle=(0, (3, 2)), alpha=0.8)
ax.set_xlim(-4, 104); ax.set_xticks([0, 50, 100]); ax.set_xticks([25, 75], minor=True)
ax.tick_params(axis='x', which='minor', length=0)
ax.set_title(title, color=INK, pad=3); ax.set_xlabel('% of 120 pairs', labelpad=2)
# shared y axis: set the labels and invert once (inverting each shared axis would undo it)
axes[0].set_yticks(range(len(rows))); axes[0].set_yticklabels([r[0] for r in rows]); axes[0].invert_yaxis()
axes[0].tick_params(axis='y', length=0)
h, l = axes[0].get_legend_handles_labels()
fig.legend(h, l, loc='lower center', bbox_to_anchor=(0.5, 1.0), ncol=1, frameon=False, handletextpad=0.3,
borderaxespad=0.0)
fig.tight_layout(w_pad=0.8)
save(fig, 'fig_scores_vs_answers', COL)
def decode(path):
raw = subprocess.run([FFMPEG, '-hide_banner', '-loglevel', 'error', '-i', str(path), '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'],
check=True, capture_output=True).stdout
return np.frombuffer(raw, np.uint8).reshape(-1, 512, 512, 3)
def draw_frames(axes, rows, frames, base):
for r, (name, stem) in enumerate(rows):
v = decode(base / f'{stem}.mp4')
for c, t in enumerate(frames):
ax = axes[r][c]; ax.imshow(v[t][200:440]); ax.set_xticks([]); ax.set_yticks([])
for sp in ax.spines.values():
sp.set_edgecolor(MUTED); sp.set_linewidth(0.5)
if r == 0:
ax.set_title(f'frame {t}' + (' (hidden)' if t == 31 else ''), color=INK, pad=3)
if c == 0:
ax.set_ylabel(name, color=INK, labelpad=3)
def draw_scene(ax):
"""Top view of the s3_wide layout: objects, grey blocks and the two camera paths."""
lay = json.loads((M2 / 'layouts_sizes_k5' / 's3_wide.json').read_text())
D, deg, L = lay['D'], lay['orbit_deg'], lay['translation']['L']
ax.set_aspect('equal')
a = np.radians(np.linspace(-deg, deg, 100))
ax.plot(D * np.sin(a), -D * np.cos(a), color='#2a78d6', linewidth=1.5, label=f'orbit (±{deg:.0f}°)')
ax.plot([-L / 2, L / 2], [-D, -D], color='#eb6834', linewidth=1.5, label=f'translation ({L:.0f} units)')
ax.scatter([0], [-D], marker='^', s=40, color=INK, zorder=4, label='hiding pose')
hexes = {'red': '#D91A1A', 'blue': '#1A33D9', 'green': '#1AA626', 'yellow': '#F2D91A', 'purple': '#8C26B3', 'orange': '#F2800D'}
marker = {'cube': 's', 'sphere': 'o', 'cylinder': 'h', 'cone': '^', 'pyramid': 'v', 'torus': 'o'}
for o in lay['occluders']:
ax.add_patch(plt.Rectangle((o['position'][0] - 0.5, o['position'][1] - 0.5), 1, 1, color='#9a9a9a', zorder=2))
i, j = lay['probed_pair']
for n, t in enumerate(lay['targets']):
ax.scatter([t['position'][0]], [t['position'][1]], marker=marker[t['shape']], s=55, color=hexes[t['color']],
edgecolor=INK if n in (i, j) else 'white', linewidth=1.0, zorder=3)
probed = n in (i, j) # probed pair labelled above, other objects to the left (keeps labels apart)
ax.annotate(t['shape'] + (' *' if probed else ''), t['position'][:2], xytext=(0, 6) if probed else (-6, -2),
textcoords='offset points', ha='center' if probed else 'right', color=INK2)
for t in (lay['targets'][i], lay['targets'][j]): # sight lines from the hiding pose
ax.plot([0, t['position'][0]], [-D, t['position'][1]], color=MUTED, linewidth=0.5, linestyle=(0, (2, 2)), zorder=1)
ax.set_xlim(-8.5, 8.5); ax.set_ylim(-11.5, 3.5); ax.set_xticks([]); ax.set_yticks([])
for sp in ax.spines.values():
sp.set_visible(False)
ax.legend(frameon=False, loc='upper center', bbox_to_anchor=(0.5, 0.02), ncol=1, handlelength=1.5,
handletextpad=0.5, labelspacing=0.3, borderaxespad=0.0)
def fig_teaser():
"""Figure 1: (a) top view of one 3-object scene; (b) its orbit videos with the blocks on: the still video and the
two swaps of the probed pair (cube, sphere)."""
base = M2 / 'dataset_sizes' / 'videos' / 's3_wide' / 'normal' / 'orbit' / 'occ_on'
rows = [('still', 'W0_W0'), ('colours\nswapped', 'W0_W1'), ('places\nswapped', 'W0_W2')]
frames = [0, 16, 31, 47, 63]
fig = plt.figure(figsize=(TEXT - 0.06, 2.55)) # labels stick out by ~0.05in: the tight box is then 7in
gs = fig.add_gridspec(3, 6, width_ratios=[1.6, 1, 1, 1, 1, 1], wspace=0.06, hspace=0.08, left=0.0, right=1.0,
top=0.86, bottom=0.04)
sc = fig.add_subplot(gs[:, 0]); draw_scene(sc)
axes = [[fig.add_subplot(gs[r, c + 1]) for c in range(len(frames))] for r in range(len(rows))]
draw_frames(axes, rows, frames, base)
fig.text(0.0, 0.995, '(a) top view', color=INK, ha='left', va='top', fontweight='bold')
x0 = axes[0][0].get_position().x0 - 0.04
fig.text(x0, 0.995, '(b) orbit videos, blocks on', color=INK, ha='left', va='top', fontweight='bold')
save(fig, 'fig_teaser', TEXT, dpi=300)
def fig_scene():
"""Stand-alone top view (no longer in the paper; part (a) of fig_teaser)."""
fig, ax = plt.subplots(figsize=(COL, 3.0)); draw_scene(ax); save(fig, 'fig_scene', COL)
def table_main(data):
"""Pooled over 1-5 objects (120 pairs per cell): right in both orders / scores point right."""
# one column wide (with \tabcolsep=3pt in main text): the family is a group row, the model column holds the size
lines = [r'\begin{tabular}{@{}l rr rr rr rr@{}}', r'\toprule',
r' & \multicolumn{4}{c}{hidden (blocks on)} & \multicolumn{4}{c}{visible (blocks off)} \\',
r'\cmidrule(lr){2-5}\cmidrule(l){6-9}',
r' & \multicolumn{2}{c}{colours} & \multicolumn{2}{c}{places} & \multicolumn{2}{c}{colours} & \multicolumn{2}{c}{places} \\',
r'\cmidrule(lr){2-3}\cmidrule(lr){4-5}\cmidrule(lr){6-7}\cmidrule(l){8-9}',
r'model & ans. & score & ans. & score & ans. & score & ans. & score \\', r'\midrule']
for fam, models in FAMILIES.items():
lines.append(r'\multicolumn{9}{@{}l}{\emph{' + fam + r'}} \\')
for size, tag in models:
cells = []
for occ in ('on', 'off'):
for q in ('colors', 'places'):
v = [x for k in range(1, 6) for x in data[tag][(q, occ, k)]]
cells += [f'{both(v):.1f}', f'{points(v):.1f}']
lines.append(f'{size} & ' + ' & '.join(cells) + r' \\')
lines.append(r'\midrule' if fam == 'Qwen3-VL' else r'\bottomrule')
lines.append(r'\end{tabular}')
(TAB / 'tab_main.tex').write_text('\n'.join(lines) + '\n')
def table_k1():
"""1-object place pairs, per wording: pairs (of 24) right in both orders / pairs whose scores point to the changed video."""
qs = [('places', 'change its place'), ('places_moved', 'moved to a different spot'),
('places_jump', 'suddenly jump'), ('places_endstart', 'different spot end vs start')]
# one column wide (with \tabcolsep=2.5pt in main text): the family is a group row, the model column holds the size
# percentages with one decimal; two rows per model (ans.: right in both orders, score: scores point right), named
# as in Table 1; hidden before visible, as in every other table
lines = [r'\begin{tabular}{@{}ll cccc cccc@{}}', r'\toprule',
r' & & \multicolumn{4}{c}{hidden (blocks on)} & \multicolumn{4}{c}{visible (blocks off)} \\',
r'\cmidrule(lr){3-6}\cmidrule(l){7-10}', r'model & & Q0 & Q1 & Q2 & Q3 & Q0 & Q1 & Q2 & Q3 \\', r'\midrule']
for fam, models in FAMILIES.items():
lines.append(r'\multicolumn{10}{@{}l}{\emph{' + fam + r'}} \\')
for size, tag in models:
g = collections.defaultdict(list)
for line in open(RUNS / f'k1places-vllm-{tag}' / 'pairs.jsonl'):
r = json.loads(line)
for a in r['answers']:
s = {c: x['sum'] for c, x in zip(a['candidates'], a['scores'])}
g[(a['q'], r['occluders'], r['layout'], r['path'], r['history'], tuple(sorted(r['videos'])))].append((s['Video 1'] - s['Video 2'], a['truth']))
cells_a, cells_s = [], []
for occ in ('on', 'off'):
for q, _ in qs:
n = ok = pos = 0
for key, d in g.items():
if key[0] != q or key[1] != occ or len(d) != 2:
continue
(g1, t1), (g2, t2) = d
b = (g1 + g2) / 2; s = ((g1 if t1 == 'Video 1' else -g1) + (g2 if t2 == 'Video 1' else -g2)) / 2
n += 1; ok += s > abs(b); pos += s > 0
cells_a.append(f'{100 * ok / n:.1f}'); cells_s.append(f'{100 * pos / n:.1f}')
lines.append(f'{size} & ans. & ' + ' & '.join(cells_a) + r' \\')
lines.append(r' & score & ' + ' & '.join(cells_s) + r' \\')
lines.append(r'\midrule' if fam == 'Qwen3-VL' else r'\bottomrule')
lines.append(r'\end{tabular}')
(TAB / 'tab_k1_wordings.tex').write_text('\n'.join(lines) + '\n')
def main():
FIG.mkdir(parents=True, exist_ok=True); TAB.mkdir(parents=True, exist_ok=True)
data = {tag: pairs(f'pairs-vllm-{tag}') for models in FAMILIES.values() for _, tag in models}
for tag, d in data.items():
n = sum(len(v) for v in d.values()); print(f'{tag}: {n} pairs', flush=True)
fig_sizes(data); print('wrote fig_sizes.pdf', flush=True)
fig_scores_vs_answers(data); print('wrote fig_scores_vs_answers.pdf', flush=True)
fig_teaser(); print('wrote fig_teaser.pdf', flush=True)
table_main(data); table_k1(); print('wrote tables/tab_main.tex, tables/tab_k1_wordings.tex', flush=True)
if __name__ == '__main__':
main()