Distilled_handvqa / code /sft_handyvqa.py
Joshkn's picture
Add 750 distilled HanDyVQA training samples and provenance
0a24277 verified
Raw History Blame Contribute Delete
20.3 kB
#!/usr/bin/env python3
"""Full-parameter Qwen3-VL SFT for the existing four-round HanDyVQA JSONL.
No model or GPU is needed for --check-data. See --help and the SFT section
in README.md. Optional dependencies are imported only when needed.
"""
import argparse
from collections import Counter, OrderedDict
import hashlib
import json
import math
from pathlib import Path
STAGES = ("recog", "caption", "track", "answer")
def read_data(filename, video_root=None):
source = Path(filename).resolve()
root = Path(video_root).resolve() if video_root else source.parent
rows, seen = [], set()
for line_no, line in enumerate(source.read_text(encoding="utf-8").splitlines(), 1):
if not line.strip():
continue
try:
row = json.loads(line)
for key in ("system", "instruction", "input", "output"):
if not isinstance(row.get(key), str) or not row[key].strip():
raise ValueError(f"{key} must be a nonempty string")
history = row.get("history")
if not isinstance(history, list) or len(history) not in range(4):
raise ValueError("history must contain 0 to 3 pairs")
for pair in history:
if (not isinstance(pair, list) or len(pair) != 2
or any(not isinstance(s, str) or not s.strip() for s in pair)):
raise ValueError("history entries must be two nonempty strings")
stage = STAGES[len(history)]
if stage == "answer":
target = tagged_json(row["output"], "answer")
if (type(target.get("answer")) is not int or target["answer"] < 0
or not isinstance(target.get("report"), str)
or type(target.get("confidence")) not in (int, float)
or not 0 <= target["confidence"] <= 1):
raise ValueError("Invalid accepted answer target")
else:
target = tagged_json(row["output"], "tool")
if target.get("name") != stage or not isinstance(target.get("arguments"), dict):
raise ValueError(f"Expected a {stage} tool target")
path = Path(row["input"])
path = (root / path).resolve() if not path.is_absolute() else path.resolve()
if not path.exists():
raise ValueError(f"Missing visual input: {path}")
row["input"] = str(path)
identity = (row["input"], row["system"], row["instruction"], len(history))
if identity in seen:
raise ValueError("Duplicate question/round")
seen.add(identity)
row["_stage"] = stage
row["_source"] = f"{source}:{line_no}"
rows.append(row)
except (ValueError, TypeError, KeyError, AttributeError) as exc:
raise ValueError(f"{source}:{line_no}: {exc}") from exc
if not rows:
raise ValueError(f"Empty dataset: {source}")
return rows
def tagged_json(text, tag):
start, end = f"<{tag}>", f"</{tag}>"
if text.count(start) != 1 or text.count(end) != 1:
raise ValueError(f"Expected exactly one {tag} block")
value = json.loads(text.split(start, 1)[1].split(end, 1)[0])
if not isinstance(value, dict):
raise ValueError(f"{tag} must contain a JSON object")
return value
def audit(rows):
groups = {}
for row in rows:
key = (row["input"], row["system"], row["instruction"])
groups.setdefault(key, {})[len(row["history"])] = row
for group in groups.values():
if set(group) != set(range(4)):
raise ValueError("Each question must have all four rounds in the same split")
for index in range(1, 4):
previous, current = group[index - 1], group[index]
if (current["history"][:-1] != previous["history"]
or current["history"][-1][0] != previous["output"]):
raise ValueError(f"Inconsistent trajectory at {current['_source']}")
return {"rows": len(rows), "questions": len(groups),
"visual_inputs": len({r["input"] for r in rows}),
"stages": dict(Counter(r["_stage"] for r in rows))}
def check_split_overlap(train, validation):
for key in ("input", "question_id", "video_id", "narration_uid"):
left = {r[key] for r in train if r.get(key) is not None}
right = {r[key] for r in validation if r.get(key) is not None}
if left & right:
raise ValueError(f"Training/validation overlap in {key}")
def frame_indices(count, source_fps, sample_fps, max_frames):
if count < 1 or not math.isfinite(source_fps) or source_fps <= 0:
raise ValueError("Cannot sample input with unknown frame count or FPS")
# Include both endpoints. Cap before constructing indices for long videos.
wanted = min(count, max_frames, max(2, math.ceil((count - 1) / source_fps * sample_fps) + 1))
if wanted == 1:
return [0]
return sorted({round(i * (count - 1) / (wanted - 1)) for i in range(wanted)})
class FrameLoader:
def __init__(self, fps=2.0, max_frames=16, max_pixels=262144, cache_size=2, directory_fps=None):
self.fps, self.max_frames, self.max_pixels = fps, max_frames, max_pixels
self.cache_size, self.directory_fps = cache_size, directory_fps
self.cache = OrderedDict()
def __call__(self, filename):
from PIL import Image
if filename in self.cache:
self.cache.move_to_end(filename)
return self.cache[filename]
path = Path(filename)
frames = []
def bounded(image):
image = image.convert("RGB")
scale = min(1.0, math.sqrt(self.max_pixels / (image.width * image.height)))
if scale < 1:
image = image.resize((max(1, int(image.width * scale)),
max(1, int(image.height * scale))), Image.Resampling.LANCZOS)
return image
if path.is_dir():
import re
if not self.directory_fps:
raise ValueError("Frame directories require --directory-fps")
files = sorted((p for p in path.iterdir() if p.suffix.lower() in
{".jpg", ".jpeg", ".png", ".bmp"}),
key=lambda p: [int(s) if s.isdigit() else s.lower()
for s in re.split(r"(\d+)", p.name)])
indices = frame_indices(len(files), self.directory_fps, self.fps, self.max_frames)
for index in indices:
with Image.open(files[index]) as image:
frames.append(bounded(image))
else:
import cv2
cap = cv2.VideoCapture(str(path))
try:
if not cap.isOpened():
raise ValueError(f"Cannot open video: {path}")
indices = frame_indices(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
cap.get(cv2.CAP_PROP_FPS), self.fps, self.max_frames)
for index in indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, index)
ok, frame = cap.read()
if not ok:
raise ValueError(f"Cannot decode frame {index}: {path}")
frames.append(bounded(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))))
finally:
cap.release()
if self.cache_size:
self.cache[filename] = frames
while len(self.cache) > self.cache_size:
self.cache.popitem(last=False)
return frames
def messages_for(row, frames):
messages = [{"role": "system", "content": [{"type": "text", "text": row["system"]}]},
{"role": "user", "content": [{"type": "image", "image": frame} for frame in frames]
+ [{"type": "text", "text": row["instruction"]}]}]
for assistant, observation in row["history"]:
messages.extend([{"role": "assistant", "content": [{"type": "text", "text": assistant}]},
{"role": "user", "content": [{"type": "text", "text": observation}]}])
return messages
def output_labels(full, prefix):
"""Use attention masks, not pad token IDs: EOS can share the pad ID."""
import torch
labels = torch.full_like(full["input_ids"], -100)
for i in range(len(labels)):
positions = full["attention_mask"][i].bool().nonzero(as_tuple=True)[0]
full_ids = full["input_ids"][i, positions]
prefix_ids = prefix["input_ids"][i, prefix["attention_mask"][i].bool()]
size = len(prefix_ids)
if size >= len(full_ids) or not torch.equal(full_ids[:size], prefix_ids):
raise ValueError("Chat template prefix mismatch or empty target; refusing incorrect loss masking")
labels[i, positions[size:]] = full_ids[size:]
return labels
class HandyVQACollator:
def __init__(self, processor, loader, max_length=8192):
self.processor, self.loader, self.max_length = processor, loader, max_length
def __call__(self, features):
full_texts, prefix_texts, images = [], [], []
for row in features:
frames = self.loader(row["input"])
if not frames:
raise ValueError(f"No images for {row['_source']}")
messages = messages_for(row, frames)
prefix_texts.append(self.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True))
messages = messages + [{"role": "assistant", "content": [{"type": "text", "text": row["output"]}]}]
full_texts.append(self.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=False))
images.extend(frames)
# Images are decoded once; the two processor calls must expand the same
# image tokens to determine the exact answer boundary for each sample.
full = self.processor(text=full_texts, images=images, padding=True,
truncation=False, return_tensors="pt")
lengths = full["attention_mask"].sum(dim=1).tolist()
for row, length in zip(features, lengths):
if length > self.max_length:
raise ValueError(f"{row['_source']}: {length} tokens > {self.max_length}; "
"reduce --max-frames/--max-pixels or use shorter evidence")
prefix = self.processor(text=prefix_texts, images=images, padding=True,
truncation=False, return_tensors="pt")
full["labels"] = output_labels(full, prefix)
return full
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--train-data", required=True)
p.add_argument("--eval-data", help="Separate, four-round distilled validation JSONL")
p.add_argument("--video-root", help="Base for relative input paths; default: each JSONL directory")
p.add_argument("--model", help="Local Qwen3-VL model path or HF model ID; fill before training")
p.add_argument("--output-dir", help="New local training directory; fill before training")
p.add_argument("--check-data", action="store_true", help="Validate data only; no ML dependencies")
p.add_argument("--dry-run", action="store_true", help="Check all batches with processor; no model weights")
p.add_argument("--local-files-only", action="store_true")
p.add_argument("--sample-fps", type=float, default=2.0)
p.add_argument("--max-frames", type=int, default=16)
p.add_argument("--min-pixels", type=int, default=4096)
p.add_argument("--max-pixels", type=int, default=262144)
p.add_argument("--max-length", type=int, default=8192)
p.add_argument("--directory-fps", type=float, help="FPS of pre-extracted frame directories")
p.add_argument("--frame-cache-size", type=int, default=2, help="Videos cached per worker/rank")
p.add_argument("--batch-size", type=int, default=1)
p.add_argument("--grad-accum", type=int, default=8)
p.add_argument("--epochs", type=float, default=1.0)
p.add_argument("--learning-rate", type=float, default=5e-6)
p.add_argument("--warmup-ratio", type=float, default=0.03)
p.add_argument("--weight-decay", type=float, default=0.01)
p.add_argument("--precision", choices=("bf16", "fp16", "fp32"), default="bf16")
p.add_argument("--attention", choices=("sdpa", "eager", "flash_attention_2"), default="sdpa")
p.add_argument("--workers", type=int, default=0)
p.add_argument("--save-steps", type=int, default=100)
p.add_argument("--eval-steps", type=int, default=100)
p.add_argument("--logging-steps", type=int, default=10)
p.add_argument("--save-total-limit", type=int, default=2)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--resume-from-checkpoint", help="Explicit Trainer checkpoint directory")
p.add_argument("--deepspeed", help="Optional DeepSpeed config JSON; select for your GPUs")
args = p.parse_args()
for name in ("sample_fps", "max_frames", "min_pixels", "max_pixels", "max_length", "batch_size",
"grad_accum", "epochs", "learning_rate", "save_steps", "eval_steps", "logging_steps", "save_total_limit"):
if not math.isfinite(getattr(args, name)) or getattr(args, name) <= 0:
p.error(f"--{name.replace('_', '-')} must be positive and finite")
if (args.min_pixels > args.max_pixels or args.frame_cache_size < 0 or args.workers < 0
or not 0 <= args.warmup_ratio <= 1 or not math.isfinite(args.weight_decay) or args.weight_decay < 0):
p.error("Invalid pixel limits, cache size, workers, warmup ratio, or weight decay")
if args.directory_fps is not None and (not math.isfinite(args.directory_fps) or args.directory_fps <= 0):
p.error("--directory-fps must be positive and finite")
if not args.check_data and not args.model:
p.error("Supply --model for dry-run or training")
if not args.check_data and not args.dry_run and not args.output_dir:
p.error("Supply --output-dir for training")
return args
def main():
args = parse_args()
train = read_data(args.train_data, args.video_root)
evaluation = read_data(args.eval_data, args.video_root) if args.eval_data else []
summaries = {"train": audit(train)}
if evaluation:
summaries["validation"] = audit(evaluation)
check_split_overlap(train, evaluation)
print(json.dumps(summaries, indent=2), flush=True)
if args.check_data:
return
manifest = {"arguments": vars(args), "data": summaries,
"sha256": {name: hashlib.sha256(Path(name).read_bytes()).hexdigest()
for name in (args.train_data, args.eval_data) if name}}
if not args.dry_run:
output = Path(args.output_dir)
if output.exists() and any(output.iterdir()) and not args.resume_from_checkpoint:
raise ValueError("Output directory is not empty; select a new directory or explicitly resume")
if args.resume_from_checkpoint:
checkpoint = Path(args.resume_from_checkpoint).resolve()
if checkpoint.parent != output.resolve() or not (checkpoint / "trainer_state.json").is_file():
raise ValueError("Resume requires a Trainer checkpoint inside the original output directory")
manifest_path = output / "sft_run.json"
if not manifest_path.exists():
raise ValueError("Missing original sft_run.json")
original = json.loads(manifest_path.read_text())
if original["sha256"] != manifest["sha256"]:
raise ValueError("Resume requires the same dataset snapshot")
for key in ("model", "sample_fps", "max_frames", "min_pixels", "max_pixels", "max_length",
"directory_fps", "video_root", "precision", "batch_size", "grad_accum", "seed"):
if original["arguments"][key] != vars(args)[key]:
raise ValueError(f"Resume configuration changed: {key}")
from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained(args.model, local_files_only=args.local_files_only,
min_pixels=args.min_pixels, max_pixels=args.max_pixels)
processor.tokenizer.padding_side = "right"
if processor.tokenizer.pad_token_id is None:
raise ValueError("The model tokenizer must define a pad token")
loader = FrameLoader(args.sample_fps, args.max_frames, args.max_pixels,
args.frame_cache_size, args.directory_fps)
collator = HandyVQACollator(processor, loader, args.max_length)
if args.dry_run:
for split, rows in (("train", train), ("validation", evaluation)):
lengths, targets = [], []
for start in range(0, len(rows), args.batch_size):
batch = collator(rows[start:start + args.batch_size])
lengths.extend(batch["attention_mask"].sum(dim=1).tolist())
targets.extend((batch["labels"] != -100).sum(dim=1).tolist())
if lengths:
print(json.dumps({"split": split, "checked": len(lengths), "max_tokens": max(lengths),
"min_target_tokens": min(targets), "max_target_tokens": max(targets)}), flush=True)
return
import torch
from transformers import Qwen3VLForConditionalGeneration, Trainer, TrainerCallback, TrainingArguments, set_seed
class SaveLastStep(TrainerCallback):
def on_step_end(self, args, state, control, **kwargs):
if state.global_step >= state.max_steps:
control.should_save = True
return control
set_seed(args.seed)
# Construct TrainingArguments first so ZeRO-3 can initialize model loading.
training_args = TrainingArguments(
output_dir=str(output), num_train_epochs=args.epochs,
per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size,
gradient_accumulation_steps=args.grad_accum, learning_rate=args.learning_rate,
warmup_ratio=args.warmup_ratio, weight_decay=args.weight_decay, lr_scheduler_type="cosine",
bf16=args.precision == "bf16", fp16=args.precision == "fp16",
gradient_checkpointing=True, gradient_checkpointing_kwargs={"use_reentrant": False},
remove_unused_columns=False, dataloader_num_workers=args.workers,
save_strategy="steps", save_steps=args.save_steps, save_total_limit=args.save_total_limit,
eval_strategy="steps" if evaluation else "no", eval_steps=args.eval_steps,
logging_steps=args.logging_steps, report_to="none", push_to_hub=False,
prediction_loss_only=True, seed=args.seed, data_seed=args.seed,
ddp_find_unused_parameters=False, deepspeed=args.deepspeed,
)
model = Qwen3VLForConditionalGeneration.from_pretrained(
args.model, torch_dtype=torch.bfloat16 if args.precision == "bf16" else torch.float32,
attn_implementation=args.attention, local_files_only=args.local_files_only)
model.config.use_cache = False
eval_sets = {stage: [r for r in evaluation if r["_stage"] == stage] for stage in STAGES} if evaluation else None
trainer = Trainer(model=model, args=training_args, train_dataset=train,
eval_dataset=eval_sets, data_collator=collator, processing_class=processor,
callbacks=[SaveLastStep()])
if trainer.is_world_process_zero():
output.mkdir(parents=True, exist_ok=True)
manifest_path = output / "sft_run.json"
if not args.resume_from_checkpoint:
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
result = trainer.train(resume_from_checkpoint=args.resume_from_checkpoint)
trainer.save_state()
trainer.save_metrics("train", result.metrics)
if evaluation:
trainer.save_metrics("eval", trainer.evaluate())
model.config.use_cache = True
trainer.save_model(str(output / "final"))
if trainer.is_world_process_zero():
processor.save_pretrained(output / "final")
if __name__ == "__main__":
main()