code-HFD / src /psi /trainers /swa_validation.py
Tinghong-Ye22's picture
Add files using upload-large-folder tool
06f9561 verified
Raw History Blame Contribute Delete
4.35 kB
"""Small deterministic held-out SWA semantic audit, separate from audio eval."""
from __future__ import annotations
import torch
from torch.nn import functional as F
from psi.data.seed.swa_visual_qa_dataset import bind_swa_batch
def validation_indices(size: int, budget: int = 16) -> list[int]:
count = min(size, budget)
return [i * size // count for i in range(count)] if count else []
@torch.no_grad()
def evaluate_swa_semantics(model, dataset, accelerator, budget: int = 16, launch_config=None) -> dict:
# Unwrapped Qwen has no DDP collectives; each rank may audit a different
# number of windows. Only the final additive statistics are reduced.
totals = torch.zeros(9, device=accelerator.device, dtype=torch.float64)
indices = validation_indices(len(dataset), budget)
body_totals = None
body_names = None
for index in indices[accelerator.process_index::accelerator.num_processes]:
source = dataset[index]
def observe(model, cache, packet):
nonlocal totals
with accelerator.autocast():
target = torch.tensor([packet["reply_label"]], device=accelerator.device)
logits = model.reply_logits.float()
reply_loss = F.cross_entropy(logits, target, reduction="sum")
qa_loss, qa_correct, qa_count = model.qa_loss(cache, [packet["answer_target"]])
if packet["answer_target"] and float(qa_count) <= 0:
raise RuntimeError("SWA validation has answer targets but no supervised tokens")
correct = (logits.argmax(-1) == target).double().sum()
positive = target.eq(1).double().sum()
totals += torch.stack((reply_loss, target.new_tensor(1), correct * positive,
positive, correct * (1 - positive), 1 - positive,
qa_loss, qa_correct, qa_count)).double()
if launch_config is not None:
from psi.runtime.swa_rollout import rollout_source, body_metrics
from psi.data.seed.swa_visual_qa_dataset import _load_body
motion, _ = rollout_source(model, launch_config, source, observer=observe)
values = body_metrics(motion, _load_body(source["swa_job"]["path"])["gt_abs"])
body_names = sorted(values)
row = torch.tensor([1., *[values[k] for k in body_names]], device=accelerator.device, dtype=torch.float64)
body_totals = row if body_totals is None else body_totals + row
else:
cache = model.begin_source([source["source_id"]])
for packet_index, packet in enumerate(source["swa_packets"]):
bind_swa_batch(model, [source], [packet_index], device=accelerator.device)
with accelerator.autocast():
cache = model._encode_qwen_stream_input(
source_ids=[source["source_id"]], cache=cache, update_semantic_cache=True,
).kv_cache
observe(model, cache, packet)
cache.detach()
totals = accelerator.reduce(totals, reduction="sum")
if totals[1] <= 0 or totals[8] <= 0:
raise RuntimeError("SWA validation cohort contains no question supervision")
recalls = [totals[2] / totals[3]] if totals[3] > 0 else []
if totals[5] > 0:
recalls.append(totals[4] / totals[5])
metrics = {
"swa_reply_loss": float(totals[0] / totals[1]),
"swa_reply_balanced_accuracy": float(torch.stack(recalls).mean()),
"swa_qa_loss": float(totals[6] / totals[8]),
"swa_qa_token_accuracy": float(totals[7] / totals[8]),
"swa_qa_target_tokens": float(totals[8]),
}
if launch_config is not None:
# Same six metrics even when this rank has no assigned source.
names = sorted(("joint_rmse_rad", "root_xy_rmse_m", "root_z_rmse_m",
"root_rotation_deg", "joint_velocity_error_rad_s", "joint_acceleration_error_rad_s2"))
if body_totals is None:
body_totals = torch.zeros(7, device=accelerator.device, dtype=torch.float64)
body_totals = accelerator.reduce(body_totals, reduction="sum")
metrics.update({"swa_closed_loop_" + k: float(body_totals[i + 1] / body_totals[0])
for i, k in enumerate(names)})
return metrics