#!/usr/bin/env python3 """Nested law-family OOF hard-negative LoRA cross-encoder control for DRiLL.""" from __future__ import annotations import argparse import hashlib import json import math import platform import random import sys import time from datetime import datetime, timezone from pathlib import Path import numpy as np import torch import torch.nn.functional as F from peft import ( LoraConfig, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict, ) from torch.utils.data import DataLoader, Dataset from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, ) REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT / "src")) from scripts.run_drill_graph_evaluation import ( # noqa: E402 DEFAULT_SEEDS, RERANKER_NAME, RERANKER_REVISION, _candidate_labels, _ranking_observations, _selection_metrics, _stable_candidate_rankings, apply_score_threshold, build_gold_document_component_folds, select_f2_threshold, ) from scripts.run_static_benchmark import resolve_device # noqa: E402 from telen.drill_graph import load_drill_graph_dataset # noqa: E402 from telen.static_benchmark import ( # noqa: E402 paired_bootstrap_difference, sha256_file, ) class PairDataset(Dataset): def __init__(self, examples: list[tuple[int, int, float]]) -> None: self.examples = examples def __len__(self) -> int: return len(self.examples) def __getitem__(self, index: int) -> tuple[int, int, float]: return self.examples[index] def build_hard_negative_examples( query_indices: np.ndarray, candidates: np.ndarray, labels: np.ndarray, *, negatives_per_positive: int, ) -> tuple[list[tuple[int, int, float]], dict[str, int]]: """Use deterministic top-RRF negatives without duplicating qrel pairs.""" if candidates.shape != labels.shape or negatives_per_positive < 1: raise ValueError("candidate labels and positive negative count are required") examples: list[tuple[int, int, float]] = [] eligible = 0 missing_positive = 0 for query_index in map(int, query_indices): positives = [ int(aid) for aid, label in zip( candidates[query_index], labels[query_index], strict=True ) if label > 0 ] negatives = [ int(aid) for aid, label in zip( candidates[query_index], labels[query_index], strict=True ) if label == 0 ] if not positives: missing_positive += 1 continue eligible += 1 for positive_index, positive in enumerate(positives): examples.append((query_index, positive, 1.0)) start = positive_index * negatives_per_positive selected = [ negatives[(start + offset) % len(negatives)] for offset in range(min(negatives_per_positive, len(negatives))) ] examples.extend((query_index, aid, 0.0) for aid in selected) return examples, { "eligible_query_count": eligible, "queries_without_candidate_positive": missing_positive, "training_pair_count": len(examples), "positive_pair_count": sum(label == 1.0 for *_pair, label in examples), "negative_pair_count": sum(label == 0.0 for *_pair, label in examples), } def _build_model(args: argparse.Namespace, device: torch.device): dtype = torch.bfloat16 if device.type == "cuda" else torch.float32 base = AutoModelForSequenceClassification.from_pretrained( args.model_name, revision=args.model_revision, local_files_only=True, dtype=dtype, ) configuration = LoraConfig( r=args.lora_rank, lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, target_modules=["query", "value"], bias="none", task_type="SEQ_CLS", modules_to_save=["classifier"], ) model = get_peft_model(base, configuration).to(device) if args.gradient_checkpointing: model.gradient_checkpointing_enable() model.enable_input_require_grads() model.config.use_cache = False return model def _collate(tokenizer, retrieval, max_length: int): def collate(rows): pairs = [ (retrieval.query_texts[qid], retrieval.corpus_texts[aid]) for qid, aid, _label in rows ] encoded = tokenizer( pairs, padding=True, truncation=True, max_length=max_length, return_tensors="pt", ) encoded["labels"] = torch.asarray( [label for _qid, _aid, label in rows], dtype=torch.float32 ) return encoded return collate def train_fold( model, tokenizer, retrieval, examples: list[tuple[int, int, float]], *, seed: int, args: argparse.Namespace, device: torch.device, ) -> dict[str, object]: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if device.type == "cuda": torch.cuda.manual_seed_all(seed) generator = torch.Generator().manual_seed(seed) loader = DataLoader( PairDataset(examples), batch_size=args.training_batch_size, shuffle=True, generator=generator, num_workers=0, collate_fn=_collate(tokenizer, retrieval, args.max_length), ) optimizer = torch.optim.AdamW( (parameter for parameter in model.parameters() if parameter.requires_grad), lr=args.learning_rate, weight_decay=args.weight_decay, ) optimizer_steps = math.ceil(len(loader) / args.gradient_accumulation_steps) total_steps = optimizer_steps * args.epochs scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=max(1, round(total_steps * args.warmup_ratio)), num_training_steps=total_steps, ) model.train() optimizer.zero_grad(set_to_none=True) losses: list[float] = [] started = time.perf_counter() completed_steps = 0 for _epoch in range(args.epochs): for batch_index, batch in enumerate(loader): labels = batch.pop("labels").to(device) encoded = {name: value.to(device) for name, value in batch.items()} with torch.autocast( device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda", ): logits = model(**encoded, return_dict=True).logits.view(-1).float() loss = F.binary_cross_entropy_with_logits( logits, labels, pos_weight=torch.tensor( float(args.negatives_per_positive), device=device ), ) scaled_loss = loss / args.gradient_accumulation_steps scaled_loss.backward() losses.append(float(loss.detach().cpu())) should_step = ( (batch_index + 1) % args.gradient_accumulation_steps == 0 or batch_index + 1 == len(loader) ) if should_step: torch.nn.utils.clip_grad_norm_( (parameter for parameter in model.parameters() if parameter.requires_grad), args.max_gradient_norm, ) optimizer.step() scheduler.step() optimizer.zero_grad(set_to_none=True) completed_steps += 1 return { "training_pair_count": len(examples), "optimizer_step_count": completed_steps, "epochs": args.epochs, "mean_batch_loss": float(np.mean(losses)), "final_batch_loss": losses[-1], "runtime_seconds": time.perf_counter() - started, "trainable_parameter_count": sum( parameter.numel() for parameter in model.parameters() if parameter.requires_grad ), } def score_queries( model, tokenizer, retrieval, candidates: np.ndarray, query_indices: np.ndarray, *, args: argparse.Namespace, device: torch.device, ) -> np.ndarray: output = np.empty((len(query_indices), candidates.shape[1]), dtype=np.float32) positions = [ (local_query, rank) for local_query in range(len(query_indices)) for rank in range(candidates.shape[1]) ] model.eval() with torch.inference_mode(): for start in range(0, len(positions), args.inference_batch_size): batch_positions = positions[start : start + args.inference_batch_size] pairs = [] for local_query, rank in batch_positions: query_index = int(query_indices[local_query]) aid = int(candidates[query_index, rank]) pairs.append( (retrieval.query_texts[query_index], retrieval.corpus_texts[aid]) ) encoded = tokenizer( pairs, padding=True, truncation=True, max_length=args.max_length, return_tensors="pt", ).to(device) with torch.autocast( device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda", ): values = model(**encoded, return_dict=True).logits.view(-1).float() for (local_query, rank), value in zip( batch_positions, values.cpu().numpy(), strict=True ): output[local_query, rank] = value return output def _state_sha256(state: dict[str, torch.Tensor]) -> str: digest = hashlib.sha256() for name, value in sorted(state.items()): digest.update(name.encode("utf-8")) tensor = value.detach().cpu().contiguous() if tensor.dtype == torch.bfloat16: tensor = tensor.float() digest.update(tensor.numpy().tobytes()) return digest.hexdigest() def run(args: argparse.Namespace) -> dict: if len(args.seeds) != 1: raise ValueError("the predeclared strong control uses exactly one seed") dataset = load_drill_graph_dataset(args.corpus, args.questions) retrieval = dataset.retrieval candidates = np.asarray(np.load(args.candidates)[:, : args.depth], dtype=np.int32) labels = _candidate_labels(candidates, retrieval.relevant_indices) total_relevant = np.asarray( list(map(len, retrieval.relevant_indices)), dtype=np.float32 ) folds, fold_audit = build_gold_document_component_folds( retrieval.relevant_indices, dataset.article_document_ids, args.fold_count ) graph_predictions = np.load(args.graph_predictions) if not np.array_equal(candidates, graph_predictions["candidates"]): raise ValueError("graph control and LoRA control candidate pools differ") graph_scores = np.asarray( graph_predictions["scores_learned_graph_residual"], dtype=np.float32 ) device = resolve_device(args.device) tokenizer = AutoTokenizer.from_pretrained( args.model_name, revision=args.model_revision, local_files_only=True, ) oof_scores = np.zeros_like(labels, dtype=np.float32) oof_selected = np.zeros_like(labels, dtype=bool) training_receipts = [] fold_artifacts = [] args.checkpoint_dir.mkdir(parents=True, exist_ok=True) args.score_dir.mkdir(parents=True, exist_ok=True) seed = args.seeds[0] for test_fold in range(args.fold_count): development_fold = (test_fold + 1) % args.fold_count test_indices = np.flatnonzero(folds == test_fold) development_indices = np.flatnonzero(folds == development_fold) training_indices = np.flatnonzero( (folds != test_fold) & (folds != development_fold) ) checkpoint_path = args.checkpoint_dir / f"fold-{test_fold}.pt" test_score_path = args.score_dir / f"fold-{test_fold}-test.npy" development_score_path = args.score_dir / f"fold-{test_fold}-development.npy" model = _build_model(args, device) if checkpoint_path.is_file(): checkpoint = torch.load( checkpoint_path, map_location="cpu", weights_only=False ) if checkpoint.get("artifact_type") != "drill_lora_cross_encoder_fold": raise ValueError("unexpected LoRA checkpoint artifact") set_peft_model_state_dict(model, checkpoint["adapter_state"]) pair_audit = checkpoint["pair_audit"] training = checkpoint["training"] else: examples, pair_audit = build_hard_negative_examples( training_indices, candidates, labels, negatives_per_positive=args.negatives_per_positive, ) training = train_fold( model, tokenizer, retrieval, examples, seed=seed + test_fold * 1009, args=args, device=device, ) adapter_state = { name: value.detach().cpu().clone() for name, value in get_peft_model_state_dict(model).items() } torch.save( { "artifact_type": "drill_lora_cross_encoder_fold", "test_fold": test_fold, "development_fold": development_fold, "seed": seed, "adapter_state": adapter_state, "adapter_state_sha256": _state_sha256(adapter_state), "pair_audit": pair_audit, "training": training, }, checkpoint_path, ) if test_score_path.is_file(): test_scores = np.load(test_score_path) else: test_scores = score_queries( model, tokenizer, retrieval, candidates, test_indices, args=args, device=device, ) np.save(test_score_path, test_scores) if development_score_path.is_file(): development_scores = np.load(development_score_path) else: development_scores = score_queries( model, tokenizer, retrieval, candidates, development_indices, args=args, device=device, ) np.save(development_score_path, development_scores) threshold, development_decision = select_f2_threshold( development_scores, labels[development_indices], total_relevant[development_indices], maximum_results=args.maximum_returned_articles, ) oof_scores[test_indices] = test_scores oof_selected[test_indices] = apply_score_threshold( test_scores, threshold, maximum_results=args.maximum_returned_articles, ) training_receipts.append( { "test_fold": test_fold, "development_fold": development_fold, "training_fold_count": args.fold_count - 2, "training_query_count": int(len(training_indices)), "development_query_count": int(len(development_indices)), "test_query_count": int(len(test_indices)), "pair_audit": pair_audit, "training": training, "development_threshold": threshold, "development_decision": development_decision, } ) fold_artifacts.append( { "test_fold": test_fold, "checkpoint": str(checkpoint_path), "checkpoint_sha256": sha256_file(checkpoint_path), "test_scores": str(test_score_path), "test_scores_sha256": sha256_file(test_score_path), "development_scores": str(development_score_path), "development_scores_sha256": sha256_file(development_score_path), } ) print( json.dumps( { "completed_fold": test_fold, "test_queries": len(test_indices), "training_pairs": pair_audit["training_pair_count"], } ), flush=True, ) del model if device.type == "cuda": torch.cuda.empty_cache() rankings = { "hard_negative_lora_cross_encoder": _stable_candidate_rankings( candidates, oof_scores, retrieval.corpus_ids ), "learned_graph_residual": _stable_candidate_rankings( candidates, graph_scores, retrieval.corpus_ids ), } results = {} observations = {} for name, ranking in rankings.items(): results[name], observations[name] = _ranking_observations( ranking, retrieval.relevant_indices ) lora_selection, lora_selection_observations = _selection_metrics( oof_selected, labels, total_relevant ) comparison = { metric: paired_bootstrap_difference( observations["hard_negative_lora_cross_encoder"][metric], observations["learned_graph_residual"][metric], samples=args.bootstrap_samples, seed=args.bootstrap_seed, ) for metric in ("ndcg_at_10", "recall_at_2", "query_f2_at_2") } ndcg_credit = comparison["ndcg_at_10"] graph_beats_control = bool( ndcg_credit["observed_difference"] > 0 and ndcg_credit["confidence_low"] > 0 ) prediction_path = args.score_dir / "drill-lora-cross-encoder-oof.npz" np.savez_compressed( prediction_path, candidates=candidates, folds=folds, labels=labels, scores_hard_negative_lora_cross_encoder=oof_scores, selected_hard_negative_lora_cross_encoder=oof_selected, ) receipt = { "schema_version": 1, "artifact_type": "drill_law_family_nested_oof_hard_negative_lora_cross_encoder", "generated_at": datetime.now(timezone.utc).isoformat(), "claim_status": ( "learned_graph_beats_finetuned_text_control" if graph_beats_control else "learned_graph_does_not_beat_finetuned_text_control" ), "protocol": { "candidate_pool": "RRF(BM25, BGE-M3) top 100 shared with graph control", "split": "same five gold-law-family components; test and next fold excluded from every LoRA fit", "negative_sampling": "deterministic top-RRF non-qrels per candidate-positive qrel", "model_selection": "none; fixed one-epoch configuration", "f2_threshold": "selected only on the nested development fold", "qrels_used_for_candidate_generation": False, }, "dataset_audit": retrieval.audit, "split_audit": fold_audit, "configuration": { "model": args.model_name, "revision": args.model_revision, "max_length": args.max_length, "lora_rank": args.lora_rank, "lora_alpha": args.lora_alpha, "lora_dropout": args.lora_dropout, "target_modules": ["query", "value"], "classifier_trainable": True, "negatives_per_positive": args.negatives_per_positive, "epochs": args.epochs, "learning_rate": args.learning_rate, "weight_decay": args.weight_decay, "effective_batch_size": args.training_batch_size * args.gradient_accumulation_steps, "warmup_ratio": args.warmup_ratio, "seed": seed, "no_hyperparameter_sweep": True, "device": str(device), }, "results": results, "official_f2_decision": { "hard_negative_lora_cross_encoder": lora_selection, "maximum_returned_articles": args.maximum_returned_articles, }, "learned_graph_minus_finetuned_text": comparison, "strong_text_control_gate": { "graph_beats_control": graph_beats_control, "ndcg_at_10": ndcg_credit, }, "training_receipts": training_receipts, "artifacts": { "folds": fold_artifacts, "oof_predictions": { "path": str(prediction_path), "sha256": sha256_file(prediction_path), }, "graph_predictions": { "path": str(args.graph_predictions), "sha256": sha256_file(args.graph_predictions), }, }, "limitations": [ "LoRA adapts a strong pretrained cross-encoder but is not full-parameter reranker fine-tuning.", "One fixed seed is used for this expensive adversarial control; the graph treatment retains its three-seed ensemble.", "Organizer private labels are unavailable, so the comparison is nested OOF on public training questions and is not a leaderboard result.", ], "environment": { "python": platform.python_version(), "numpy": np.__version__, "torch": torch.__version__, }, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text( json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" ) return receipt def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--corpus", type=Path, default=REPO_ROOT / "tmp/telen/drill-public/legal-corpus/data/train-00000-of-00001.parquet", ) parser.add_argument( "--questions", type=Path, default=REPO_ROOT / "tmp/telen/drill-public/train/data/train-00000-of-00001.parquet", ) cache = REPO_ROOT / "tmp/telen/static-benchmarks/cache/drill" parser.add_argument("--candidates", type=Path, default=cache / "drill-rrf-top100.npy") parser.add_argument( "--graph-predictions", type=Path, default=cache / "drill-rrf-graph-semantic-rank64-oof-predictions.npz", ) parser.add_argument( "--checkpoint-dir", type=Path, default=REPO_ROOT / "tmp/telen/drill-lora-control/checkpoints", ) parser.add_argument( "--score-dir", type=Path, default=REPO_ROOT / "tmp/telen/drill-lora-control/scores", ) parser.add_argument( "--output", type=Path, default=REPO_ROOT / "research/results/telen_drill_lora_cross_encoder_oof_2026-08-29.json", ) parser.add_argument("--model-name", default=RERANKER_NAME) parser.add_argument("--model-revision", default=RERANKER_REVISION) parser.add_argument("--depth", type=int, default=100) parser.add_argument("--fold-count", type=int, default=5) parser.add_argument("--seeds", type=int, nargs="+", default=[DEFAULT_SEEDS[0]]) parser.add_argument("--max-length", type=int, default=384) parser.add_argument("--lora-rank", type=int, default=8) parser.add_argument("--lora-alpha", type=int, default=16) parser.add_argument("--lora-dropout", type=float, default=0.05) parser.add_argument("--negatives-per-positive", type=int, default=7) parser.add_argument("--epochs", type=int, default=1) parser.add_argument("--learning-rate", type=float, default=1e-4) parser.add_argument("--weight-decay", type=float, default=0.01) parser.add_argument("--warmup-ratio", type=float, default=0.1) parser.add_argument("--training-batch-size", type=int, default=16) parser.add_argument("--gradient-accumulation-steps", type=int, default=2) parser.add_argument("--max-gradient-norm", type=float, default=1.0) parser.add_argument("--inference-batch-size", type=int, default=64) parser.add_argument("--maximum-returned-articles", type=int, default=10) parser.add_argument("--gradient-checkpointing", action=argparse.BooleanOptionalAction, default=True) parser.add_argument("--bootstrap-samples", type=int, default=10_000) parser.add_argument("--bootstrap-seed", type=int, default=20260829) parser.add_argument("--device", default="auto") return parser.parse_args() if __name__ == "__main__": payload = run(parse_args()) print( json.dumps( { "claim_status": payload["claim_status"], "results": payload["results"], "strong_text_control_gate": payload["strong_text_control_gate"], }, ensure_ascii=False, indent=2, ) )