"""Reproducible single-device training with account-level validation.""" import argparse from collections import Counter from contextlib import nullcontext from dataclasses import replace import hashlib import importlib.util import json import math import os from pathlib import Path import random import time import numpy as np import torch from transformers import AutoTokenizer from .config import VARIANTS from .data import CallEncoder, account_key, build_vocabulary, load_calls, split_calls, to_device from .inference import decode, load_checkpoint, save_checkpoint from .loss import fact_loss from .model import FactSetNet from .temporal import load_time_labels from compact_fact_extraction.normalization.catalog import ValueCatalog def write_json(path, value): path = Path(path) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8") temporary.replace(path) def save_training_state(path, optimizer, scaler, epoch, train_calls, best): """Atomically add restart state using tensors and weights_only-safe primitives.""" numpy_state = np.random.get_state() state = { "format_version": 1, "epoch": epoch, "optimizer": optimizer.state_dict(), "scaler": scaler.state_dict(), "python_rng": random.getstate(), "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [], "numpy_rng": { "algorithm": numpy_state[0], "keys": torch.tensor(numpy_state[1].astype(np.int64)), "position": numpy_state[2], "has_gauss": numpy_state[3], "cached_gauss": numpy_state[4], }, # Shuffling historically mutates the prior epoch's order. Preserve it. "train_order": [call["call_id"] for call in train_calls], "best": best, } path = Path(path) temporary = path.with_suffix(path.suffix + ".tmp") try: torch.save(state, temporary) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) def restore_training_state(state, optimizer, scaler, train_calls): if state.get("format_version") != 1: raise ValueError("Unsupported training state format") by_id = {call["call_id"]: call for call in train_calls} order = state["train_order"] if len(order) != len(by_id) or set(order) != set(by_id): raise ValueError("Checkpoint training calls do not match this run") train_calls[:] = [by_id[call_id] for call_id in order] optimizer.load_state_dict(state["optimizer"]) scaler.load_state_dict(state["scaler"]) random.setstate(state["python_rng"]) numpy_state = state["numpy_rng"] np.random.set_state((numpy_state["algorithm"], numpy_state["keys"].numpy().astype(np.uint32), numpy_state["position"], numpy_state["has_gauss"], numpy_state["cached_gauss"])) torch.set_rng_state(state["torch_rng"]) if state["cuda_rng"]: if not torch.cuda.is_available() or len(state["cuda_rng"]) != torch.cuda.device_count(): raise ValueError("Resuming CUDA training requires the same visible GPU count") torch.cuda.set_rng_state_all(state["cuda_rng"]) def validate_resume(saved, current): """Changing data or training settings starts a new experiment, not a resume.""" hashes = ("train_sha256", "dev_sha256", "dev_calib_sha256", "catalog_sha256", "temporal_labels_sha256", "metrics_sha256") arguments = ("seed", "dev_fraction", "limit", "accumulation", "learning_rate", "head_learning_rate", "amp", "gradient_checkpointing", "threshold", "min_temporal_recall", "min_state_accuracy", "no_fact_weight", "temporal_loss_weight", "date_loss_weight", "device", "calibration_thresholds", "ticket_states", "agreement_dates") changed = [key for key in hashes if saved.get(key) != current.get(key)] changed += [key for key in arguments if saved["arguments"].get(key) != current["arguments"].get(key)] if saved.get("torch_version") != current.get("torch_version"): changed.append("torch_version") if changed: raise ValueError("Resume settings changed: " + ", ".join(changed)) def load_evaluator(path): spec = importlib.util.spec_from_file_location("factsetnet_case_metrics", path) if spec is None or spec.loader is None: raise ValueError(f"Cannot load evaluator {path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) if hasattr(module, "load_catalog"): module.load_catalog(str(Path(path).parent / "catalog.json")) return module.evaluate def score_predictions(evaluator, gold, predicted): """Use exact official matching counts rather than the rounded P/R report.""" metrics = evaluator(gold, predicted) matcher = evaluator.__globals__.get("match_facts") if matcher is None: raise ValueError("Evaluator must expose official match_facts for exact checkpoint selection") matched = sum(len(matcher(call["facts"], predicted[call_id]["facts"])) for call_id, call in gold.items()) gold_count = sum(len(call["facts"]) for call in gold.values()) pred_count = sum(len(call["facts"]) for call in predicted.values()) metrics.update(n_matched_facts=matched, fact_f1=2 * matched / (gold_count + pred_count) if gold_count + pred_count else 0.0) return metrics def independent_accounts(**splits): """All held-out choices use account-independent, call-disjoint splits.""" names = list(splits) for i, left in enumerate(names): for right in names[i + 1:]: if {c["call_id"] for c in splits[left]} & {c["call_id"] for c in splits[right]}: raise ValueError(f"{left} and {right} call IDs overlap") if {account_key(c) for c in splits[left]} & {account_key(c) for c in splits[right]}: raise ValueError(f"{left} and {right} accounts overlap") @torch.inference_mode() def evaluate_thresholds(model, encoder, calls, device, evaluator, thresholds, *, catalog=None, ticket_states=False, agreement_dates=False, with_coverage=True): """One gold-free forward per call; thresholds differ only in decoding.""" model.eval() gold, predicted = {}, {threshold: {} for threshold in thresholds} coverage = Counter() for call in calls: clean = {key: value for key, value in call.items() if key != "facts"} encoded = to_device(encoder.encode(clean, with_targets=False), device) output = model(encoded) gold[call["call_id"]] = call for threshold in thresholds: facts = decode(output, encoded, encoder.vocabulary, threshold, catalog, ticket_states, agreement_dates=agreement_dates) predicted[threshold][call["call_id"]] = {"call_id": call["call_id"], "facts": facts} if with_coverage: # Reference labels are computed only after inference, separately. for name, labels in encoder.targets({**encoded, "call": call}).items(): coverage[name + "_labelled"] += int((labels >= 0).sum()) coverage[name + "_total"] += len(labels) results = {threshold: score_predictions(evaluator, gold, values) for threshold, values in predicted.items()} return results, predicted, dict(coverage) def evaluate(model, encoder, calls, device, evaluator, threshold, **decode_options): metrics, predictions, coverage = evaluate_thresholds( model, encoder, calls, device, evaluator, [threshold], **decode_options) return metrics[threshold], predictions[threshold], coverage def select_threshold(results): # Precision and then the stricter threshold settle exact F1 ties. return max(results, key=lambda t: (results[t]["fact_f1"], results[t]["fact_precision"], t)) def train(args): # Keep library callers compatible with the historical Namespace interface. args.dev_calib = getattr(args, "dev_calib", None) args.calibration_thresholds = getattr(args, "calibration_thresholds", [.3, .5, .65, .75, .85, .9, .95]) args.ticket_states = getattr(args, "ticket_states", False) args.agreement_dates = getattr(args, "agreement_dates", False) args.temporal_v2 = getattr(args, "temporal_v2", False) args.date_candidate_pool = getattr(args, "date_candidate_pool", "legacy") args.date_encoder = getattr(args, "date_encoder", "linear") args.date_span_features = getattr(args, "date_span_features", True) if args.epochs < 1 or args.accumulation < 1 or args.learning_rate <= 0 or args.head_learning_rate <= 0: raise ValueError("Epochs, accumulation and learning rates must be positive") if not 0 <= args.threshold <= 1: raise ValueError("Threshold must be in [0, 1]") if not 0 <= args.min_temporal_recall <= 1 or not 0 <= args.min_state_accuracy <= 1: raise ValueError("Metric floors must be in [0, 1]") if args.limit is not None and args.limit < 1: raise ValueError("Limit must be positive") if not math.isfinite(args.no_fact_weight) or args.no_fact_weight <= 0: raise ValueError("--no-fact-weight must be finite and positive") if any(not math.isfinite(weight) or weight < 0 for weight in (args.temporal_loss_weight, args.date_loss_weight)): raise ValueError("Loss weights must be finite and nonnegative") if args.resume and not (args.resume / "training_state.pt").is_file(): raise ValueError("Resume requires training_state.pt; older weights-only checkpoints cannot resume") if args.output.exists(): raise FileExistsError(f"Use a new run directory: {args.output}") if not args.calibration_thresholds or any(not math.isfinite(t) or not 0 <= t <= 1 for t in args.calibration_thresholds): raise ValueError("Calibration thresholds must be finite values in [0, 1]") if len(args.calibration_thresholds) != len(set(args.calibration_thresholds)): raise ValueError("Duplicate calibration thresholds") if args.dev_calib and not args.dev: raise ValueError("--dev-calib requires explicit independent --dev for checkpoint selection") if args.ticket_states and not args.catalog: raise ValueError("--ticket-states requires --catalog") random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed) torch.backends.cudnn.benchmark = False if args.device == "auto": args.device = "cuda" if torch.cuda.is_available() else "cpu" calls = load_calls(args.train) if args.dev: train_calls, dev_calls = calls, load_calls(args.dev) corpus = train_calls + dev_calls train_groups = {account_key(call) for call in train_calls} dev_groups = {account_key(call) for call in dev_calls} if train_groups & dev_groups: raise ValueError("Training and dev accounts overlap") else: corpus = calls train_calls, dev_calls = split_calls(calls, args.dev_fraction, args.seed) calib_calls = load_calls(args.dev_calib) if args.dev_calib else [] if calib_calls: independent_accounts(train=train_calls, dev_select=dev_calls, dev_calib=calib_calls) corpus += calib_calls if args.limit: train_calls, dev_calls = train_calls[:args.limit], dev_calls[:args.limit] calib_calls = calib_calls[:args.limit] temporal_labels = {} if args.temporal_labels: temporal_labels = load_time_labels(args.temporal_labels, corpus) if not any( label["kind"] != "fallback" for call in train_calls for label in temporal_labels.get(call["call_id"], {}).values() ): raise ValueError("Temporal span supervision is missing from the selected training split") config = VARIANTS[args.variant] if args.backbone: config = replace(config, backbone=args.backbone) config = replace(config, queries=args.queries, max_length=args.max_length, overlap=args.overlap, temporal_spans=bool(args.temporal_labels), date_candidate_pool='extended' if args.temporal_v2 else args.date_candidate_pool, date_encoder='nonlinear' if args.temporal_v2 else args.date_encoder, date_span_features=args.date_span_features) if max(len(call["facts"]) for call in train_calls + dev_calls) > config.queries: raise ValueError("Increase --queries to cover all annotated facts") catalog = json.loads(args.catalog.read_text(encoding="utf-8")) if args.catalog else None decode_options = {"catalog": ValueCatalog(catalog) if catalog else None, "ticket_states": args.ticket_states, "agreement_dates": args.agreement_dates} vocabulary = build_vocabulary(train_calls, catalog) if args.resume: model, tokenizer, resumed = load_checkpoint(args.resume, args.device) if model.config != config or resumed["vocabulary"] != vocabulary: raise ValueError("Resume model configuration or vocabulary differs from this run") else: tokenizer = AutoTokenizer.from_pretrained(config.backbone, use_fast=True) model = FactSetNet.pretrained(config, vocabulary).to(args.device) if args.gradient_checkpointing: model.backbone.gradient_checkpointing_enable() encoder = CallEncoder(tokenizer, config, vocabulary, temporal_labels) evaluator = load_evaluator(args.metrics_script) backbone_parameters = list(model.backbone.parameters()) backbone_ids = {id(parameter) for parameter in backbone_parameters} head_parameters = [parameter for parameter in model.parameters() if id(parameter) not in backbone_ids] optimizer = torch.optim.AdamW([ {"params": backbone_parameters, "lr": args.learning_rate}, {"params": head_parameters, "lr": args.head_learning_rate}, ], weight_decay=0.01) use_amp = args.amp and args.device.startswith("cuda") dtype = torch.bfloat16 if use_amp and torch.cuda.is_bf16_supported() else torch.float16 scaler = torch.amp.GradScaler("cuda", enabled=use_amp and dtype == torch.float16) metadata = { "seed": args.seed, "parameters": sum(parameter.numel() for parameter in model.parameters()), "backbone_revision": getattr(model.backbone.config, "_commit_hash", None), "train_sha256": hashlib.sha256(args.train.read_bytes()).hexdigest(), "metrics_sha256": hashlib.sha256(args.metrics_script.read_bytes()).hexdigest(), "arguments": {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()}, "torch_version": str(torch.__version__), } if args.dev: metadata["dev_sha256"] = hashlib.sha256(args.dev.read_bytes()).hexdigest() if args.dev_calib: metadata["dev_calib_sha256"] = hashlib.sha256(args.dev_calib.read_bytes()).hexdigest() metadata["selection_protocol"] = { "calibration": "complete facts on dev_calib" if calib_calls else "fixed --threshold", "checkpoint_selection": "complete facts on dev_select", "val_used": False, "decode_catalog": bool(catalog), "ticket_states": args.ticket_states, "agreement_dates": args.agreement_dates, } if args.catalog: metadata["catalog_sha256"] = hashlib.sha256(args.catalog.read_bytes()).hexdigest() if args.temporal_labels: metadata["temporal_labels_sha256"] = hashlib.sha256(args.temporal_labels.read_bytes()).hexdigest() start_epoch, best = 1, None if args.resume: validate_resume(resumed["metadata"], metadata) state = torch.load(args.resume / "training_state.pt", map_location="cpu", weights_only=True) if state["epoch"] != resumed["metadata"]["epoch"]: raise ValueError("Training state and model checkpoint epochs disagree") start_epoch = state["epoch"] + 1 if start_epoch > args.epochs: raise ValueError("--epochs is the total target epoch count and must exceed the resumed epoch") restore_training_state(state, optimizer, scaler, train_calls) if state["best"]: best = dict(state["best"]) previous = (args.resume.parent / best["checkpoint"]).resolve() best["checkpoint"] = os.path.relpath(previous, args.output.resolve()) metadata["resumed_from"] = str(args.resume.resolve()) args.output.mkdir(parents=True) write_json(args.output / "run.json", metadata) write_json(args.output / "split.json", { "train": [call["call_id"] for call in train_calls], "dev": [call["call_id"] for call in dev_calls], "dev_calib": [call["call_id"] for call in calib_calls], }) if best: write_json(args.output / "best.json", best) best_f1 = best["metrics"]["fact_f1"] if best else -1.0 for epoch in range(start_epoch, args.epochs + 1): model.train() if args.device.startswith("cuda"): torch.cuda.reset_peak_memory_stats(args.device) random.Random(args.seed + epoch).shuffle(train_calls) optimizer.zero_grad(set_to_none=True) loss_total, started = 0.0, time.monotonic() field_totals, field_counts = Counter(), Counter() for step, call in enumerate(train_calls): encoded = to_device(encoder.encode(call, with_targets=True), args.device) group_start = (step // args.accumulation) * args.accumulation group_size = min(args.accumulation, len(train_calls) - group_start) context = torch.autocast("cuda", dtype=dtype) if use_amp else nullcontext() with context: loss, terms = fact_loss( model(encoded), encoded["targets"], args.no_fact_weight, temporal_loss_weight=args.temporal_loss_weight, date_loss_weight=args.date_loss_weight) if not torch.isfinite(loss): raise FloatingPointError(f"Non-finite loss for {call['call_id']}") scaler.scale(loss / group_size).backward() logged = torch.stack([loss.detach(), *(value.detach() for value in terms.values())]) logged = logged.float().cpu().tolist() loss_total += logged[0] for name, value in zip(terms, logged[1:]): field_totals[name] += value field_counts[name] += 1 if (step + 1) % args.accumulation == 0 or step + 1 == len(train_calls): scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=not scaler.is_enabled()) scaler.step(optimizer) scaler.update() optimizer.zero_grad(set_to_none=True) if (step + 1) % args.log_every == 0: print(json.dumps({"epoch": epoch, "step": step + 1, "loss": loss_total / (step + 1), "train_seconds": time.monotonic() - started}), flush=True) threshold = args.threshold if calib_calls: calibration, _, _ = evaluate_thresholds( model, encoder, calib_calls, args.device, evaluator, args.calibration_thresholds, with_coverage=False, **decode_options) threshold = select_threshold(calibration) write_json(args.output / f"calibration-{epoch}.json", { "epoch": epoch, "split": "dev_calib", "threshold": threshold, "selection_metric": "fact_f1", "results": calibration, }) metrics, predictions, coverage = evaluate( model, encoder, dev_calls, args.device, evaluator, threshold, **decode_options) record = {"epoch": epoch, "train_loss": loss_total / len(train_calls), "elapsed_seconds": time.monotonic() - started, "metrics": metrics, "threshold": threshold, "target_coverage": coverage, "train_loss_by_field": {name: total / field_counts[name] for name, total in field_totals.items()}, "train_labelled_calls_by_field": dict(field_counts)} if args.device.startswith("cuda"): record["cuda_peak_allocated_bytes"] = torch.cuda.max_memory_allocated(args.device) record["cuda_peak_reserved_bytes"] = torch.cuda.max_memory_reserved(args.device) write_json(args.output / f"epoch-{epoch}.json", record) with (args.output / f"dev-{epoch}.jsonl").open("w", encoding="utf-8") as stream: for prediction in predictions.values(): stream.write(json.dumps(prediction, ensure_ascii=False) + "\n") checkpoint = args.output / f"checkpoint-{epoch}" save_checkpoint(checkpoint, model, tokenizer, vocabulary, {**metadata, "epoch": epoch, "metrics": metrics, "threshold": threshold}) eligible = ((metrics["temporal_recall"] or 0.0) >= args.min_temporal_recall and (metrics["state_accuracy"] or 0.0) >= args.min_state_accuracy) if eligible and metrics["fact_f1"] > best_f1: best_f1 = metrics["fact_f1"] best = {"checkpoint": f"checkpoint-{epoch}", "selection_metric": "fact_f1", "metrics": metrics, "threshold": threshold, "calibration_split": "dev_calib" if calib_calls else None} write_json(args.output / "best.json", best) save_training_state(checkpoint / "training_state.pt", optimizer, scaler, epoch, train_calls, best) print(json.dumps(record, ensure_ascii=False), flush=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("train", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--variant", choices=VARIANTS, default="base") parser.add_argument("--backbone", help="Override with a local backbone directory or model ID") parser.add_argument("--dev", type=Path) parser.add_argument("--dev-calib", type=Path, help="Independent calls for per-epoch full-fact threshold calibration") parser.add_argument("--calibration-thresholds", type=float, nargs="+", default=[.3, .5, .65, .75, .85, .9, .95]) parser.add_argument("--catalog", type=Path) parser.add_argument("--ticket-states", action="store_true") parser.add_argument("--agreement-dates", action="store_true") parser.add_argument("--temporal-labels", type=Path, help="JSONL with temporal span supervision") parser.add_argument("--temporal-v2",action="store_true",help="Extended calendar pool and nonlinear fact-conditioned date encoder") parser.add_argument("--date-candidate-pool",choices=['legacy','extended'],default='legacy') parser.add_argument("--date-encoder",choices=['linear','nonlinear'],default='linear') parser.add_argument("--no-date-span-features",dest="date_span_features",action="store_false", help="Zero only pooled time-expression features in the nonlinear date encoder") parser.add_argument("--resume", type=Path, help="Resume an epoch checkpoint into a new output directory; --epochs is total") parser.add_argument("--dev-fraction", type=float, default=0.15) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--epochs", type=int, default=3) parser.add_argument("--accumulation", type=int, default=16) parser.add_argument("--learning-rate", type=float, default=2e-5) parser.add_argument("--head-learning-rate", type=float, default=1e-4) parser.add_argument("--no-fact-weight", type=float, default=0.1) parser.add_argument("--temporal-loss-weight", type=float, default=1.0) parser.add_argument("--date-loss-weight", type=float, default=1.0) parser.add_argument("--queries", type=int, default=16) parser.add_argument("--max-length", type=int, default=512) parser.add_argument("--overlap", type=int, default=128) parser.add_argument("--device", default="auto") parser.add_argument("--amp", action="store_true") parser.add_argument("--gradient-checkpointing", action="store_true") parser.add_argument("--threshold", type=float, default=0.5) parser.add_argument("--min-temporal-recall", type=float, default=0.0) parser.add_argument("--min-state-accuracy", type=float, default=0.0) parser.add_argument("--limit", type=int, help="Limit each split for smoke testing") parser.add_argument("--log-every", type=int, default=25) parser.add_argument("--metrics-script", type=Path, default=Path("МТС MWS CompactFactExtraction/Данные кейса/case_metrics.py")) args = parser.parse_args() if args.log_every < 1: parser.error("--log-every must be positive") train(args) if __name__ == "__main__": main()