File size: 8,256 Bytes
5f4e9ea | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | """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
|