PortraitMT / qwenvl /train /logging_callback.py
MHHHH02's picture
Upload folder using huggingface_hub
1737ebf verified
Raw History Blame Contribute Delete
5.87 kB
"""
Local training logger callback.
Writes two files to output_dir:
- train_metrics.jsonl : one JSON line per logging step with loss / grad_norm / lr / step
- model_output_samples.txt : periodic model generation samples showing <think> + score token
"""
import csv
import json
import os
import time
from pathlib import Path
from typing import Optional
import torch
from transformers import TrainerCallback, TrainerControl, TrainerState, TrainingArguments
class LocalLoggingCallback(TrainerCallback):
"""
Args:
processor: AutoProcessor (for generation + decoding).
sample_dataset: A small list of dicts with keys image_path / question / gt_score,
used for periodic generation samples. Pass None to skip.
sample_every_steps: How often (in steps) to run generation samples.
output_dir: Where to write log files (defaults to training_args.output_dir).
"""
def __init__(
self,
processor,
sample_dataset=None,
sample_every_steps: int = 500,
output_dir: Optional[str] = None,
):
self.processor = processor
self.sample_dataset = sample_dataset or []
self.sample_every_steps = sample_every_steps
self._output_dir = output_dir
self._metrics_path = None
self._samples_path = None
self._csv_writer = None
self._csv_file = None
# ── setup ─────────────────────────────────────────────────────────────────
def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
out = Path(self._output_dir or args.output_dir)
out.mkdir(parents=True, exist_ok=True)
self._metrics_path = out / "train_metrics.jsonl"
self._samples_path = out / "model_output_samples.txt"
if args.local_rank in (-1, 0):
with open(self._samples_path, "a") as f:
f.write(f"\n{'='*60}\nTraining started: {time.strftime('%Y-%m-%d %H:%M:%S')}\n{'='*60}\n")
# ── metrics logging ───────────────────────────────────────────────────────
def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, logs=None, **kwargs):
if args.local_rank not in (-1, 0):
return
if logs is None:
return
record = {
"step": state.global_step,
"epoch": round(state.epoch or 0, 4),
"loss": logs.get("loss"),
"grad_norm": logs.get("grad_norm"),
"lr": logs.get("learning_rate"),
"wall_time": time.time(),
}
record = {k: v for k, v in record.items() if v is not None}
with open(self._metrics_path, "a") as f:
f.write(json.dumps(record) + "\n")
# ── generation samples ────────────────────────────────────────────────────
def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model=None, **kwargs):
if args.local_rank not in (-1, 0):
return
if not self.sample_dataset:
return
if state.global_step % self.sample_every_steps != 0:
return
self._run_samples(model, state.global_step, args)
def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model=None, **kwargs):
if args.local_rank not in (-1, 0):
return
if self.sample_dataset and model is not None:
self._run_samples(model, state.global_step, args, label="[FINAL]")
def _run_samples(self, model, step: int, args: TrainingArguments, label: str = ""):
model.eval()
lines = [f"\n--- Step {step} {label} {time.strftime('%H:%M:%S')} ---\n"]
with torch.no_grad():
for item in self.sample_dataset:
image_path = item["image_path"]
question = item["question"]
gt_score = item.get("gt_score", "?")
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image_path},
{"type": "text", "text": question},
],
}
]
try:
inputs = self.processor.apply_chat_template(
messages, tokenize=True, return_dict=True,
return_tensors="pt", add_generation_prompt=True,
)
inputs = {k: v.to(model.device) if hasattr(v, "to") else v
for k, v in inputs.items()}
out_ids = model.generate(
**inputs,
max_new_tokens=300,
do_sample=False,
)
# decode only the generated tokens
generated = out_ids[0][inputs["input_ids"].shape[1]:]
text = self.processor.tokenizer.decode(generated, skip_special_tokens=False)
lines.append(f"[Q] {question[:80]}")
lines.append(f"[GT score] {gt_score}")
lines.append(f"[Model output]\n{text}\n")
except Exception as e:
lines.append(f"[ERROR] {e}\n")
with open(self._samples_path, "a") as f:
f.write("\n".join(lines) + "\n")
model.train()