Download src/psi/data/seed/swa_visual_qa_dataset.py from Tinghong-Ye22/code-HFD: direct link, hf CLI and curl.
- Browser
- Download file 9.54 kB
-
https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/src/psi/data/seed/swa_visual_qa_dataset.py
- Command line
-
hf download hf://Tinghong-Ye22/code-HFD/src/psi/data/seed/swa_visual_qa_dataset.py
-
curl -L -o swa_visual_qa_dataset.py https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/src/psi/data/seed/swa_visual_qa_dataset.py
9.54 kB
| """Formal SWA visual-QA sources and mixed HFD dataset. | |
| The expensive camera/audio frontend is frozen on disk. Qwen, its KV, the | |
| action/control/duration heads and the two SWA heads remain online/trainable. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| def bind_swa_batch(model, sources, packet_indices, *, device, auxiliary=False, | |
| positive_weight=8.0, padding_source=None) -> bool: | |
| """Bind this forward's inputs; audio batches must clear prior AV state. | |
| None rows are padding: their packet is shape-only and never a QA target. | |
| The caller's semantic mask prevents them from writing production KV. | |
| """ | |
| if len(sources) != len(packet_indices): | |
| raise ValueError("SWA source rows and packet indices must match") | |
| modes = {row.get("source_modality", "audio_action") | |
| for row in sources if row is not None} | |
| if not modes and padding_source is not None: | |
| modes = {padding_source.get("source_modality", "audio_action")} | |
| if len(modes) > 1: | |
| raise RuntimeError("Audio and SWA rows entered one Qwen cache batch") | |
| model.swa_packets = None | |
| model.swa_compute_auxiliary = False | |
| model.swa_reply_targets = None | |
| model.swa_answer_targets = None | |
| if modes != {"swa_visual_qa"}: | |
| return False | |
| fallback = next((row for row in sources if row is not None), padding_source) | |
| packets, labels, answers = [], [], [] | |
| for row, index in zip(sources, packet_indices): | |
| owner = fallback if row is None else row | |
| sequence = owner["swa_packets"] | |
| if not sequence: | |
| raise RuntimeError("SWA source has no packets") | |
| if row is not None and (index is None or not 0 <= int(index) < len(sequence)): | |
| raise RuntimeError("SWA packet index is outside the source timeline") | |
| packet = sequence[0 if row is None else int(index)] | |
| packets.append(packet) | |
| labels.append(int(packet["reply_label"]) if row is not None else 0) | |
| answers.append(str(packet["answer_target"]) if row is not None else "") | |
| model.swa_packets = packets | |
| model.swa_reply_targets = torch.tensor(labels, device=device, dtype=torch.long) | |
| model.swa_answer_targets = answers | |
| model.swa_reply_positive_weight = float(positive_weight) | |
| model.swa_compute_auxiliary = bool(auxiliary) | |
| return True | |
| def modality_batches(batches): | |
| """Keep validation's row order/budget while splitting modality seams.""" | |
| for batch in batches: | |
| group = [] | |
| for source in batch["sources"]: | |
| if group and source.get("source_modality", "audio_action") != group[0].get("source_modality", "audio_action"): | |
| yield {**batch, "sources": group} | |
| group = [] | |
| group.append(source) | |
| if group: | |
| yield {**batch, "sources": group} | |
| def _load_body(path: str) -> dict[str, Any]: | |
| return torch.load(path, weights_only=False, mmap=True) | |
| def validate_swa_progress_geometry(path: str) -> None: | |
| """Reject cached bodies whose progress clock differs from deployment. | |
| GT is inspected ONLY to validate the offline data format, never used as | |
| deployment duration/progress. This check runs once per immutable body. | |
| """ | |
| import numpy as np | |
| from psi.runtime.swa_rollout import inplace_future_progress | |
| source = _load_body(path)["source"] | |
| motion = [s for s in source["steps"] if s.get("phase") == "motion"] | |
| if not motion: | |
| raise ValueError(f"SWA body has no motion supervision: {path}") | |
| for step in (motion[0], motion[len(motion) // 2]): | |
| total = round(float(step["motion_duration_target_seconds"]) * 50) | |
| expected = inplace_future_progress(int(step["frame_id"]), total) | |
| if not np.allclose(step["future_progress"], expected, atol=2e-6, rtol=0): | |
| raise ValueError(f"SWA cached body has incompatible progress geometry: {path}") | |
| class SwaVisualQaDataset(torch.utils.data.Dataset): | |
| def __init__(self, source_plan: str, split: str, repeat: int = 1) -> None: | |
| self.source_plan = Path(source_plan).expanduser().resolve() | |
| if not self.source_plan.is_file(): | |
| raise FileNotFoundError(f"SWA source plan is missing: {self.source_plan}") | |
| rows = json.loads(self.source_plan.read_text(encoding="utf-8")) | |
| self.rows = tuple(row for row in rows if str(row.get("split")) == split) | |
| self.repeat = max(int(repeat), 1) if split == "train" else 1 | |
| self._stream_lengths = None | |
| if not self.rows: | |
| raise ValueError(f"SWA plan has no {split!r} rows: {self.source_plan}") | |
| def __len__(self) -> int: | |
| return len(self.rows) * self.repeat | |
| def _row(self, index: int) -> dict[str, Any]: | |
| return self.rows[int(index) % len(self.rows)] | |
| def _frontend_path(row: dict[str, Any]) -> Path: | |
| return Path(row["frontend_root"]) / "data" / "frontend" / f"{row['id']}.pt" | |
| def source_modality(self, index: int) -> str: | |
| return "swa_visual_qa" | |
| def estimated_stream_steps(self, index: int) -> int: | |
| if self._stream_lengths is None: | |
| from psi.data.seed.startup_index_cache import cached_index | |
| paths = sorted({str(row["path"]) for row in self.rows}) | |
| signatures = [] | |
| for path in paths: | |
| stat = Path(path).stat() | |
| signatures.append((path, stat.st_size, stat.st_mtime_ns, | |
| stat.st_ctime_ns)) | |
| def build(): | |
| # Bypass the item LRU: a replaced body must not inherit its | |
| # previous in-process value under a new filesystem signature. | |
| return {path: len(torch.load(path, weights_only=False, mmap=True)["source"]["steps"]) | |
| for path in paths} | |
| lengths = cached_index("swa-body-lengths", signatures, build, | |
| code_paths=(Path(__file__),)) | |
| self._stream_lengths = tuple(lengths[str(row["path"])] for row in self.rows) | |
| return self._stream_lengths[int(index) % len(self.rows)] | |
| def __getitem__(self, index: int) -> dict[str, Any]: | |
| row = self._row(index) | |
| validate_swa_progress_geometry(str(row["path"])) | |
| source = dict(_load_body(str(row["path"]))["source"]) | |
| frontend_path = self._frontend_path(row) | |
| if not frontend_path.is_file(): | |
| raise FileNotFoundError(f"SWA frontend packet is missing: {frontend_path}") | |
| from psi.data.seed.swa_frontend import load_swa_frontend | |
| frontend = load_swa_frontend(frontend_path) | |
| packets = frontend.get("packets") | |
| if not packets: | |
| raise RuntimeError(f"SWA frontend has no packets: {frontend_path}") | |
| variant = int(index) // len(self.rows) | |
| source["source_id"] = f"swa::{row['id']}::v{variant}" | |
| source["source_modality"] = "swa_visual_qa" | |
| # A unique source is a QA example unless its immutable source plan | |
| # explicitly declares an ordinary/no-question hard negative. The | |
| # variant rule remains only for exact reproduction of historical runs | |
| # that deliberately requested repeat > 1; repeat=1 must never erase | |
| # every QA target merely because its sole variant number is zero. | |
| if "swa_has_question" in row: | |
| with_qa = bool(row["swa_has_question"]) | |
| elif self.repeat > 1: | |
| with_qa = variant % 4 != 0 | |
| else: | |
| with_qa = True | |
| prepared_packets = [] | |
| for packet in packets: | |
| prepared = dict(packet) | |
| if not with_qa: | |
| prepared["embeds"] = prepared["embeds"].clone() | |
| prepared["embeds"][prepared["audio_mask"]] = prepared["ordinary_audio"] | |
| prepared["reply_label"] = 0 | |
| prepared["answer_target"] = "" | |
| prepared_packets.append(prepared) | |
| source["swa_packets"] = prepared_packets | |
| source["swa_job"] = row | |
| # Body tensors were produced by the exact formal transform snapshot. | |
| source["steps"] = [dict(step, source_id=source["source_id"]) for step in source["steps"]] | |
| return source | |
| class MixedFullDuplexDataset(torch.utils.data.Dataset): | |
| """Concatenate audio and SWA sources while exposing sampler modality.""" | |
| def __init__(self, audio_dataset, swa_dataset: SwaVisualQaDataset) -> None: | |
| self.audio_dataset = audio_dataset | |
| self.swa_dataset = swa_dataset | |
| self.audio_size = len(audio_dataset) | |
| # Preserve the leakage audit interface used by the trainer. | |
| self.raw_dataset = getattr(audio_dataset, "raw_dataset", audio_dataset) | |
| def __len__(self) -> int: | |
| return self.audio_size + len(self.swa_dataset) | |
| def source_modality(self, index: int) -> str: | |
| return "audio_action" if index < self.audio_size else "swa_visual_qa" | |
| def estimated_stream_steps(self, index: int) -> int: | |
| if index < self.audio_size: | |
| return self.audio_dataset.estimated_stream_steps(index) | |
| return self.swa_dataset.estimated_stream_steps(index - self.audio_size) | |
| def __getitem__(self, index: int) -> dict[str, Any]: | |
| if index < self.audio_size: | |
| source = self.audio_dataset[index] | |
| source["source_modality"] = "audio_action" | |
| return source | |
| return self.swa_dataset[index - self.audio_size] | |