import argparse import os import random import subprocess from pathlib import Path from typing import Dict, List, Optional, Tuple import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import sacrebleu import torch try: import evaluate except ImportError as exc: raise ImportError( "This script now requires the 'evaluate' package. " "Install it via 'pip install evaluate' (or add it to your environment) and rerun." ) from exc from datasets import Dataset from transformers import ( AutoModelForSeq2SeqLM, AutoTokenizer, DataCollatorForSeq2Seq, Seq2SeqTrainer, Seq2SeqTrainingArguments, ) from transformers.trainer_callback import TrainerCallback def read_lines(path: Path) -> List[str]: with path.open("r", encoding="utf-8") as f: return [line.rstrip("\n") for line in f] def str2bool(value: str) -> bool: if isinstance(value, bool): return value value = value.lower() if value in {"yes", "true", "t", "1"}: return True if value in {"no", "false", "f", "0"}: return False raise argparse.ArgumentTypeError(f"Cannot interpret '{value}' as boolean.") def select_gpu(max_used_mb: int = 2000) -> Optional[str]: """Return GPU index whose current memory usage is below threshold.""" try: result = subprocess.run( [ "nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits", ], check=True, capture_output=True, text=True, ) except (subprocess.CalledProcessError, FileNotFoundError): return None for line in result.stdout.strip().splitlines(): if not line: continue idx_str, mem_str = [item.strip() for item in line.split(",")] try: mem_used = float(mem_str) except ValueError: continue if mem_used < max_used_mb: return idx_str return None def build_examples( prompts: List[str], texts: List[str], glosses: List[str], prefix: str, ) -> Tuple[List[Dict[str, str]], List[Dict[str, str]]]: assert len(prompts) == len(texts) == len(glosses), "Input files must align line-by-line" examples: List[Dict[str, str]] = [] metadata: List[Dict[str, str]] = [] for prompt, sent, gloss in zip(prompts, texts, glosses): gloss_clean = gloss.strip() if not gloss_clean or gloss_clean.lower() == "none": continue src = f"{prefix} prompt: {prompt.strip()} context: {sent.strip()}" examples.append({"input_text": src, "target_text": gloss_clean}) metadata.append( { "prompt": prompt.strip(), "text": sent.strip(), "gloss": gloss_clean, } ) return examples, metadata def tokenize_examples(tokenizer, examples, max_source_length: int, max_target_length: int): model_inputs = tokenizer( examples["input_text"], max_length=max_source_length, truncation=True, ) with tokenizer.as_target_tokenizer(): labels = tokenizer( examples["target_text"], max_length=max_target_length, truncation=True, ) model_inputs["labels"] = labels["input_ids"] return model_inputs def main(args: argparse.Namespace): if args.data_dir: base_dir = Path(args.data_dir) else: base_dir = Path(__file__).resolve().parent prompt_path = base_dir / "example_input.prompt" text_path = base_dir / "example_input.text" gloss_path = base_dir / "example_short.gloss" prompts = read_lines(prompt_path) texts = read_lines(text_path) glosses = read_lines(gloss_path) examples, metadata = build_examples( prompts, texts, glosses, prefix=args.task_prefix, ) if not examples: raise RuntimeError("No training examples remain after filtering gloss == 'none'.") combined = list(zip(examples, metadata)) rng = random.Random(args.seed) rng.shuffle(combined) if combined: examples, metadata = zip(*combined) examples = list(examples) metadata = list(metadata) else: examples, metadata = [], [] split_idx = int(len(examples) * args.train_ratio) train_examples = examples[:split_idx] eval_examples = examples[split_idx:] or examples[:1] # ensure non-empty eval set train_dataset = Dataset.from_list(train_examples) eval_dataset = Dataset.from_list(eval_examples) eval_metadata = metadata[split_idx:] or metadata[:1] if "CUDA_VISIBLE_DEVICES" not in os.environ: gpu_choice = select_gpu() if gpu_choice is not None: os.environ["CUDA_VISIBLE_DEVICES"] = gpu_choice output_root = Path(args.output_dir) if args.output_dir else base_dir / "t5_finetuned" output_root.mkdir(parents=True, exist_ok=True) best_dir = output_root / "best" tokenizer_source = best_dir if (best_dir / "tokenizer_config.json").exists() else args.model_name tokenizer = AutoTokenizer.from_pretrained(tokenizer_source) if (best_dir / "pytorch_model.bin").exists(): model_source = best_dir else: model_source = args.model_name model = AutoModelForSeq2SeqLM.from_pretrained(model_source) best_metric_path = best_dir / "metric.txt" initial_best_metric: Optional[float] = None if best_metric_path.exists(): try: content = best_metric_path.read_text().strip() if "=" in content: _, value = content.split("=", 1) else: value = content initial_best_metric = float(value) except ValueError: initial_best_metric = None resume_checkpoint = None if (best_dir / "trainer_state.json").exists(): resume_checkpoint = str(best_dir) tokenized_train = train_dataset.map( lambda batch: tokenize_examples( tokenizer, batch, args.max_source_length, args.max_target_length, ), batched=True, remove_columns=train_dataset.column_names, ) tokenized_eval = eval_dataset.map( lambda batch: tokenize_examples( tokenizer, batch, args.max_source_length, args.max_target_length, ), batched=True, remove_columns=eval_dataset.column_names, ) data_collator = DataCollatorForSeq2Seq(tokenizer, model=model) sample_metadata = list(eval_metadata) try: rouge = evaluate.load("rouge") except ImportError as exc: raise ImportError( "Using rouge metrics requires 'rouge_score' and 'nltk'. " "Install them via `pip install rouge_score nltk` and rerun." ) from exc def compute_bleu(eval_preds): preds, labels = eval_preds if isinstance(preds, tuple): preds = preds[0] decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) labels = np.where(labels != -100, labels, tokenizer.pad_token_id) decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) decoded_preds = [pred.strip().upper() for pred in decoded_preds] decoded_labels = [label.strip().upper() for label in decoded_labels] bleu = sacrebleu.corpus_bleu( decoded_preds, [decoded_labels], smooth_method="exp", smooth_value=1.0, force=True, ) rouge_scores = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) num_samples = min(4, len(decoded_preds), len(sample_metadata)) if num_samples: print("\n===== Sample Predictions =====") for idx in range(num_samples): meta = sample_metadata[idx] print(f"--- Sample {idx + 1} ---") print(f"Prompt: {meta['prompt']}") print(f"Text: {meta['text']}") print(f"Pred gloss: {decoded_preds[idx]}") print(f"GT gloss: {meta['gloss']}") if num_samples: print("=============================\n") metrics = { "bleu": bleu.score, "bleu1": bleu.precisions[0], "bleu2": bleu.precisions[1], "bleu3": bleu.precisions[2], "bleu4": bleu.precisions[3], "rouge1": rouge_scores.get("rouge1", 0.0), "rouge2": rouge_scores.get("rouge2", 0.0), "rougeL": rouge_scores.get("rougeL", 0.0), } return metrics training_args = Seq2SeqTrainingArguments( output_dir=str(output_root), per_device_train_batch_size=args.train_batch_size, per_device_eval_batch_size=args.eval_batch_size, learning_rate=args.learning_rate, weight_decay=args.weight_decay, num_train_epochs=1.0, max_steps=args.max_train_steps, evaluation_strategy="steps", eval_steps=args.eval_steps, logging_steps=args.loss_plot_steps, save_strategy="no", predict_with_generate=True, fp16=args.fp16, seed=args.seed, ) trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=tokenized_train, eval_dataset=tokenized_eval, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_bleu, ) class LossPlotCallback(TrainerCallback): def __init__(self, plot_dir: Path, history_path: Path, frequency: int): self.plot_dir = plot_dir self.frequency = max(1, frequency) self.history_path = history_path self.plot_path = self.plot_dir / "loss_curve.png" self.steps: List[int] self.losses: List[float] if history_path.exists(): data = np.load(history_path) self.steps = data.get("steps", np.array([], dtype=np.int64)).tolist() self.losses = data.get("losses", np.array([], dtype=np.float32)).tolist() else: self.steps = [] self.losses = [] self.plot_dir.mkdir(parents=True, exist_ok=True) def on_log(self, args, state, control, logs=None, **kwargs): if logs is None: return loss = logs.get("loss") if loss is None or state.global_step == 0: return self.steps.append(state.global_step) self.losses.append(loss) self._save_history() if state.global_step % self.frequency == 0: self._save_plot() def _save_history(self): np.savez( self.history_path, steps=np.array(self.steps, dtype=np.int64), losses=np.array(self.losses, dtype=np.float32), ) def _save_plot(self): if not self.steps: return plt.figure(figsize=(8, 5)) plt.plot(self.steps, self.losses, marker="o", linewidth=1) plt.title("Training Loss") plt.xlabel("Global Step") plt.ylabel("Loss") plt.grid(True, linestyle="--", alpha=0.5) plt.tight_layout() plt.savefig(self.plot_path) plt.close() class BestCheckpointCallback(TrainerCallback): def __init__( self, trainer: Seq2SeqTrainer, save_root: Path, tokenizer, metric_name: str, greater_is_better: bool, initial_best: Optional[float], save_interval: int, ): self.trainer = trainer self.save_root = save_root self.best_dir = self.save_root / "best" self.tokenizer = tokenizer self.metric_name = metric_name self.greater_is_better = greater_is_better self.best_metric: Optional[float] = initial_best self.save_interval = max(1, save_interval) def _is_better(self, value: float) -> bool: if self.best_metric is None: return True if self.greater_is_better: return value > self.best_metric return value < self.best_metric def on_evaluate(self, args, state, control, metrics=None, **kwargs): if metrics is None or self.metric_name not in metrics: return if state.global_step % self.save_interval != 0: return metric_val = metrics[self.metric_name] if not isinstance(metric_val, (int, float)): return if self._is_better(metric_val): self.best_metric = float(metric_val) self._save_checkpoint() def _save_checkpoint(self): self.best_dir.mkdir(parents=True, exist_ok=True) self.trainer.save_model(self.best_dir) self.trainer.state.save_to_json(str(self.best_dir / "trainer_state.json")) if self.trainer.optimizer is not None: torch.save(self.trainer.optimizer.state_dict(), self.best_dir / "optimizer.pt") if self.trainer.lr_scheduler is not None: torch.save(self.trainer.lr_scheduler.state_dict(), self.best_dir / "scheduler.pt") scaler = getattr(self.trainer, "scaler", None) if scaler is not None: torch.save(scaler.state_dict(), self.best_dir / "scaler.pt") self.tokenizer.save_pretrained(self.best_dir) with (self.best_dir / "metric.txt").open("w", encoding="utf-8") as f: f.write(f"{self.metric_name}={self.best_metric}\n") loss_dir = output_root / "loss_plots" loss_history_path = loss_dir / "loss_history.npz" trainer.add_callback(LossPlotCallback(loss_dir, loss_history_path, args.loss_plot_steps)) trainer.add_callback( BestCheckpointCallback( trainer, output_root, tokenizer, args.best_metric, args.greater_is_better, initial_best_metric, args.save_interval, ) ) train_kwargs = {} if resume_checkpoint: train_kwargs["resume_from_checkpoint"] = resume_checkpoint trainer.train(**train_kwargs) trainer.save_model(str(output_root)) tokenizer.save_pretrained(str(output_root)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Train T5 to translate prompt/text into gloss.") parser.add_argument( "--data_dir", type=str, default=None, help="Directory containing training files (defaults to this script's directory).", ) parser.add_argument( "--model_name", type=str, default="t5-base", help="HF model checkpoint to fine-tune", ) parser.add_argument( "--output_dir", type=str, default=None, help="Directory used by TrainingArguments for checkpoints (default: ./t5_finetuned next to this script)", ) parser.add_argument("--max_source_length", type=int, default=512) parser.add_argument("--max_target_length", type=int, default=128) parser.add_argument("--train_batch_size", type=int, default=32) parser.add_argument("--eval_batch_size", type=int, default=32) parser.add_argument("--learning_rate", type=float, default=5e-5) parser.add_argument("--weight_decay", type=float, default=0.01) parser.add_argument( "--max_train_steps", type=int, default=10000, help="Total optimizer steps to run; overrides epoch-based training.", ) parser.add_argument("--eval_steps", type=int, default=20) parser.add_argument("--fp16", action="store_true", help="Enable mixed precision") parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--loss_plot_steps", type=int, default=10, help="Frequency (in steps) to update/save training loss plot.", ) parser.add_argument( "--best_metric", type=str, default="bleu", help="Metric name used to decide best checkpoint.", ) parser.add_argument( "--greater_is_better", type=str2bool, default=True, help="Whether higher metric values are considered better when saving checkpoints.", ) parser.add_argument( "--save_interval", type=int, default=100, help="Only steps divisible by this value are eligible for checkpoint comparison/saving.", ) parser.add_argument( "--train_ratio", type=float, default=0.9, help="Fraction of filtered data used for training (rest for eval).", ) parser.add_argument("--task_prefix", type=str, default="translate prompt2gloss:") main(parser.parse_args())