"""Reproducible training script for Tamarillo pii-secrets-guard (ModernBertForTokenClassification). Selects the best checkpoint strictly by validation metrics (entity F1 with hard-negative FPR check) and writes clean safetensors release weights to --output-dir without leftover optimizer states. """ from __future__ import annotations import argparse import gc import json import os import shutil from pathlib import Path from typing import Any import numpy as np import torch from datasets import Dataset, concatenate_datasets, load_from_disk from seqeval.metrics import f1_score, precision_score, recall_score from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorForTokenClassification, Trainer, TrainingArguments, ) from taxonomy import BIO_LABELS, ID2LABEL, LABEL2ID def load_jsonl(path: Path) -> list[dict[str, Any]]: rows = [] with path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def align_char_spans_to_bio( text: str, spans: list[dict[str, Any]], offsets: list[tuple[int, int]], special_mask: list[int], ) -> list[int]: """ Exact character-offset to subword BIO tag alignment. First subword overlapping a span gets B-