abidlabs's picture
download
raw
7.97 kB
#!/usr/bin/env python3
"""E2: OVOBench caption-memory ablation with OneStreamer-4B — memory vs recent16.
Mirrors Eval/Proactive_Eval/OneStreamer/src/onestreamer/local_runner.py `infer`
verbatim for the ovobench flow: memory setting streams the chunk video through
load_or_create_caption (4 fps, 1 update/s) and answers with hierarchical memory
rendered under a 12000-token budget; recent16 answers with mode='none' memory
and the last 16 recent frames at 1 fps. Scoring uses their score_prediction.
Env:
ONESTREAMER_MODEL (required) path to the OneStreamer-4B checkpoint dir
ONESTREAMER_REPO default /work/OneStreamer
E2_VIDEO_ROOT default /work/videos/chunked
E2_SUBSET default /work/e2_subset.json
E2_OUT default /work/out
TRACKIO_SPACE_ID optional; logs progress/accuracy if set
recent16 runs first (cheap) so partial results survive a timeout; both settings
resume from their JSONL.
"""
import json
import os
import sys
import time
from pathlib import Path
REPO = Path(os.environ.get('ONESTREAMER_REPO', '/work/OneStreamer'))
MODEL = os.environ['ONESTREAMER_MODEL']
VIDEO_ROOT = Path(os.environ.get('E2_VIDEO_ROOT', '/work/videos/chunked'))
SUBSET = Path(os.environ.get('E2_SUBSET', '/work/e2_subset.json'))
OUT = Path(os.environ.get('E2_OUT', '/work/out'))
SETTINGS = ('recent16', 'memory')
sys.path.insert(0, str(REPO / 'Eval' / 'VLMEvalKit'))
sys.path.insert(0, str(REPO / 'Eval' / 'Proactive_Eval'))
sys.path.insert(0, str(REPO / 'Eval' / 'Proactive_Eval' / 'OneStreamer' / 'src'))
import torch # noqa: E402
from onestreamer.engine import OneStreamerEngine # noqa: E402
from onestreamer.schema import ExperimentConfig, Sample # noqa: E402
from onestreamer.cache import load_or_create_caption # noqa: E402
from onestreamer.memory import MemoryBank, MemoryEvent # noqa: E402
from onestreamer.video import read_recent_frames # noqa: E402
from onestreamer.prompts import MEMORY_QA_SYSTEM, MEMORY_DIRECT_QA_SYSTEM # noqa: E402
from onestreamer.ovobench import build_question_text, score_prediction # noqa: E402
def main():
rows = json.loads(SUBSET.read_text())['samples']
protocol = json.loads(
(REPO / 'Eval' / 'Proactive_Eval' / 'OneStreamer' / 'configs' / 'ovobench.json').read_text())
config = ExperimentConfig(
path=REPO / 'Eval' / 'Proactive_Eval' / 'OneStreamer' / 'configs' / 'ovobench.json',
models={'onestreamer-4b': MODEL},
video_root=VIDEO_ROOT, samples_path=SUBSET,
cache_root=OUT / 'memory',
caption=protocol['caption'], answer=protocol['answer'], variants=())
model_alias = 'onestreamer-4b'
engine = OneStreamerEngine(
model_path=MODEL, dtype='bfloat16',
attn_implementation='flash_attention_2', min_pixels=3136, max_pixels=100352)
OUT.mkdir(parents=True, exist_ok=True)
done = set()
handles = {}
for setting in SETTINGS:
path = OUT / f'e2_predictions_{setting}.jsonl'
if path.exists():
for line in path.open():
if line.strip():
rec = json.loads(line)
if 'hit' in rec: # only real results block re-processing
done.add((rec['sample_id'], rec['setting']))
handles[setting] = path.open('a')
track = None
space_id = os.environ.get('TRACKIO_SPACE_ID')
if space_id:
try:
import trackio
trackio.init(project='onestreamer-e2-ovobench', space_id=space_id)
track = trackio
except Exception as exc:
print(f'[warn] trackio disabled: {exc}', flush=True)
totals = {}
n = 0
for sample_dict in rows:
n += 1
sample = Sample.from_dict(sample_dict)
video = VIDEO_ROOT / sample.video
for setting in SETTINGS:
if (sample.sample_id, setting) in done:
continue
if not video.is_file():
rec = dict(sample_dict, setting=setting, error='video_missing')
handles[setting].write(json.dumps(rec) + '\n')
handles[setting].flush()
continue
memory = setting == 'memory'
caption_data = {'events': [], 'counts': {}}
cache_path = None
t_caption = time.monotonic()
if memory:
caption_data, _, cache_path = load_or_create_caption(
engine=engine, config=config, model_alias=model_alias,
sample=sample, video_path=video, allow_create=True)
bank = MemoryBank(MemoryEvent.from_dict(e) for e in caption_data['events'])
mode = 'hierarchical' if memory else 'none'
text, meta = bank.render_with_budget(
mode=mode, question=sample.question,
tokenizer=engine.processor.tokenizer, max_tokens=12000)
frames = read_recent_frames(
video, sample.start, sample.end, recent_frames=16, sample_fps=1.0)
t_answer = time.monotonic()
prediction = engine.answer(
system=MEMORY_QA_SYSTEM if sample.eval_mode == 'mcq_letter'
else MEMORY_DIRECT_QA_SYSTEM,
memory_text=text, recent_frames=frames,
question_text=build_question_text(sample),
max_tokens=16, recent_resize_policy='source_pixels')
parsed, hit = score_prediction(sample, prediction)
rec = dict(sample_dict, setting=setting,
variant=f'r16_fps1_source_{mode}',
prediction=prediction, parsed_output=parsed, hit=hit,
memory_events=len(caption_data['events']),
caption_cache=str(cache_path) if cache_path else None,
caption_seconds=round(time.monotonic() - t_caption, 1),
answer_seconds=round(time.monotonic() - t_answer, 1),
**engine.last_input_metrics)
handles[setting].write(json.dumps(rec) + '\n')
handles[setting].flush()
stats = totals.setdefault(setting, {'n': 0, 'hit': 0})
stats['n'] += 1
stats['hit'] += int(hit)
print(f"[{n}/{len(rows)} {setting}] {sample.task} {sample.sample_id} "
f"pred={parsed or '-'} hit={hit} cap={rec['caption_seconds']}s "
f"ans={rec['answer_seconds']}s "
f"acc={stats['hit'] / max(1, stats['n']):.3f}", flush=True)
if track is not None:
try:
track.log({'progress': n / len(rows),
f'acc_{setting}': stats['hit'] / max(1, stats['n'])},
step=n)
except Exception:
pass
for handle in handles.values():
handle.close()
summary = {'per_setting': {}, 'per_task': {}}
for setting in SETTINGS:
path = OUT / f'e2_predictions_{setting}.jsonl'
recs = []
if path.exists():
recs = [json.loads(l) for l in path.open() if l.strip() and 'hit' in json.loads(l)]
per_task = {}
for r in recs:
per_task.setdefault(r['task'], []).append(r['hit'])
summary['per_setting'][setting] = {
'n': len(recs),
'accuracy': sum(r['hit'] for r in recs) / max(1, len(recs)),
}
summary['per_task'][setting] = {
t: {'n': len(v), 'accuracy': sum(v) / len(v)}
for t, v in sorted(per_task.items())}
(OUT / 'e2_summary.json').write_text(json.dumps(summary, indent=1))
print(json.dumps(summary, indent=1), flush=True)
if not any(s['n'] for s in summary['per_setting'].values()):
raise SystemExit('E2 FAILED: zero predictions were produced - check staging/video paths')
if track is not None:
try:
track.finish()
except Exception:
pass
if __name__ == '__main__':
main()

Xet Storage Details

Size:
7.97 kB
·
Xet hash:
c318f1ed7c545ce6a25d127bfc221425951ca677e6cbdd1c9a1393aec6faedb9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.