PhysVLM / other_transfer /src /physics_model /val_callback.py
hk239's picture
Upload 798 files
5f4e9ea verified
Raw History Blame Contribute Delete
8.26 kB
"""Generation-based val metrics after each Trainer evaluate() call."""
from __future__ import annotations
import json
import logging
import time
from pathlib import Path
import torch
from transformers import TrainerCallback
from physics_model.eval import generate_many, summarize
from physics_sft.metrics import flatten_eval_metrics, format_eval_table, score_prediction
logger = logging.getLogger(__name__)
_GLOO_GROUP = None
class PhysicsValMetricsCallback(TrainerCallback):
"""After loss eval, greedy-decode a mixed val subset and log answer metrics."""
def __init__(
self,
processor,
collator,
eval_rows: list[dict],
*,
output_dir: Path,
max_new_tokens: int = 512,
max_samples: int | None = 32,
gen_batch_size: int = 4,
) -> None:
self.processor = processor
self.collator = collator
self.eval_rows = _take_mixed(list(eval_rows), max_samples)
self.output_dir = Path(output_dir)
self.max_new_tokens = int(max_new_tokens)
self.gen_batch_size = max(1, int(gen_batch_size))
self._trainer = None
self._last_summary: dict = {}
def set_trainer(self, trainer) -> None:
self._trainer = trainer
def on_evaluate(self, args, state, control, metrics=None, **kwargs):
if self._trainer is None and hasattr(self, "trainer"):
self._trainer = self.trainer
trainer = self._trainer
if trainer is None or not self.eval_rows:
return
extra: dict = {}
try:
logger.info(
"step %s: starting generation val on %s rows (batch=%s, max_new_tokens=%s)",
state.global_step,
len(self.eval_rows),
self.gen_batch_size,
self.max_new_tokens,
)
t0 = time.time()
extra = self._run(trainer, state.global_step)
logger.info("step %s: generation val finished in %.1fs", state.global_step, time.time() - t0)
if extra and trainer.accelerator.is_main_process:
logger.info("\n%s", format_eval_table(self._last_summary, step=state.global_step))
except Exception:
logger.exception("generation val failed; continuing training")
extra = {}
_cpu_barrier()
if metrics is not None and extra:
metrics.update(extra)
if extra and trainer.accelerator.is_main_process:
trainer.log(extra)
@torch.no_grad()
def _run(self, trainer, step: int) -> dict:
accelerator = trainer.accelerator
rank = int(accelerator.process_index)
world = int(accelerator.num_processes)
model = accelerator.unwrap_model(trainer.model)
restore = _enable_fast_generate(model)
was_training = model.training
model.eval()
_gloo_group()
local_error = None
detailed_part: list[dict] = []
my_rows = self.eval_rows[rank::world]
try:
preds = generate_many(
model,
self.processor,
self.collator,
my_rows,
self.max_new_tokens,
device=accelerator.device,
batch_size=self.gen_batch_size,
synced_gpus=False,
)
detailed_part = [score_prediction(row, pred) for row, pred in zip(my_rows, preds)]
logger.info("rank %s val generate %s/%s", rank, len(my_rows), len(self.eval_rows))
except Exception as exc:
local_error = f"{type(exc).__name__}: {exc}"
logger.exception("rank %s generation val failed", rank)
finally:
restore()
if was_training:
model.train()
trainer.model.train()
gathered = _all_gather_object({"rows": detailed_part, "error": local_error})
if any(part.get("error") for part in gathered):
logger.warning("skipping val metrics because at least one rank failed")
return {}
detailed = _merge_sharded_rows(self.eval_rows, gathered, world)
summary = summarize(detailed)
self._last_summary = summary
flat = {k: (None if _is_nan(v) else v) for k, v in flatten_eval_metrics(summary, prefix="eval").items()}
if accelerator.is_main_process:
payload = {
"step": step,
"n": len(detailed),
"summary": summary,
"metrics": flat,
"rows": detailed,
}
self.output_dir.mkdir(parents=True, exist_ok=True)
path = self.output_dir / f"eval_step_{step}.json"
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
logger.info("wrote val predictions %s", path)
return flat
def _enable_fast_generate(model):
"""Turn on KV cache and turn off checkpointing for decode; restore afterwards."""
modules = []
seen = set()
stack = [model]
if hasattr(model, "get_base_model"):
stack.append(model.get_base_model())
if hasattr(model, "base_model"):
stack.append(model.base_model)
for module in stack:
ident = id(module)
if ident in seen:
continue
seen.add(ident)
modules.append(module)
snapshot = []
for module in modules:
cfg = getattr(module, "config", None)
snapshot.append(
(
module,
bool(getattr(cfg, "use_cache", False)) if cfg is not None else False,
bool(getattr(module, "is_gradient_checkpointing", False)),
)
)
if cfg is not None:
cfg.use_cache = True
if hasattr(module, "gradient_checkpointing_disable"):
module.gradient_checkpointing_disable()
def restore() -> None:
for module, use_cache, had_gc in snapshot:
cfg = getattr(module, "config", None)
if cfg is not None:
cfg.use_cache = use_cache
if had_gc and hasattr(module, "gradient_checkpointing_enable"):
module.gradient_checkpointing_enable()
return restore
def _gloo_group():
global _GLOO_GROUP
import torch.distributed as dist
if not dist.is_available() or not dist.is_initialized() or dist.get_world_size() <= 1:
return None
if _GLOO_GROUP is None:
_GLOO_GROUP = dist.new_group(backend="gloo")
return _GLOO_GROUP
def _all_gather_object(obj):
import torch.distributed as dist
if not dist.is_available() or not dist.is_initialized() or dist.get_world_size() <= 1:
return [obj]
group = _gloo_group()
gathered = [None] * dist.get_world_size()
dist.all_gather_object(gathered, obj, group=group)
return gathered
def _cpu_barrier() -> None:
import torch.distributed as dist
if not dist.is_available() or not dist.is_initialized() or dist.get_world_size() <= 1:
return
dist.barrier(group=_gloo_group())
def _take_mixed(rows: list[dict], max_samples: int | None) -> list[dict]:
if max_samples is None:
return rows
limit = max(0, int(max_samples))
if limit == 0 or len(rows) <= limit:
return rows[:limit]
images = [r for r in rows if r.get("has_image")]
texts = [r for r in rows if not r.get("has_image")]
n_img = min(len(images), limit // 2)
n_txt = min(len(texts), limit - n_img)
picked = images[:n_img] + texts[:n_txt]
if len(picked) < limit:
leftover = [r for r in rows if r not in picked]
picked.extend(leftover[: limit - len(picked)])
return picked
def _merge_sharded_rows(eval_rows: list[dict], gathered: list[dict], world: int) -> list[dict]:
merged: list[dict | None] = [None] * len(eval_rows)
for rank, part in enumerate(gathered):
rows = part.get("rows") or []
idxs = range(rank, len(eval_rows), world)
for idx, item in zip(idxs, rows):
merged[idx] = item
return [item for item in merged if item is not None]
def _is_nan(value) -> bool:
try:
return value != value
except Exception:
return False