#!/usr/bin/env python3 """ Heterogeneous Ensemble Distillation Generator This script takes a dataset and an ensemble configuration (JSON), trains K-Fold Out-Of-Fold (OOF) models for each configuration, mathematically merges their probability distributions (handling 2-stage Unknown vs Known logic), and exports a Parquet file with generated soft labels. Usage: python scripts/ensemble_distillation_generator.py \ --data_path data/dist_to_main_street.parquet \ --text_col text \ --label_col dist_to_main_street \ --mapping_dict_path configs/distance_mapping.json \ --unknown_label_value UNKNOWN \ --ordinal_num_classes 5 \ --ensemble_config_path configs/ce_ensemble.json \ --artifacts_dir experiments/ce_v1/artifacts \ --ensemble_output_path experiments/ce_v1/oof_predictions.parquet \ --metadata_path experiments/ce_v1/metadata.json # Outputs written to experiments/ce_v1/: # artifacts/ — fold checkpoints, one dir per model # oof_predictions.parquet — OOF probability columns # metadata.json — model names + OOF F1 scores # run_config.json — frozen snapshot of input config + CLI args # ensemble_log_*.txt — training log # # Input configs/ce_ensemble.json is NEVER modified. # Resume a partial run by re-running with the same command — # models with existing artifacts are skipped automatically. """ # ============================================================================= # LABEL MAPPING CONVENTION (read this before creating a new task!) # # The --mapping_dict_path json MUST contain EVERY label value present in the # data, in this form (example from condition_tier): # # { "N": -1, "D": 1, "C": 2, "B": 3, "A": 4 } # # * UNKNOWN class -> value -1 (sentinel: "not part of the ordinal scale"). # It must ALSO be named via --unknown_label_value. Omitting it from the # mapping makes label lookup produce NaN and crashes at astype(int). # * Known classes -> 1-indexed integers whose ORDER defines the ordinal # scale (1 = one end, N = the other; e.g. worst -> best). # # OUTPUT COLUMN ORDER produced everywhere downstream (oof_probs.npy, # *_logprob_* columns, soft labels, deployment prob_* columns): # # [ known classes sorted by mapping value ASCENDING, then UNKNOWN last ] # # e.g. condition_tier: [D, C, B, A, N] # dist_to_main_street: [ON_MAIN_STREET, ADJACENT, NEAR, MODERATE, FAR, UNKNOWN] # # Any consumer that hard-codes a class list must match this order exactly. # (Forensic note: the May-2026 condition_tier "phobert collapse", F1 0.087, # was an eval comparing against this order REVERSED; true F1 was 0.9008.) # ============================================================================= import signal import atexit import pickle import matplotlib.pyplot as plt import seaborn as sns import argparse import gc import json import warnings import sys import copy import shutil from pathlib import Path import numpy as np import pandas as pd import os # Reduce CUDA allocator fragmentation (mid-run OOM with dynamic-padding batches # on tight GPUs). Must be set before torch initialises CUDA; a value already # set in the shell takes precedence. os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import torch import torch.nn as nn from datasets import Dataset import datasets from sklearn.metrics import accuracy_score, precision_recall_fscore_support, mean_absolute_error from sklearn.preprocessing import StandardScaler from sklearn.utils.class_weight import compute_class_weight from sklearn.model_selection import StratifiedKFold from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.calibration import CalibratedClassifierCV from scipy.sparse import hstack, csr_matrix from torch.utils.data import WeightedRandomSampler import lightgbm as lgb from transformers import ( AutoModelForSequenceClassification, AutoModel, AutoTokenizer, EarlyStoppingCallback, Trainer, TrainingArguments, TrainerCallback, ) warnings.filterwarnings("ignore") # ============================================================================= # CLEAN LOGGER # ============================================================================= import re from datetime import datetime class LoggerTee(object): def __init__(self, filename, mode="a"): self.terminal = sys.stdout self.log = open(filename, mode) self.line_buffer = "" self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') self.tqdm_pattern = re.compile(r'\b\d+%\s*\|') def write(self, message): self.terminal.write(message) for char in message: if char == '\r': self.line_buffer = "" elif char == '\n': clean_line = self.ansi_escape.sub('', self.line_buffer) if self.tqdm_pattern.search(clean_line): if "100%|" not in clean_line.replace(" ", ""): self.line_buffer = "" continue self.log.write(clean_line + '\n') self.log.flush() self.line_buffer = "" else: self.line_buffer += char def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return self.terminal.isatty() # Log file starts in cwd (args not parsed yet); main() moves it into artifacts_dir. timestamp = datetime.now().strftime("%Y%m%d_%H%M") log_filename = f"ensemble_log_{timestamp}.txt" sys.stdout = LoggerTee(filename=log_filename) sys.stderr = sys.stdout # ============================================================================= # ARGUMENT PARSING # ============================================================================= def parse_args(): parser = argparse.ArgumentParser(description="Generate Ensemble Soft Labels via K-Fold OOF Predictions.") # --- Data --- parser.add_argument("--data_path", type=str, required=True) parser.add_argument("--text_col", type=str, required=True) parser.add_argument("--label_col", type=str, required=True) parser.add_argument("--mapping_dict_path", type=str, required=True) parser.add_argument("--unknown_label_value", type=str, default="N") parser.add_argument("--ordinal_num_classes", type=int, required=True) parser.add_argument("--training_mode", type=str, default="kfold", choices=["kfold", "final"], help="kfold: K-fold CV producing OOF predictions (default, " "resource-heavy at serving: K checkpoints per model). " "final: ONE stratified holdout of --val_rows_per_class " "rows per class; each model trains once on the rest and " "is saved under /final/model/ — 1/K serving " "cost. Honest F1 is measured on the holdout; the output " "parquet gains an __is_holdout column (fit the meta-" "learner on those rows only).") parser.add_argument("--val_rows_per_class", type=int, default=50, help="Holdout size per class for --training_mode final.") parser.add_argument("--ordinal_min_label", type=int, default=1) # --- Ensemble structure --- parser.add_argument("--ensemble_k_folds", type=int, default=5) parser.add_argument("--ensemble_config_path", type=str, required=True) parser.add_argument("--ensemble_output_path", type=str, default="ensemble_soft_labels.parquet") parser.add_argument("--artifacts_dir", type=str, default="ensemble_artifacts") parser.add_argument("--metadata_path", type=str, default="ensemble_metadata.json") parser.add_argument("--soft_label_path", type=str, default=None, help="Path to a processed ensemble parquet (output of --mode process) " "that contains final_logprob_ columns. Required when any " "model config has loss_type=kl.") parser.add_argument("--artifact_suffix", type=str, default=None, help="Suffix appended to artifacts_dir, metadata_path, and " "ensemble_output_path. E.g. --artifact_suffix condition_tier " "gives ensemble_artifacts_condition_tier/, " "ensemble_metadata_condition_tier.json, etc.") # --- Global training defaults (all overridable per-model in JSON) --- parser.add_argument("--max_length", type=int, default=256) parser.add_argument("--batch_size", type=int, default=8) parser.add_argument("--max_steps", type=int, default=10000) parser.add_argument("--eval_steps", type=int, default=200) parser.add_argument("--learning_rate", type=float, default=2e-5) parser.add_argument("--early_stopping_patience", type=int, default=5) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--warmup_steps", type=int, default=0) parser.add_argument("--weight_decay", type=float, default=0.01) parser.add_argument("--adam_epsilon", type=float, default=1e-6, help="Adam epsilon (floor on second-moment denominator). " "1e-6 (vs PyTorch default 1e-8) prevents Adam blow-up when " "gradients stay near-zero for many steps (e.g. saturated ordinal " "BCE), which would otherwise let v̂→0 and cause enormous effective " "weight updates when gradients eventually become non-trivial.") parser.add_argument("--max_grad_norm", type=float, default=1.0) parser.add_argument("--label_smoothing", type=float, default=0.0, help="Label smoothing factor (0.0 = off). Recommended: 0.05-0.1 for noisy tasks.") parser.add_argument("--lr_scheduler_type", type=str, default="linear", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup", "inverse_sqrt"], help="LR scheduler. 'cosine' is generally more stable than 'linear' for long runs.") parser.add_argument("--class_balancing", type=str, choices=["none", "weighted", "sampler"], default="weighted", help="Global default. Override per-model with 'class_balancing' in JSON config.") parser.add_argument("--freeze_layers", type=int, default=0, help="Number of encoder layers to freeze from the bottom. 0 = no freezing.") # --- Distillation remedies --- parser.add_argument("--mode", type=str, choices=["generate", "process", "generate_and_process"], default="generate_and_process") parser.add_argument("--alpha_correct", type=float, default=0.95, help="Weight of the model's probabilities when it predicts the correct class.") parser.add_argument("--alpha_incorrect", type=float, default=0.10, help="Weight of the model's probabilities when it predicts the wrong class.") parser.add_argument("--temperature", type=float, default=1.0) parser.add_argument("--entropy_threshold", type=float, default=None) parser.add_argument("--use_f1_weights", action="store_true") return parser.parse_args() # ============================================================================= # UTILITIES & MATH # ============================================================================= def batch_ordinal_encoding_to_labels(encodings: np.ndarray, threshold: float = 0.5) -> np.ndarray: predictions = (encodings > threshold).astype(int) return predictions.sum(axis=1) def load_mapping(mapping_path: str) -> dict: with open(mapping_path, "r", encoding="utf-8") as f: return json.load(f) def ordinal_logits_to_probabilities(logits: np.ndarray) -> np.ndarray: cumulative_probs = 1.0 / (1.0 + np.exp(-logits)) batch_size, num_thresholds = cumulative_probs.shape num_classes = num_thresholds + 1 exact_probs = np.zeros((batch_size, num_classes)) exact_probs[:, 0] = 1.0 - cumulative_probs[:, 0] for i in range(1, num_thresholds): exact_probs[:, i] = cumulative_probs[:, i-1] - cumulative_probs[:, i] exact_probs[:, -1] = cumulative_probs[:, -1] exact_probs = np.clip(exact_probs, 1e-7, 1.0) return exact_probs / exact_probs.sum(axis=1, keepdims=True) def compute_class_weights_from_labels( labels: np.ndarray, dampening: str | float = "none" ) -> torch.Tensor: unique_classes = np.unique(labels) class_weights = compute_class_weight( class_weight="balanced", classes=unique_classes, y=labels) if dampening == "none": pass elif dampening == "sqrt": class_weights = np.sqrt(class_weights) elif isinstance(dampening, (int, float)) and dampening != 1.0: class_weights = np.power(class_weights, float(dampening)) else: raise ValueError(f"class_weight_dampening must be 'none', 'sqrt', or a float. Got: {dampening}") # Re-normalise so the mean weight stays ~1.0, preserving loss scale class_weights = class_weights / class_weights.mean() return torch.tensor(class_weights, dtype=torch.float32) def compute_ordinal_pos_weights(labels: np.ndarray, num_thresholds: int, dampening: str = "none") -> torch.Tensor: """ Compute per-threshold positive weights for BCEWithLogitsLoss. For threshold i, the binary question is 'label > i?'. pos_weight[i] = count(label <= i) / count(label > i) dampening: 'none' = raw ratio, 'sqrt' = square-rooted, float = that power. """ pos_weights = [] for i in range(num_thresholds): n_pos = np.sum(labels > i) n_neg = np.sum(labels <= i) if n_pos == 0: pos_weights.append(1.0) else: w = n_neg / n_pos if dampening == "sqrt": w = np.sqrt(w) elif dampening != "none": w = w ** float(dampening) pos_weights.append(w) return torch.tensor(pos_weights, dtype=torch.float32) class WeightWarmupCallback(TrainerCallback): """ Defers applying class weights to the loss until `warmup_steps` have passed. Prevents the random head from ping-ponging between trivial single-class solutions driven by large minority-class gradients in early training. The trainer reference is injected after trainer construction. """ def __init__(self, class_weights: torch.Tensor, warmup_steps: int): self.class_weights = class_weights self.warmup_steps = warmup_steps self.trainer = None # injected post-construction self._activated = False def on_step_end(self, args, state, control, **kwargs): if (not self._activated and self.trainer is not None and state.global_step >= self.warmup_steps): self.trainer.class_weights = self.class_weights self._activated = True print(f"\n -> [WeightWarmup] Class weights activated at step {state.global_step}") def freeze_encoder_layers(model, num_layers: int): """ Freeze the bottom `num_layers` encoder layers of a transformer. Useful to stabilise early training — frozen layers act as a fixed feature extractor while only the top layers and head fine-tune. """ if num_layers <= 0: return # Works for BERT-family (encoder.layer), DeBERTa (encoder.layer), ELECTRA, etc. encoder = None for attr in ["encoder", "bert", "deberta", "electra", "roberta"]: enc = getattr(model, attr, None) if enc is not None: encoder = getattr(enc, "layer", None) if encoder is not None: break if encoder is None: print(f" [WARNING] Could not find encoder layers to freeze — skipping.") return actual = min(num_layers, len(encoder)) for i in range(actual): for param in encoder[i].parameters(): param.requires_grad = False print(f" -> Froze {actual}/{len(encoder)} encoder layers.") # ============================================================================= # CHECKPOINT HELPERS # ============================================================================= def load_ensemble_configs(config_path: str) -> list: with open(config_path, "r") as f: return json.load(f) def get_artifact_dir(artifacts_root: str, model_name: str) -> Path: safe_name = model_name.replace("/", "__") return Path(artifacts_root) / safe_name def artifact_exists(artifacts_root: str, model_name: str) -> bool: return (get_artifact_dir(artifacts_root, model_name) / "oof_probs.npy").exists() def load_artifact_oof_probs(artifacts_root: str, model_name: str) -> tuple: artifact_dir = get_artifact_dir(artifacts_root, model_name) oof_probs = np.load(artifact_dir / "oof_probs.npy") with open(artifact_dir / "metadata.json") as f: meta = json.load(f) return oof_probs, meta["oof_f1"] def save_model_artifact_metadata(artifact_dir: Path, oof_f1: float, fold_f1s: list, task_type: str, num_folds: int): meta = { "oof_f1": round(oof_f1, 6), "fold_f1s": [round(f, 6) for f in fold_f1s], "task_type": task_type, "num_folds": num_folds, "saved_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } with open(artifact_dir / "metadata.json", "w") as f: json.dump(meta, f, indent=2) # ============================================================================= # CONFIG HELPER — resolves per-model overrides against global defaults # ============================================================================= # Complete list of every training arg that can live in the JSON config. # Format: (json_key, args_attr, default_if_neither_set) _TRAINING_ARG_SPECS = [ # Tokenisation ("max_length", "max_length", 256), # Batch / gradient ("batch_size", "batch_size", 8), ("gradient_accumulation_steps", "gradient_accumulation_steps", 1), # Optimiser ("learning_rate", "learning_rate", 2e-5), ("head_lr_multiplier", "head_lr_multiplier", 1.0), ("head_keywords", "head_keywords", []), ("weight_decay", "weight_decay", 0.01), ("adam_epsilon", "adam_epsilon", 1e-6), # AMSGrad keeps an extra full-size optimizer state tensor (max_exp_avg_sq). # On VRAM-tight GPUs with very large encoders (e.g. RemBERT ~576M params) # this can be the difference between fitting and OOM. Set false per-model # to drop it; the raised adam_epsilon remains the primary guard against # second-moment underflow. ("use_amsgrad", "use_amsgrad", True), ("max_grad_norm", "max_grad_norm", 1.0), ("class_weight_dampening", "class_weight_dampening", "none"), # Schedule ("warmup_steps", "warmup_steps", 0), ("lr_scheduler_type", "lr_scheduler_type", "linear"), ("class_weight_warmup_steps", "class_weight_warmup_steps", 0), # Steps / patience ("max_steps", "max_steps", 10000), ("eval_steps", "eval_steps", 200), ("early_stopping_patience", "early_stopping_patience", 5), # Regularisation ("label_smoothing", "label_smoothing", 0.0), ("freeze_layers", "freeze_layers", 0), # Class imbalance ("class_balancing", "class_balancing", "weighted"), # Precision / model flags ("use_bf16", "use_bf16", False), ("drop_token_type_ids", "drop_token_type_ids", None), # Model identity ("tokenizer_name", "tokenizer_name", None), # resolved below ("other_cols", "other_cols", []), ("cat_cols", "cat_cols", []), ("cat_encoding", "cat_encoding", "ordinal"), # Options: ordinal, frequency, target # Loss objective # "ce" — standard cross-entropy against hard integer labels (default). # "kl" — KL divergence against soft label distributions from a previous ensemble run. # Requires --soft_label_path pointing to a processed ensemble parquet that # contains final_logprob_ columns. Use a separate ensemble_config for # this second-generation training. ("loss_type", "loss_type", "ce"), # Prefix of soft-label columns in the soft_label_path parquet (default matches process output). ("soft_label_prefix", "soft_label_prefix", "final_logprob_"), # KL temperature: soften/sharpen the teacher distribution before computing KL loss. # Values > 1.0 soften (more uniform), < 1.0 sharpen. Usually 1.0–4.0. ("kl_temperature", "kl_temperature", 1.0), ] def resolve_model_args(global_args, config: dict): """ Returns a namespace where every training arg is resolved with priority: per-model JSON config > global CLI args > hardcoded default """ resolved = copy.deepcopy(global_args) for json_key, attr, default in _TRAINING_ARG_SPECS: if json_key in config: setattr(resolved, attr, config[json_key]) elif not hasattr(resolved, attr) or getattr(resolved, attr) is None: setattr(resolved, attr, default) # tokenizer_name falls back to model_name if not explicitly set if not getattr(resolved, "tokenizer_name", None): resolved.tokenizer_name = config["model_name"] resolved.model_name = config["model_name"] return resolved # ============================================================================= # FORMATTED EVAL CALLBACK # ============================================================================= class FormattedEvalCallback(TrainerCallback): def __init__(self, task_type: str, num_labels: int, idx_to_label: dict = None): self.task_type = task_type self.num_labels = num_labels self.idx_to_label = idx_to_label def on_evaluate(self, args, state, control, metrics=None, **kwargs): if metrics is None: return print("\n" + "-" * 60) print("Overall Metrics:") for key in ["eval_loss", "eval_accuracy", "eval_f1", "eval_precision", "eval_recall", "eval_mae", "eval_rmse", "eval_mse", "eval_r2", "eval_within_1_accuracy"]: if key in metrics: v = metrics[key] name = key.replace("eval_", "") print(f" {name:<20}: {v:.4f}" if isinstance(v, float) else f" {name:<20}: {v}") if self.task_type in ["classification", "ordinal", "soft_label"]: class_indices = sorted( int(k.split("_")[-1]) for k in metrics if k.startswith("eval_precision_class_") ) if class_indices: has_kl = f"eval_kl_class_{class_indices[0]}" in metrics header = f" {'Class':<8} {'Prec':<8} {'Recall':<8} {'F1':<8} {'Support':<8}" if has_kl: header += f" {'KL Loss':<8}" print(f"\n{header}") print(" " + "-" * (len(header) - 2)) for i in class_indices: label = f"{i}({self.idx_to_label[i]})" if self.idx_to_label else str(i) row = (f" {label:<8} " f"{metrics.get(f'eval_precision_class_{i}', 0):<8.4f} " f"{metrics.get(f'eval_recall_class_{i}', 0):<8.4f} " f"{metrics.get(f'eval_f1_class_{i}', 0):<8.4f} " f"{metrics.get(f'eval_support_class_{i}', 0):<8}") if has_kl: row += f" {metrics.get(f'eval_kl_class_{i}', 0):<8.4f}" print(row) if self.task_type == "ordinal": thresh_indices = sorted( int(k.split("_")[2]) for k in metrics if k.startswith("eval_threshold_") and k.endswith("_acc") ) if thresh_indices: print(f"\n {'Thresh':<8} {'Question':<14} {'Acc':<8} {'Recall':<8}") print(" " + "-" * 38) for i in thresh_indices: print(f" {i:<8} {'label > ' + str(i) + '?':<14} " f"{metrics.get(f'eval_threshold_{i}_acc', 0):<8.4f} " f"{metrics.get(f'eval_threshold_{i}_recall', 0):<8.4f}") print("-" * 60) # ============================================================================= # CUSTOM MODELS # ============================================================================= class MultimodalClassificationModel(nn.Module): def __init__(self, base_model, num_additional_features, num_labels, class_weights=None, drop_token_type_ids=None, label_smoothing=0.0): super().__init__() self.base_model = base_model self.num_additional_features = num_additional_features self.num_labels = num_labels self.class_weights = class_weights self.drop_token_type_ids = drop_token_type_ids self.label_smoothing = label_smoothing self.config = base_model.config # required by HuggingFace Trainer hidden_size = base_model.config.hidden_size combined_size = hidden_size + num_additional_features self.classifier = nn.Sequential( nn.Linear(combined_size, hidden_size), nn.ReLU(), nn.Dropout(0.1), nn.Linear(hidden_size, num_labels) ) if hasattr(base_model, 'classifier'): base_model.classifier = nn.Identity() def forward(self, input_ids, attention_mask, additional_features=None, labels=None, **kwargs): model_type = getattr(self.base_model.config, "model_type", "") default_drop = ["xlm-roberta", "roberta", "camembert", "deberta-v2", "distilbert", "bart", "longformer"] should_drop = self.drop_token_type_ids if self.drop_token_type_ids is not None else (model_type in default_drop) if should_drop: kwargs.pop("token_type_ids", None) base_encoder = getattr(self.base_model, self.base_model.base_model_prefix, self.base_model) outputs = base_encoder(input_ids=input_ids, attention_mask=attention_mask, **kwargs) pooled = outputs.last_hidden_state[:, 0, :] combined = torch.cat([pooled, additional_features], dim=1) if additional_features is not None else pooled logits = self.classifier(combined) loss = None if labels is not None: loss_fct = nn.CrossEntropyLoss( weight=self.class_weights.to(logits.device) if self.class_weights is not None else None, label_smoothing=self.label_smoothing, ) loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) return {"loss": loss, "logits": logits} class OrdinalRegressionModel(nn.Module): def __init__(self, base_model, num_classes, num_additional_features=0, drop_token_type_ids=None, pos_weight=None): super().__init__() self.base_model = base_model self.num_classes = num_classes self.num_thresholds = num_classes - 1 self.drop_token_type_ids = drop_token_type_ids self.pos_weight = pos_weight # [num_thresholds] tensor or None self.config = base_model.config # required by HuggingFace Trainer hidden_size = base_model.config.hidden_size combined_size = hidden_size + num_additional_features self.feature_extractor = nn.Sequential( nn.Linear(combined_size, hidden_size), nn.ReLU(), nn.Dropout(0.1), ) self.ordinal_head = nn.Linear(hidden_size, self.num_thresholds) def forward(self, input_ids, attention_mask, additional_features=None, labels=None, **kwargs): model_type = getattr(self.base_model.config, "model_type", "") default_drop = ["xlm-roberta", "roberta", "camembert", "deberta-v2", "distilbert", "bart", "longformer"] should_drop = self.drop_token_type_ids if self.drop_token_type_ids is not None else (model_type in default_drop) if should_drop: kwargs.pop("token_type_ids", None) outputs = self.base_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs) pooled = outputs.last_hidden_state[:, 0, :] combined = torch.cat([pooled, additional_features], dim=1) if additional_features is not None else pooled logits = self.ordinal_head(self.feature_extractor(combined)) loss = None if labels is not None: targets = torch.zeros(labels.size(0), self.num_thresholds, device=labels.device) for i in range(self.num_thresholds): targets[:, i] = (labels > i).float() pw = self.pos_weight.to(logits.device) if self.pos_weight is not None else None loss = nn.BCEWithLogitsLoss(pos_weight=pw)(logits, targets) return {"loss": loss, "logits": logits} # ============================================================================= # CUSTOM TRAINERS # ============================================================================= class BalancedSamplerMixin: def _get_train_sampler(self, dataset=None, **kwargs): target_dataset = dataset if dataset is not None else self.train_dataset labels = target_dataset["label"] class_counts = np.bincount(labels) class_weights = np.divide(1.0, class_counts, out=np.zeros_like(class_counts, dtype=float), where=class_counts != 0) sample_weights = [class_weights[label] for label in labels] return WeightedRandomSampler(weights=sample_weights, num_samples=len(sample_weights), replacement=True) class SamplerTrainer(BalancedSamplerMixin, Trainer): pass class WeightedLossTrainer(Trainer): """Standard Trainer with a weighted CrossEntropyLoss to handle class imbalance. Used for non-multimodal models (no additional_features) with class_balancing='weighted'. """ def __init__(self, *args, class_weights: torch.Tensor = None, **kwargs): super().__init__(*args, **kwargs) self.class_weights = class_weights def compute_loss(self, model, inputs, return_outputs=False, **kwargs): labels = inputs.get("labels") outputs = model(**inputs) logits = outputs.logits if self.class_weights is not None: loss_fct = nn.CrossEntropyLoss( weight=self.class_weights.to(logits.device), label_smoothing=self.args.label_smoothing_factor, ) loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) else: loss = outputs.loss return (loss, outputs) if return_outputs else loss class KLDivTrainer(Trainer): """Trains against soft label distributions using KL divergence loss. Expects `soft_labels` tensor in the batch (shape: [batch, num_classes]). `kl_temperature` softens/sharpens the teacher before computing loss. """ def __init__(self, *args, kl_temperature=1.0, **kwargs): super().__init__(*args, **kwargs) self.kl_temperature = kl_temperature def _set_signature_columns_if_needed(self): """Tells the Hugging Face Trainer NOT to delete our custom soft_labels column.""" super()._set_signature_columns_if_needed() if self._signature_columns is not None and "soft_labels" not in self._signature_columns: self._signature_columns.append("soft_labels") def compute_loss(self, model, inputs, return_outputs=False, **kwargs): soft_labels = inputs.pop("soft_labels") # [B, C] float _ = inputs.pop("labels", None) # Pop to prevent wasted CE loss computation outputs = model(**inputs) logits = outputs.logits # [B, C] # Apply temperature to teacher distribution if self.kl_temperature != 1.0: teacher = torch.softmax( torch.log(soft_labels.clamp(1e-7)) / self.kl_temperature, dim=-1) else: teacher = soft_labels # KL(teacher || student) = sum(teacher * log(teacher / student)) # nn.KLDivLoss expects log-probs as input, probs as target log_student = torch.nn.functional.log_softmax(logits, dim=-1) loss = torch.nn.functional.kl_div( log_student, teacher, reduction="batchmean") return (loss, outputs) if return_outputs else loss class KLDivMultimodalTrainer(KLDivTrainer): """KL divergence trainer for MultimodalClassificationModel.""" def compute_loss(self, model, inputs, return_outputs=False, **kwargs): soft_labels = inputs.pop("soft_labels") _ = inputs.pop("labels", None) # Pop to prevent wasted CE loss computation additional_features = inputs.pop("additional_features", None) outputs = model(**inputs, additional_features=additional_features, labels=None) logits = outputs["logits"] if self.kl_temperature != 1.0: teacher = torch.softmax( torch.log(soft_labels.clamp(1e-7)) / self.kl_temperature, dim=-1) else: teacher = soft_labels log_student = torch.nn.functional.log_softmax(logits, dim=-1) loss = torch.nn.functional.kl_div( log_student, teacher, reduction="batchmean") return (loss, outputs) if return_outputs else loss class MultimodalTrainerOverride(Trainer): def compute_loss(self, model, inputs, return_outputs=False, **kwargs): labels = inputs.pop("labels", None) additional_features = inputs.pop("additional_features", None) outputs = model(**inputs, additional_features=additional_features, labels=labels) return (outputs["loss"], outputs) if return_outputs else outputs["loss"] class WeightedMultimodalTrainer(MultimodalTrainerOverride): pass class SamplerMultimodalTrainer(BalancedSamplerMixin, MultimodalTrainerOverride): pass class OrdinalRegressionTrainer(MultimodalTrainerOverride): pass class OrdinalSamplerTrainer(BalancedSamplerMixin, MultimodalTrainerOverride): """Ordinal trainer with WeightedRandomSampler for class-imbalance correction. Sampling is driven by the hard label so minority ordinal classes appear more often, while the loss target remains the standard BCE ordinal objective. """ pass class OrdinalWeightedTrainer(MultimodalTrainerOverride): """Ordinal trainer that passes per-threshold pos_weights into the model. The pos_weight is baked into OrdinalRegressionModel at construction time (compute_ordinal_pos_weights), so no extra compute_loss override is needed. """ pass class KLOrdinalTrainer(MultimodalTrainerOverride): """ Distillation for ordinal students. Teacher produces P(class=k) via ordinal_logits_to_probabilities. We convert that to cumulative soft targets: soft_cum[:, i] = sum(teacher_probs[:, i+1:]) → P(label > i) Then apply BCEWithLogitsLoss against those soft targets, optionally with pos_weight for threshold-level imbalance. """ def __init__(self, *args, kl_temperature=1.0, pos_weight=None, **kwargs): super().__init__(*args, **kwargs) self.kl_temperature = kl_temperature self.pos_weight = pos_weight # [num_thresholds] def _set_signature_columns_if_needed(self): super()._set_signature_columns_if_needed() if self._signature_columns and "soft_labels" not in self._signature_columns: self._signature_columns.append("soft_labels") def compute_loss(self, model, inputs, return_outputs=False, **kwargs): soft_labels = inputs.pop("soft_labels") # [B, total_classes] incl. unknown _ = inputs.pop("labels", None) additional_features = inputs.pop("additional_features", None) outputs = model(**inputs, additional_features=additional_features, labels=None) logits = outputs["logits"] # [B, num_thresholds] num_thresholds = logits.shape[1] num_ord_classes = num_thresholds + 1 # Strip unknown class (last column) and renormalize to ordinal-only distribution. # This matters for stage-2 where soft_labels has an extra unknown column. # Relies on soft_label_cols being sorted by internal class index (guaranteed by # the idx_to_name sort in generate_kfold_oof_predictions). ordinal_soft = soft_labels[:, :num_ord_classes] ordinal_soft = ordinal_soft / ordinal_soft.sum(dim=1, keepdim=True).clamp(min=1e-7) if self.kl_temperature != 1.0: log_soft = torch.log(ordinal_soft.clamp(1e-7)) / self.kl_temperature ordinal_soft = torch.softmax(log_soft, dim=-1) # Convert class probs → cumulative binary targets P(label > i) soft_cum = torch.stack( [ordinal_soft[:, i+1:].sum(dim=1) for i in range(num_thresholds)], dim=1 ) # [B, num_thresholds] pw = self.pos_weight.to(logits.device) if self.pos_weight is not None else None loss = nn.BCEWithLogitsLoss(pos_weight=pw)(logits, soft_cum) return (loss, outputs) if return_outputs else loss # ============================================================================= # METRICS # ============================================================================= def compute_classification_metrics(p): logits = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions preds = np.argmax(logits, axis=1) labels = p.label_ids num_labels = logits.shape[1] precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average="macro", zero_division=0) results = {"accuracy": accuracy_score(labels, preds), "f1": f1, "precision": precision, "recall": recall} precision_pc, recall_pc, f1_pc, support_pc = precision_recall_fscore_support( labels, preds, average=None, labels=list(range(num_labels)), zero_division=0) for i in range(num_labels): results[f"precision_class_{i}"] = precision_pc[i] results[f"recall_class_{i}"] = recall_pc[i] results[f"f1_class_{i}"] = f1_pc[i] results[f"support_class_{i}"] = int(support_pc[i]) return results def compute_ordinal_metrics(p): logits = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions probs = torch.sigmoid(torch.tensor(logits)).numpy() preds = batch_ordinal_encoding_to_labels(probs) labels = p.label_ids num_classes = logits.shape[1] + 1 precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average="macro", zero_division=0) results = {"accuracy": accuracy_score(labels, preds), "mae": mean_absolute_error(labels, preds), "f1": f1} precision_pc, recall_pc, f1_pc, support_pc = precision_recall_fscore_support( labels, preds, average=None, labels=list(range(num_classes)), zero_division=0) for i in range(num_classes): results[f"precision_class_{i}"] = precision_pc[i] results[f"recall_class_{i}"] = recall_pc[i] results[f"f1_class_{i}"] = f1_pc[i] results[f"support_class_{i}"] = int(support_pc[i]) threshold_preds = (probs > 0.5).astype(int) for i in range(num_classes - 1): threshold_true = (labels > i).astype(int) threshold_pred = threshold_preds[:, i] results[f"threshold_{i}_acc"] = accuracy_score(threshold_true, threshold_pred) n_true_pos = threshold_true.sum() results[f"threshold_{i}_recall"] = ( threshold_pred[threshold_true == 1].sum() / n_true_pos if n_true_pos > 0 else 0.0 ) return results # ============================================================================= # K-FOLD ENGINE — TRANSFORMER # ============================================================================= def generate_kfold_oof_predictions(args, df, task_type, model_list, artifact_name=None, idx_to_name=None, custom_splits=None, split_names=None): """ args here is already a *resolved* namespace — all per-model overrides applied. artifact_name: override the folder name used for all disk I/O (oof_probs.npy, fold_N/model/, metadata.json). When None, falls back to model_name. This decouples the HuggingFace model identifier from the artifact path, which is necessary for split-stage models that share the same base model but need separate stage1 / stage2 artifact directories. """ kfold = StratifiedKFold(n_splits=args.ensemble_k_folds, shuffle=True, random_state=args.seed) num_classes = int(df["label"].max()) + 1 if task_type == "classification" else args.ordinal_num_classes final_oof_probs = np.zeros((len(df), num_classes)) for model_name in model_list: # artifact_name drives all path operations; model_name drives from_pretrained _artifact_name = artifact_name if artifact_name is not None else model_name artifact_dir = get_artifact_dir(args.artifacts_dir, _artifact_name) artifact_dir.mkdir(parents=True, exist_ok=True) # --- Per-model resume: if oof_probs.npy already exists, skip all training --- if (artifact_dir / "oof_probs.npy").exists(): with open(artifact_dir / "metadata.json") as f: meta = json.load(f) existing_probs = np.load(artifact_dir / "oof_probs.npy") print(f"\n{'='*70}\nResuming K-Fold for: {model_name}\n{'='*70}") print(f" -> Artifact directory: {artifact_dir}") print(f" -> [Resume] Found existing oof_probs.npy — skipping all training.") print(f" -> OOF Macro F1: {meta['oof_f1']:.4f} | Fold F1s: {meta.get('fold_f1s', [])}") return existing_probs, meta["oof_f1"] print(f"\n{'='*70}\nStarting K-Fold for: {model_name}\n{'='*70}") print(f" -> Artifact directory: {artifact_dir}") print(f" -> class_balancing={args.class_balancing} " f"label_smoothing={args.label_smoothing} " f"freeze_layers={args.freeze_layers} " f"lr_scheduler={args.lr_scheduler_type} " f"warmup_steps={args.warmup_steps}") model_oof_probs = np.zeros_like(final_oof_probs) fold_f1s = [] # custom_splits: list of (train_idx, val_idx). Used by --training_mode # final to train ONE model on a stratified holdout split. split_names # override the fold_N directory names (e.g. ["final"]). _splits = (custom_splits if custom_splits is not None else list(kfold.split(df, df["label"]))) for fold, (train_idx, val_idx) in enumerate(_splits): fold_num = fold + 1 _dir_name = split_names[fold] if split_names else f"fold_{fold_num}" fold_artifact_dir = artifact_dir / _dir_name print(f"\n--- Split {_dir_name} ({fold_num}/{len(_splits)}) ---") keep_cols = ["text", "label"] if args.other_cols: keep_cols.append("additional_features") # KL training: include soft label columns so the Trainer can read them per-batch soft_label_cols = [] if getattr(args, "loss_type", "ce") == "kl": prefix = getattr(args, "soft_label_prefix", "final_logprob_") raw_soft_cols = [c for c in df.columns if c.startswith(prefix)] if not raw_soft_cols: raise ValueError( f"loss_type=kl but no '{prefix}*' columns found in df. " "Did you pass --soft_label_path?") # Sort columns by internal class index so the packed soft_labels tensor # always has classes in order [0, 1, ..., ordinal_num_classes, unknown]. # Alphabetical sort is NOT safe here — e.g. mapping {"D":1,"C":2,"B":3,"A":4,"N":-1} # would sort as A,B,C,D,N = internal indices 3,2,1,0,4, causing KLOrdinalTrainer # to strip the wrong column when slicing [:, :num_ord_classes]. if idx_to_name: name_to_idx = {v: k for k, v in idx_to_name.items()} soft_label_cols = sorted( raw_soft_cols, key=lambda c: name_to_idx.get(c[len(prefix):], 999) ) else: soft_label_cols = raw_soft_cols # fallback: trust insertion order keep_cols.extend(soft_label_cols) train_df = df.iloc[train_idx][keep_cols].copy() val_df = df.iloc[val_idx][keep_cols].copy() tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name) def tokenize_fn(examples): toks = tokenizer(examples["text"], padding="max_length", max_length=args.max_length, truncation=True) if getattr(args, 'drop_token_type_ids', False) and "token_type_ids" in toks: del toks["token_type_ids"] if "additional_features" in examples: toks["additional_features"] = examples["additional_features"] # Pack soft label columns into a single float32 tensor per example if soft_label_cols: toks["soft_labels"] = [ [examples[c][i] for c in soft_label_cols] for i in range(len(examples[soft_label_cols[0]])) ] return toks train_ds = (Dataset.from_pandas(train_df, preserve_index=False) .map(tokenize_fn, batched=True).remove_columns(["text"])) val_ds = (Dataset.from_pandas(val_df, preserve_index=False) .map(tokenize_fn, batched=True).remove_columns(["text"])) trainer_kwargs = {} weight_warmup_cb = None if task_type == "classification": if args.class_balancing == "weighted": class_weights = compute_class_weights_from_labels( train_df["label"].values, dampening=args.class_weight_dampening, ) # If warmup requested, start with no weights and inject later if args.class_weight_warmup_steps > 0: print(f" [Fold {fold_num}] Class weight warmup: " f"weights deferred until step {args.class_weight_warmup_steps} " f"(dampening={args.class_weight_dampening})") weight_warmup_cb = WeightWarmupCallback( class_weights, args.class_weight_warmup_steps) effective_weights = None # start unweighted else: print(f" [Fold {fold_num}] class_weight_dampening={args.class_weight_dampening}") effective_weights = class_weights else: class_weights = None effective_weights = None _use_kl = getattr(args, "loss_type", "ce") == "kl" if args.other_cols: base_model = AutoModelForSequenceClassification.from_pretrained( model_name, num_labels=num_classes, use_safetensors=True, ignore_mismatched_sizes=True, torch_dtype=torch.float32) freeze_encoder_layers(base_model, args.freeze_layers) model = MultimodalClassificationModel( base_model, len(args.other_cols), num_classes, class_weights, args.drop_token_type_ids, args.label_smoothing ).to("cuda") if _use_kl: TrainerClass = KLDivMultimodalTrainer trainer_kwargs = {"kl_temperature": args.kl_temperature} print(f" [Fold {fold_num}] KL divergence objective (temperature={args.kl_temperature})") else: TrainerClass = (SamplerMultimodalTrainer if args.class_balancing == "sampler" else WeightedMultimodalTrainer) else: model = AutoModelForSequenceClassification.from_pretrained( model_name, num_labels=num_classes, use_safetensors=True, torch_dtype=torch.float32, ).to("cuda") freeze_encoder_layers(model, args.freeze_layers) if _use_kl: TrainerClass = KLDivTrainer trainer_kwargs = {"kl_temperature": args.kl_temperature} print(f" [Fold {fold_num}] KL divergence objective (temperature={args.kl_temperature})") elif args.class_balancing == "sampler": TrainerClass = SamplerTrainer elif effective_weights is not None or args.class_weight_warmup_steps > 0: TrainerClass = WeightedLossTrainer # Pass effective_weights (may be None during warmup — that's intentional) trainer_kwargs = {"class_weights": effective_weights} else: TrainerClass = Trainer compute_metrics_fn = compute_classification_metrics metric_for_best = "eval_f1" greater_is_better = True elif task_type == "ordinal": base_model = AutoModel.from_pretrained( model_name, use_safetensors=True, ignore_mismatched_sizes=True, torch_dtype=torch.float32) freeze_encoder_layers(base_model, args.freeze_layers) # Compute per-threshold pos_weights for weighted BCE ordinal_pos_weight = None if args.class_balancing == "weighted": ordinal_pos_weight = compute_ordinal_pos_weights( train_df["label"].values, num_classes - 1, dampening=args.class_weight_dampening, ) print(f" [Fold {fold_num}] class_balancing=weighted " f"(BCEWithLogitsLoss pos_weight={[round(w,3) for w in ordinal_pos_weight.tolist()]})") elif args.class_balancing == "sampler": print(f" [Fold {fold_num}] class_balancing=sampler (WeightedRandomSampler)") else: print(f" [Fold {fold_num}] class_balancing=none") model = OrdinalRegressionModel( base_model, num_classes, len(args.other_cols) if args.other_cols else 0, args.drop_token_type_ids, pos_weight=ordinal_pos_weight, ).to("cuda") _use_kl = getattr(args, "loss_type", "ce") == "kl" if _use_kl: TrainerClass = KLOrdinalTrainer trainer_kwargs = { "kl_temperature": args.kl_temperature, "pos_weight": ordinal_pos_weight, # still apply threshold balancing } elif args.class_balancing == "sampler": TrainerClass = OrdinalSamplerTrainer elif args.class_balancing == "weighted": TrainerClass = OrdinalWeightedTrainer else: TrainerClass = OrdinalRegressionTrainer compute_metrics_fn = compute_ordinal_metrics metric_for_best = "eval_mae" greater_is_better = False if task_type == "classification": if args.class_balancing == "sampler": print(f" [Fold {fold_num}] class_balancing=sampler (WeightedRandomSampler)") elif args.class_balancing == "weighted": print(f" [Fold {fold_num}] class_balancing=weighted (CrossEntropyLoss weights)") else: print(f" [Fold {fold_num}] class_balancing=none") training_args = TrainingArguments( output_dir=str(fold_artifact_dir / "tmp_checkpoints"), max_steps=args.max_steps, learning_rate=args.learning_rate, per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size, gradient_accumulation_steps=args.gradient_accumulation_steps, weight_decay=args.weight_decay, adam_epsilon=args.adam_epsilon, max_grad_norm=args.max_grad_norm, warmup_steps=args.warmup_steps, lr_scheduler_type=args.lr_scheduler_type, label_smoothing_factor=args.label_smoothing, eval_strategy="steps", eval_steps=args.eval_steps, save_steps=args.eval_steps, load_best_model_at_end=True, metric_for_best_model=metric_for_best, greater_is_better=greater_is_better, logging_strategy="steps", logging_steps=args.eval_steps, save_total_limit=1, save_only_model=True, # skip optimizer/scheduler state — saves ~3GB per checkpoint report_to="none", bf16=args.use_bf16, ) import torch.optim as optim if args.head_lr_multiplier > 1.0: print(f" [Fold {fold_num}] Using Differential LR: Head is learning {args.head_lr_multiplier}x faster than Base.") base_head_keys = ["classifier", "ordinal_head", "feature_extractor", "score", "pooler"] head_keywords = base_head_keys + args.head_keywords # Remove duplicates just in case head_keywords = list(set(head_keywords)) no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ # Base Encoder (With Decay) {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and not any(hk in n for hk in head_keywords) and p.requires_grad], "weight_decay": args.weight_decay, "lr": args.learning_rate}, # Base Encoder (No Decay) {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and not any(hk in n for hk in head_keywords) and p.requires_grad], "weight_decay": 0.0, "lr": args.learning_rate}, # Custom Head (With Decay, Multiplied LR) {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and any(hk in n for hk in head_keywords) and p.requires_grad], "weight_decay": args.weight_decay, "lr": args.learning_rate * args.head_lr_multiplier}, # Custom Head (No Decay, Multiplied LR) {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and any(hk in n for hk in head_keywords) and p.requires_grad], "weight_decay": 0.0, "lr": args.learning_rate * args.head_lr_multiplier} ] _use_ams = bool(getattr(args, "use_amsgrad", True)) if not _use_ams: print(" [OPTIM] AMSGrad disabled for this model " "(saves one full-size optimizer state tensor)") custom_optimizer = optim.AdamW( optimizer_grouped_parameters, eps=args.adam_epsilon, amsgrad=_use_ams, # running max of v̂ prevents second-moment decay toward zero ) optimizers = (custom_optimizer, None) else: # No differential LR, but we still construct the optimizer explicitly # so we can enable amsgrad=True. This prevents the second-moment v̂ from # decaying toward zero when gradients stay near-zero for many steps # (e.g. saturated ordinal BCE), which would otherwise cause enormous # effective weight updates and a training loss blow-up. no_decay = ["bias", "LayerNorm.weight"] standard_grouped_parameters = [ {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and p.requires_grad], "weight_decay": args.weight_decay, "lr": args.learning_rate}, {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and p.requires_grad], "weight_decay": 0.0, "lr": args.learning_rate}, ] _use_ams = bool(getattr(args, "use_amsgrad", True)) if not _use_ams: print(" [OPTIM] AMSGrad disabled for this model") fallback_optimizer = optim.AdamW( standard_grouped_parameters, eps=args.adam_epsilon, amsgrad=_use_ams, # running max of v̂ — see comment above ) optimizers = (fallback_optimizer, None) trainer = TrainerClass( model=model, args=training_args, train_dataset=train_ds, eval_dataset=val_ds, compute_metrics=compute_metrics_fn, optimizers=optimizers, callbacks=[ EarlyStoppingCallback(args.early_stopping_patience), FormattedEvalCallback(task_type=task_type, num_labels=num_classes), *([weight_warmup_cb] if weight_warmup_cb is not None else []), ], **trainer_kwargs ) # Give the warmup callback a handle to the trainer so it can # set class_weights on it when the step threshold is reached if weight_warmup_cb is not None: weight_warmup_cb.trainer = trainer trainer.train() # --- Save best fold model permanently --- fold_model_dir = fold_artifact_dir / "model" fold_model_dir.mkdir(parents=True, exist_ok=True) trainer.save_model(str(fold_model_dir)) tokenizer.save_pretrained(str(fold_model_dir)) print(f" [Fold {fold_num}] Saved best model → {fold_model_dir}") tmp_ckpt_dir = fold_artifact_dir / "tmp_checkpoints" if tmp_ckpt_dir.exists(): shutil.rmtree(tmp_ckpt_dir) # --- OOF inference --- oof_output = trainer.predict(val_ds) logits = (oof_output.predictions[0] if isinstance(oof_output.predictions, tuple) else oof_output.predictions) fold_probs = (torch.softmax(torch.tensor(logits), dim=1).numpy() if task_type == "classification" else ordinal_logits_to_probabilities(logits)) model_oof_probs[val_idx] = fold_probs # For both task types, fold_probs contains per-class probabilities # (softmax for classification, ordinal_logits_to_probabilities for ordinal). # argmax is the correct decoder in both cases. # NOTE: do NOT use batch_ordinal_encoding_to_labels here — that function # expects sigmoid/cumulative probabilities (as used inside compute_ordinal_metrics), # not the class-probability representation stored in fold_probs. Applying it to # class probs causes virtually all predictions to be 0 (class probs rarely > 0.5), # which produces a near-zero reported Val Macro F1 despite healthy training metrics. fold_preds = np.argmax(fold_probs, axis=1) fold_f1 = precision_recall_fscore_support( df.iloc[val_idx]["label"].values, fold_preds, average="macro", zero_division=0)[2] fold_f1s.append(float(fold_f1)) print(f" [Fold {fold_num}] Val Macro F1: {fold_f1:.4f}") del trainer, model torch.cuda.empty_cache() gc.collect() final_oof_probs += model_oof_probs final_oof_probs /= len(model_list) # final_oof_probs holds per-class probabilities for every sample (both task types). # argmax is the correct decoder. The previous ordinal branch # `batch_ordinal_encoding_to_labels(final_oof_probs[:, :-1])` was wrong: it passed # class probabilities (which rarely exceed 0.5) into a function that expects # cumulative/sigmoid probabilities, collapsing nearly all predictions to class 0. oof_preds = np.argmax(final_oof_probs, axis=1) # Score only rows that actually received predictions: the union of all # validation indices. In kfold mode this is every row (unchanged # behaviour); in final mode it is the holdout, giving an honest score # instead of one diluted by the untouched (all-zero) training rows. _scored = np.zeros(len(df), dtype=bool) for _tr, _va in _splits: _scored[_va] = True valid_mask = (df["label"].values >= 0) & _scored _, _, oof_f1, _ = precision_recall_fscore_support( df["label"].values[valid_mask], oof_preds[valid_mask], average="macro", zero_division=0) _tag = "Holdout" if (split_names and "final" in split_names) else "OOF" print(f" -> Model {_tag} Macro F1: {oof_f1:.4f} " f"({int(valid_mask.sum())} scored rows)") np.save(artifact_dir / "oof_probs.npy", final_oof_probs) save_model_artifact_metadata(artifact_dir, oof_f1, fold_f1s, task_type, args.ensemble_k_folds) print(f" -> Saved oof_probs.npy + metadata.json → {artifact_dir}") torch.cuda.empty_cache() gc.collect() return final_oof_probs, oof_f1 # ============================================================================= # K-FOLD ENGINE — LIGHTGBM # ============================================================================= class LightGBMProgressCallback: def __init__(self, fold: int, total_folds: int, log_every: int = 100): self.fold = fold self.total_folds = total_folds self.log_every = log_every def __call__(self, env): if (env.iteration == 0 or (env.iteration + 1) % self.log_every == 0 or env.iteration + 1 == env.end_iteration): metrics_str = " | ".join( f"{ds}/{metric}: {value:.4f}" for ds, metric, value, _ in (env.evaluation_result_list or [])) print(f" [Fold {self.fold}/{self.total_folds}] " f"Round {env.iteration + 1:>4}/{env.end_iteration} | {metrics_str}") sys.stdout.flush() def predict_ordinal_folds_on_rows(current_args, df_rows, model_name, artifact_name, num_classes, dir_names=None): """ Predict ordinal class probabilities for rows using the saved stage2 fold checkpoints, averaged across folds. Purpose: UNKNOWN rows are excluded from stage2 training, so their stage2 OOF slots used to be filled with a uniform distribution selected via the ground-truth label mask. That leaked the label into the meta-learner's features ("perfectly uniform known-class probs" existed only for UNKNOWN rows) and cannot be reproduced at inference. Predicting these rows with the trained fold models is leak-free — no fold ever saw them — and makes training features match what inference computes. """ from safetensors.torch import load_file as _stload artifact_dir = get_artifact_dir(current_args.artifacts_dir, artifact_name) device = "cuda" if torch.cuda.is_available() else "cpu" texts = df_rows["text"].fillna("").astype(str).tolist() n = len(texts) bs = int(getattr(current_args, "eval_batch_size", None) or 64) add_feats = None if getattr(current_args, "other_cols", None) and "additional_features" in df_rows.columns: add_feats = np.stack(df_rows["additional_features"].values).astype(np.float32) tok_name = getattr(current_args, "tokenizer_name", None) or model_name tokenizer = AutoTokenizer.from_pretrained(tok_name) max_len = int(getattr(current_args, "max_length", 256)) s_sum, cnt = None, 0 _names = dir_names or [f"fold_{i}" for i in range(1, current_args.ensemble_k_folds + 1)] for fold_num, _dname in enumerate(_names, start=1): model_dir = artifact_dir / _dname / "model" st = model_dir / "model.safetensors" if not st.exists(): st = model_dir / "pytorch_model.bin" if not st.exists(): print(f" [WARN] stage2 fold {fold_num} checkpoint missing — skipped") continue base = AutoModel.from_pretrained(model_name) n_add = len(current_args.other_cols) if getattr(current_args, "other_cols", None) else 0 model = OrdinalRegressionModel(base, num_classes, num_additional_features=n_add) sd = (_stload(str(st)) if st.suffix == ".safetensors" else torch.load(str(st), map_location="cpu", weights_only=True)) model.load_state_dict(sd, strict=False) del sd model.eval().to(device) probs = np.zeros((n, num_classes)) with torch.no_grad(): for start in range(0, n, bs): bt = texts[start:start + bs] enc = tokenizer(bt, padding=True, truncation=True, max_length=max_len, return_tensors="pt") enc = {k: v.to(device) for k, v in enc.items()} af = (torch.tensor(add_feats[start:start + bs], device=device) if add_feats is not None else None) logits = model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"], additional_features=af)["logits"] cum = torch.sigmoid(logits) p = torch.zeros(cum.shape[0], num_classes, device=device) p[:, 0] = 1 - cum[:, 0] for i in range(1, num_classes - 1): p[:, i] = cum[:, i - 1] - cum[:, i] p[:, -1] = cum[:, -1] probs[start:start + bs] = p.clamp(min=0).cpu().numpy() s_sum = probs if s_sum is None else s_sum + probs cnt += 1 model.cpu(); del model, base gc.collect() if device == "cuda": torch.cuda.empty_cache() print(f" [stage2-on-unknown] fold {fold_num} done") if cnt == 0: raise RuntimeError("No stage2 fold checkpoints found for " + artifact_name) avg = s_sum / cnt return avg / np.clip(avg.sum(axis=1, keepdims=True), 1e-9, None) def generate_kfold_oof_predictions_lgbm(args, df, total_classes): artifact_dir = get_artifact_dir(args.artifacts_dir, "tfidf_lgbm") artifact_dir.mkdir(parents=True, exist_ok=True) print(f" -> Artifact directory: {artifact_dir}") kfold = StratifiedKFold(n_splits=args.ensemble_k_folds, shuffle=True, random_state=args.seed) final_oof_probs = np.zeros((len(df), total_classes)) texts = df["text"].fillna("").tolist() labels = df["label"].values use_tabular = "additional_features" in df.columns if use_tabular: tab_matrix = csr_matrix(np.vstack(df["additional_features"].values)) print(f"\n{'='*70}\nStarting K-Fold for: TF-IDF + LightGBM\n{'='*70}") all_oof_preds = np.zeros(len(df), dtype=int) fold_f1s = [] for fold, (train_idx, val_idx) in enumerate(kfold.split(df, labels)): fold_num = fold + 1 fold_artifact_dir = artifact_dir / f"fold_{fold_num}" fold_artifact_dir.mkdir(parents=True, exist_ok=True) print(f"\n--- Fold {fold_num}/{args.ensemble_k_folds} ---") train_texts = [texts[i] for i in train_idx] val_texts = [texts[i] for i in val_idx] train_labels = labels[train_idx] val_labels = labels[val_idx] print(f" [Fold {fold_num}] Fitting TF-IDF vectorizers on {len(train_texts):,} samples...") word_tfidf = TfidfVectorizer(analyzer="word", ngram_range=(1, 2), max_features=100_000, sublinear_tf=True, min_df=2) char_tfidf = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), max_features=100_000, sublinear_tf=True, min_df=3) X_train_word = word_tfidf.fit_transform(train_texts) X_val_word = word_tfidf.transform(val_texts) print(f" [Fold {fold_num}] Word TF-IDF: {len(word_tfidf.vocabulary_):,} features") X_train_char = char_tfidf.fit_transform(train_texts) X_val_char = char_tfidf.transform(val_texts) print(f" [Fold {fold_num}] Char TF-IDF: {len(char_tfidf.vocabulary_):,} features") X_train = hstack([X_train_word, X_train_char]) X_val = hstack([X_val_word, X_val_char]) if use_tabular: X_train = hstack([X_train, tab_matrix[train_idx]]) X_val = hstack([X_val, tab_matrix[val_idx]]) print(f" [Fold {fold_num}] Feature matrix: {X_train.shape[1]:,} total | " f"train={X_train.shape[0]:,} val={X_val.shape[0]:,}") lgbm_model = lgb.LGBMClassifier( n_estimators=1000, learning_rate=0.05, num_leaves=63, subsample=0.8, colsample_bytree=0.8, class_weight="balanced", random_state=args.seed, n_jobs=-1, verbose=-1) print(f" [Fold {fold_num}] Training LightGBM...") lgbm_model.fit( X_train, train_labels, eval_set=[(X_val, val_labels)], eval_metric="multi_logloss", callbacks=[ lgb.early_stopping(stopping_rounds=50, verbose=False), lgb.log_evaluation(period=-1), LightGBMProgressCallback(fold_num, args.ensemble_k_folds, log_every=100), ]) print(f" [Fold {fold_num}] Best iteration: {lgbm_model.best_iteration_}") print(f" [Fold {fold_num}] Fitting isotonic calibrator...") calibrated_model = CalibratedClassifierCV(lgbm_model, method="isotonic", cv=3) calibrated_model.fit(X_train, train_labels) fold_pkl = fold_artifact_dir / "model.pkl" with open(fold_pkl, "wb") as f: pickle.dump({"calibrated_model": calibrated_model, "word_tfidf": word_tfidf, "char_tfidf": char_tfidf}, f, protocol=pickle.HIGHEST_PROTOCOL) print(f" [Fold {fold_num}] Saved calibrated model → {fold_pkl}") fold_probs = calibrated_model.predict_proba(X_val) final_oof_probs[val_idx] = fold_probs all_oof_preds[val_idx] = np.argmax(fold_probs, axis=1) fold_f1 = precision_recall_fscore_support( val_labels, all_oof_preds[val_idx], average="macro", zero_division=0)[2] fold_f1s.append(float(fold_f1)) print(f" [Fold {fold_num}] Val Macro F1: {fold_f1:.4f}") _, _, oof_f1, _ = precision_recall_fscore_support( labels, all_oof_preds, average="macro", zero_division=0) print(f"\n -> LightGBM OOF Macro F1: {oof_f1:.4f}") np.save(artifact_dir / "oof_probs.npy", final_oof_probs) save_model_artifact_metadata(artifact_dir, oof_f1, fold_f1s, "tfidf_lgbm", args.ensemble_k_folds) print(f" -> Saved oof_probs.npy + metadata.json → {artifact_dir}") return final_oof_probs, oof_f1 # ============================================================================= # PROCESS ENSEMBLE PREDICTIONS # ============================================================================= def process_ensemble_predictions(df, args, model_names, f1_scores, total_classes, internal_idx_to_name): print("\n" + "="*70) print("APPLYING DISTILLATION REMEDIES") print("="*70) final_ensemble_probs = np.zeros((len(df), total_classes)) if args.use_f1_weights: weights = np.array(f1_scores) / np.sum(f1_scores) print(f" -> F1-Weighted Averaging: {np.round(weights, 3)}") else: weights = np.ones(len(model_names)) / len(model_names) print(" -> Standard Averaging") for idx, model_name in enumerate(model_names): clean_name = model_name.split('/')[-1] model_cols = [f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}" for i in range(total_classes)] raw_probs = df[model_cols].values if args.temperature != 1.0: pseudo_logits = np.log(np.clip(raw_probs, 1e-7, 1.0)) scaled = pseudo_logits / args.temperature raw_probs = np.exp(scaled) / np.sum(np.exp(scaled), axis=1, keepdims=True) final_ensemble_probs += raw_probs * weights[idx] entropy = -np.sum(final_ensemble_probs * np.log(np.clip(final_ensemble_probs, 1e-7, 1.0)), axis=1) df["ensemble_entropy"] = entropy # 1. Update the condition to check the new explicit variables if args.alpha_correct < 1.0 or args.alpha_incorrect < 1.0 or args.entropy_threshold is not None: print(f" -> Blending with Ground Truth (Correct Alpha: {args.alpha_correct}, Incorrect Alpha: {args.alpha_incorrect})") mapping = load_mapping(args.mapping_dict_path) hard_labels = np.zeros((len(df), total_classes)) ensemble_argmax = np.argmax(final_ensemble_probs, axis=1) true_argmax = np.full(len(df), -1, dtype=int) for idx, row in df.iterrows(): orig_label = str(row[args.label_col]) internal_idx = (args.ordinal_num_classes if mapping.get(orig_label) == -1 else mapping.get(orig_label) - args.ordinal_min_label) if internal_idx is not None and 0 <= internal_idx < total_classes: hard_labels[idx, internal_idx] = 1.0 true_argmax[idx] = internal_idx # 2. Apply the explicit alphas correct_mask = (ensemble_argmax == true_argmax) & (true_argmax >= 0) incorrect_mask = (ensemble_argmax != true_argmax) & (true_argmax >= 0) # Start with an array of 1.0s (no blending) to safely handle unmapped/unknown labels dynamic_alphas = np.ones(len(df)) dynamic_alphas[correct_mask] = args.alpha_correct dynamic_alphas[incorrect_mask] = args.alpha_incorrect dynamic_alphas = dynamic_alphas[:, np.newaxis] blended = (dynamic_alphas * final_ensemble_probs) + ((1.0 - dynamic_alphas) * hard_labels) if args.entropy_threshold is not None: high_entropy_mask = entropy > args.entropy_threshold blended[high_entropy_mask] = hard_labels[high_entropy_mask] df["is_high_entropy_flag"] = high_entropy_mask print(f" -> Reverted {high_entropy_mask.sum()} high-entropy rows to hard labels.") final_ensemble_probs = blended for idx, col in enumerate( [f"final_logprob_{internal_idx_to_name.get(i, i)}" for i in range(total_classes)] ): df[col] = final_ensemble_probs[:, idx] return df # ============================================================================= # ANALYSIS # ============================================================================= def analyze_ensemble_characteristics(df, args, model_names, f1_scores, total_classes): print("\n" + "="*70) print("ENSEMBLE DISTILLATION ANALYSIS & RECOMMENDATIONS") print("="*70) raw_ensemble_probs = np.zeros((len(df), total_classes)) clean_model_names = [name.split('/')[-1] for name in model_names] for clean_name in clean_model_names: model_cols = [col for col in df.columns if col.startswith(f"{clean_name}_logprob_")] raw_ensemble_probs += df[model_cols].values raw_ensemble_probs /= len(model_names) max_f1, min_f1 = max(f1_scores), min(f1_scores) f1_spread = max_f1 - min_f1 print(f"1. Model Disparity (F1 Spread): {f1_spread:.4f} (Max: {max_f1:.4f}, Min: {min_f1:.4f})") print(" -> REC: USE `--use_f1_weights`." if f1_spread > 0.05 else " -> REC: Standard averaging is fine.") max_probs = np.max(raw_ensemble_probs, axis=1) avg_confidence = np.mean(max_probs) print(f"\n2. Average Top-Choice Confidence: {avg_confidence:.2%}") if avg_confidence > 0.90: print(" -> REC: Set `--temperature` > 1.0 (e.g., 1.5-2.0).") elif avg_confidence < 0.60: print(" -> REC: Set `--temperature` < 1.0 (e.g., 0.5-0.8).") else: print(" -> REC: Leave `--temperature` at 1.0.") entropy = -np.sum(raw_ensemble_probs * np.log(np.clip(raw_ensemble_probs, 1e-7, 1.0)), axis=1) p90_entropy = np.percentile(entropy, 90) print(f"\n3. Entropy — Mean: {np.mean(entropy):.4f} | 90th Pct: {p90_entropy:.4f}") print(f" -> REC: `--entropy_threshold {p90_entropy:.3f}`") mapping = load_mapping(args.mapping_dict_path) internal_idx_to_name = { args.ordinal_num_classes if val == -1 else val - args.ordinal_min_label: name for name, val in mapping.items() } ensemble_preds = np.argmax(raw_ensemble_probs, axis=1) true_labels = [] for _, row in df.iterrows(): orig = str(row[args.label_col]) idx = (args.ordinal_num_classes if mapping.get(orig) == -1 else mapping.get(orig) - args.ordinal_min_label) true_labels.append(idx if idx is not None and 0 <= idx < total_classes else -1) true_labels = np.array(true_labels) valid_mask = true_labels >= 0 agreement_rate = accuracy_score(true_labels[valid_mask], ensemble_preds[valid_mask]) print(f"\n4. Agreement with Ground Truth: {agreement_rate:.2%}") if agreement_rate < 0.80: print(" -> REC: `--alpha_incorrect 0.2` (Heavy penalty for errors)") elif agreement_rate < 0.90: print(" -> REC: `--alpha_incorrect 0.5` (Moderate penalty)") else: print(" -> REC: `--alpha_correct 1.0 --alpha_incorrect 1.0` (Trust the model entirely)") print("="*70 + "\n") print("Generating Deep Dive Analysis Plots...") sns.set_theme(style="whitegrid") fig, axes = plt.subplots(2, 2, figsize=(16, 12)) fig.suptitle('Ensemble Distillation Deep Dive Analysis', fontsize=18, y=0.98) sns.barplot(x=clean_model_names, y=f1_scores, ax=axes[0, 0], palette="viridis") axes[0, 0].set_title('OOF Macro F1 per Model', fontsize=14) axes[0, 0].set_ylabel('F1 Score') axes[0, 0].set_ylim(0, max(f1_scores) * 1.1) for i, s in enumerate(f1_scores): axes[0, 0].text(i, s + 0.01, f'{s:.3f}', ha='center', va='bottom', fontweight='bold') sns.histplot(max_probs, bins=40, kde=True, ax=axes[0, 1], color="royalblue") axes[0, 1].set_title('Ensemble Confidence Distribution', fontsize=14) axes[0, 1].axvline(avg_confidence, color='red', linestyle='--', label=f'Mean: {avg_confidence:.2f}') axes[0, 1].legend() sns.histplot(entropy, bins=40, kde=True, ax=axes[1, 0], color="coral") axes[1, 0].set_title('Ensemble Entropy Distribution', fontsize=14) axes[1, 0].axvline(p90_entropy, color='red', linestyle='--', label=f'90th Pct: {p90_entropy:.2f}') axes[1, 0].legend() class_agreement, class_names = [], [] for i in range(total_classes): mask = (true_labels == i) if mask.sum() > 0: class_agreement.append(accuracy_score(true_labels[mask], ensemble_preds[mask])) class_names.append(internal_idx_to_name.get(i, str(i))) sns.barplot(x=class_names, y=class_agreement, ax=axes[1, 1], palette="magma") axes[1, 1].set_title('Agreement Rate by True Class', fontsize=14) axes[1, 1].set_ylim(0, 1.05) for i, acc in enumerate(class_agreement): axes[1, 1].text(i, acc + 0.02, f'{acc:.1%}', ha='center', va='bottom', fontweight='bold') plt.tight_layout() output_dir = Path(args.ensemble_output_path).parent plot_path = output_dir / "ensemble_analysis_dashboard.png" plt.savefig(plot_path, dpi=300, bbox_inches='tight') plt.close() print(f"-> Saved dashboard → {plot_path}") # ============================================================================= # MAIN ORCHESTRATOR # ============================================================================= def main(): args = parse_args() torch.manual_seed(args.seed) np.random.seed(args.seed) if args.artifact_suffix: s = args.artifact_suffix args.artifacts_dir = f"{args.artifacts_dir}_{s}" stem, ext = args.metadata_path.rsplit(".", 1) args.metadata_path = f"{stem}_{s}.{ext}" stem, ext = args.ensemble_output_path.rsplit(".", 1) args.ensemble_output_path = f"{stem}_{s}.{ext}" Path(args.artifacts_dir).mkdir(parents=True, exist_ok=True) # Move the log file (created at module level in cwd) into artifacts_dir # so all run outputs are co-located. Use flush+rename to avoid data loss. global log_filename dest_log = Path(args.artifacts_dir) / Path(log_filename).name sys.stdout.log.flush() sys.stdout.log.close() if Path(log_filename).exists() and not dest_log.exists(): shutil.move(log_filename, dest_log) sys.stdout.log = open(dest_log, "a") sys.stderr = sys.stdout log_filename = str(dest_log) print(f" -> Log file: {dest_log}") # --- SNAPSHOT RUN CONTEXT --- # Save a frozen snapshot of the input config as run_config.json. # This is the canonical record of what was run — it never gets mutated. # The original config file stays clean and can be reused for other runs. print(f"\nSnapshotting run context to {args.artifacts_dir}/") run_config_path = Path(args.artifacts_dir) / "run_config.json" with open(args.ensemble_config_path) as f: input_config = json.load(f) run_snapshot = { "config_source": args.ensemble_config_path, "data_path": args.data_path, "mapping_dict_path": args.mapping_dict_path, "soft_label_path": args.soft_label_path, "cli_args": vars(args), "started_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "models": input_config, } with open(run_config_path, "w") as f: json.dump(run_snapshot, f, indent=2) print(f" -> run_config.json saved (input config snapshot + CLI args)") # Backup the generator script itself for full reproducibility shutil.copy2(__file__, Path(args.artifacts_dir) / Path(__file__).name) print(f" -> {Path(__file__).name} backed up") # Backup mapping (small, useful to have co-located with artifacts) if args.mapping_dict_path and Path(args.mapping_dict_path).exists(): shutil.copy2(args.mapping_dict_path, Path(args.artifacts_dir) / Path(args.mapping_dict_path).name) print(f" -> {Path(args.mapping_dict_path).name} backed up") print(f"\nLoading data from: {args.data_path}") df = (pd.read_parquet(args.data_path) if args.data_path.endswith('.parquet') else pd.read_csv(args.data_path)) # Merge soft label columns from a previous ensemble run when provided. # These will be used by models with loss_type="kl" in their config. if args.soft_label_path: print(f"Loading soft labels from: {args.soft_label_path}") soft_df = pd.read_parquet(args.soft_label_path) soft_cols = [c for c in soft_df.columns if c.startswith("final_logprob_")] if not soft_cols: raise ValueError(f"No final_logprob_* columns found in {args.soft_label_path}. " "Run --mode process first to generate soft labels.") # Align on index — both parquets must come from the same source data df = df.join(soft_df[soft_cols], how="left") print(f" -> Merged {len(soft_cols)} soft label columns: {soft_cols}") with open(args.ensemble_config_path, "r") as f: ensemble_configs = json.load(f) ensemble_configs = [c for c in ensemble_configs if c.get("use", True)] # 1. Load the mapping first so we can inspect its contents mapping = load_mapping(args.mapping_dict_path) # 2. Dynamically check if an Unknown category (-1) is active in this task has_unknown_class = any(val == -1 for val in mapping.values()) total_classes = args.ordinal_num_classes + 1 if has_unknown_class else args.ordinal_num_classes # ── FINAL training mode: one global stratified holdout, shared by every # model and stage so the honest-evaluation rows are identical across the # whole ensemble (required for meta-learner fitting on those rows). final_splits = None if getattr(args, "training_mode", "kfold") == "final": _rng = np.random.RandomState(args.seed) _lbls = df[args.label_col].astype(str).values _val = [] for _cls in np.unique(_lbls): _cidx = np.where(_lbls == _cls)[0] _take = min(args.val_rows_per_class, max(1, len(_cidx) // 2)) _val.extend(_rng.choice(_cidx, size=_take, replace=False)) _val = np.sort(np.array(_val)) _train = np.setdiff1d(np.arange(len(df)), _val) final_splits = [(_train, _val)] df["__is_holdout"] = np.isin(np.arange(len(df)), _val) print(f"\n[FINAL MODE] Stratified holdout: {len(_val)} rows " f"(target {args.val_rows_per_class}/class) | train: {len(_train)}") print(f"[FINAL MODE] Each model trains ONCE; checkpoint saved under " f"/final/model/. F1 is holdout-honest. Fit the meta-" f"learner on rows where __is_holdout is True.") # 3. Safely build internal index mapping internal_idx_to_name = { args.ordinal_num_classes if val == -1 else val - args.ordinal_min_label: name for name, val in mapping.items() } model_names = [] f1_scores = [] # ------------------------------------------------------------------------- # INTERRUPT HANDLER # ------------------------------------------------------------------------- _interrupted = {"flag": False} def _emergency_save(signum=None, frame=None): if _interrupted["flag"]: return _interrupted["flag"] = True sig_name = f"signal {signum}" if signum else "exit" print(f"\n\n[INTERRUPT] Caught {sig_name}.") if model_names: with open(args.metadata_path, "w") as f: json.dump({"model_names": model_names, "f1_scores": f1_scores}, f, indent=2) print(f" -> Metadata saved → {args.metadata_path}") print(f" -> Artifacts safe in: {args.artifacts_dir}/") print(f" -> Re-run with the same command to resume.") else: print(" -> No models completed yet.") if signum is not None: sys.exit(1) signal.signal(signal.SIGINT, _emergency_save) signal.signal(signal.SIGTERM, _emergency_save) atexit.register(_emergency_save) # ========================================================================= # GENERATION PHASE # ========================================================================= if args.mode in ["generate", "generate_and_process"]: print("\n" + "="*70) print(f"INITIATING HETEROGENEOUS ENSEMBLE DISTILLATION ({len(ensemble_configs)} Models)") print(f"Artifacts root: {args.artifacts_dir}") print("="*70) for idx, config in enumerate(ensemble_configs): model_name = config["model_name"] lgbm_artifact_name = "tfidf_lgbm" if config.get("task_type") == "tfidf_lgbm" else model_name # --- RESUME: filesystem is the source of truth --- if artifact_exists(args.artifacts_dir, lgbm_artifact_name): oof_probs, oof_f1 = load_artifact_oof_probs(args.artifacts_dir, lgbm_artifact_name) artifact_dir = get_artifact_dir(args.artifacts_dir, lgbm_artifact_name) with open(artifact_dir / "metadata.json") as f: meta = json.load(f) print(f"\n\n{'*'*70}") print(f"LOADING FROM ARTIFACT {idx+1}/{len(ensemble_configs)}: {model_name}") print(f" -> Saved at: {meta.get('saved_at','?')} | OOF F1: {oof_f1:.4f}") print(f" -> Fold F1s: {meta.get('fold_f1s', [])}") print(f"{'*'*70}") model_names.append(model_name) f1_scores.append(float(oof_f1)) clean_name = model_name.split('/')[-1] for i in range(total_classes): df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = oof_probs[:, i] continue print(f"\n\n{'*'*70}") print(f"RUNNING ENSEMBLE MODEL {idx+1}/{len(ensemble_configs)}: {model_name}") print(f"{'*'*70}") # Resolve all per-model overrides against global defaults current_args = resolve_model_args(args, config) df_model = df.copy() # ========================================================================= # --- ADDITION: CATEGORICAL ENCODING LOGIC --- # ========================================================================= if current_args.cat_cols: if current_args.cat_encoding == "target": # Temporarily map labels to numeric to calculate target means temp_num_target = df_model[args.label_col].map(mapping) temp_num_target = np.where( temp_num_target == -1, args.ordinal_num_classes, temp_num_target - args.ordinal_min_label ) global_mean = temp_num_target.mean() for col in current_args.cat_cols: if current_args.cat_encoding == "frequency": freq = df_model[col].value_counts() df_model[col + "_encoded"] = df_model[col].map(freq) elif current_args.cat_encoding == "target": # Smoothed Target Encoding to prevent overfitting rare provinces agg = pd.DataFrame({'target': temp_num_target, 'cat': df_model[col]}).groupby('cat')['target'].agg(['mean', 'count']) smoothing = 10 smooth_mean = (agg['count'] * agg['mean'] + smoothing * global_mean) / (agg['count'] + smoothing) df_model[col + "_encoded"] = df_model[col].map(smooth_mean).fillna(global_mean) else: # Default: "ordinal" df_model[col + "_encoded"] = df_model[col].astype('category').cat.codes # Append encoded columns to other_cols so they get bundled into additional_features encoded_cols = [c + "_encoded" for c in current_args.cat_cols] current_args.other_cols = list(current_args.other_cols) + encoded_cols # ========================================================================= if current_args.other_cols: df_model[current_args.other_cols] = df_model[current_args.other_cols].fillna(0) df_model["additional_features"] = list( StandardScaler().fit_transform(df_model[current_args.other_cols].values)) # --- DISPATCH: TF-IDF + LightGBM --- if config.get("task_type") == "tfidf_lgbm": df_model["label"] = df_model[args.label_col].astype(str).map(mapping) df_model["label"] = np.where( df_model["label"] == -1, args.ordinal_num_classes, df_model["label"] - args.ordinal_min_label) df_model["label"] = df_model["label"].astype(int) df_model["text"] = df_model[args.text_col] model_probs, oof_f1 = generate_kfold_oof_predictions_lgbm( current_args, df_model, total_classes) clean_name = model_name.split('/')[-1] model_names.append(model_name) f1_scores.append(float(oof_f1)) for i in range(total_classes): df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = model_probs[:, i] continue # --- DISPATCH: Transformer (2-Stage or 1-Stage) --- if config.get("split_unknown_stage", False): df_stage1 = df_model.copy() df_stage1["label"] = np.where( df_stage1[args.label_col].astype(str) == args.unknown_label_value, 1, 0) # When using KL/mixed objective, collapse multi-class soft labels to binary. # P(unknown) = final_logprob_ # P(known) = sum of all other final_logprob_* columns # Fail loudly if the expected unknown column is missing — a silent CE # fallback here would mask a misconfigured unknown_label_value. _use_kl = getattr(current_args, "loss_type", "ce") in ("kl", "mixed_kl_ce") if _use_kl: prefix = getattr(current_args, "soft_label_prefix", "final_logprob_") unknown_col = f"{prefix}{args.unknown_label_value}" all_soft = [c for c in df_stage1.columns if c.startswith(prefix)] known_cols = [c for c in all_soft if c != unknown_col] if unknown_col not in df_stage1.columns: raise ValueError( f"loss_type='{current_args.loss_type}' with split_unknown_stage=True " f"requires a soft label column '{unknown_col}', not found.\n" f"Available soft label columns: {all_soft}\n" f"--unknown_label_value is '{args.unknown_label_value}' — it must " f"exactly match the class name used when generating the soft labels." ) if not known_cols: raise ValueError( f"loss_type='{current_args.loss_type}' with split_unknown_stage=True " f"found '{unknown_col}' but no other soft label columns for P(known). " f"Available: {all_soft}" ) df_stage1["__soft_known"] = df_stage1[known_cols].sum(axis=1) df_stage1["__soft_unknown"] = df_stage1[unknown_col] total = (df_stage1["__soft_known"] + df_stage1["__soft_unknown"]).clip(lower=1e-7) df_stage1["__soft_known"] /= total df_stage1["__soft_unknown"] /= total df_stage1 = df_stage1.drop(columns=all_soft).rename(columns={ "__soft_known": f"{prefix}known", "__soft_unknown": f"{prefix}unknown", }) print(f" -> [Stage 1] Collapsed {len(all_soft)}-class soft labels " f"to binary (P_known, P_unknown) for {current_args.loss_type} training") print(f" -> [Stage 1] Unknown vs Rest Classification") stage1_probs, _ = generate_kfold_oof_predictions( current_args, df_stage1, "classification", [model_name], artifact_name=model_name + "__stage1", idx_to_name=internal_idx_to_name, custom_splits=final_splits, split_names=["final"] if final_splits else None) # Release stage1 model/optimizer memory before stage2 trains — # on tight GPUs the leftover allocations plus fragmentation # from dynamic-padding batches cause mid-training OOM. gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() p_known, p_unknown = stage1_probs[:, 0], stage1_probs[:, 1] odds_unknown = p_unknown / np.clip(p_known, 1e-7, 1.0) adjusted_odds_unknown = odds_unknown / args.ordinal_num_classes p_unknown_calibrated = adjusted_odds_unknown / (1.0 + adjusted_odds_unknown) p_known_calibrated = 1.0 - p_unknown_calibrated df_stage2 = df_model.copy() known_mask = df_stage2[args.label_col].astype(str) != args.unknown_label_value df_stage2["label"] = df_stage2[args.label_col].map(mapping) df_stage2.loc[known_mask, "label"] = ( df_stage2.loc[known_mask, "label"].astype(int) - args.ordinal_min_label) df_stage2.loc[~known_mask, "label"] = 0 train_df_stage2 = df_stage2[known_mask].reset_index(drop=True) print(f" -> [Stage 2] Ordinal Regression on Knowns") # In final mode, restrict the global holdout to the known-rows # subset that stage2 actually trains on (positions re-indexed). _s2_splits = _s2_names = None if final_splits is not None: _hold = np.zeros(len(df), dtype=bool) _hold[final_splits[0][1]] = True _known_pos = np.where(known_mask.values)[0] _sub_hold = _hold[_known_pos] _s2_splits = [(np.where(~_sub_hold)[0], np.where(_sub_hold)[0])] _s2_names = ["final"] stage2_probs_known, oof_f1 = generate_kfold_oof_predictions( current_args, train_df_stage2, "ordinal", [model_name], artifact_name=model_name + "__stage2", idx_to_name=internal_idx_to_name, custom_splits=_s2_splits, split_names=_s2_names) gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() # LEAK FIX: unknown rows were previously filled with a uniform # distribution selected via the ground-truth mask, giving the # meta-learner a label fingerprint that cannot exist at inference. # Predict them with the trained stage2 folds instead (leak-free: # no fold ever trained on these rows). stage2_full = np.zeros((len(df), args.ordinal_num_classes)) stage2_full[known_mask] = stage2_probs_known if (~known_mask).any(): print(f" -> [Stage 2] Predicting {(~known_mask).sum()} UNKNOWN " f"rows with fold models (leak-free fill)") stage2_full[~known_mask] = predict_ordinal_folds_on_rows( current_args, df_stage2[~known_mask], model_name, model_name + "__stage2", args.ordinal_num_classes, dir_names=["final"] if final_splits is not None else None) model_probs = np.zeros((len(df), total_classes)) for i in range(args.ordinal_num_classes): model_probs[:, i] = p_known_calibrated * stage2_full[:, i] model_probs[:, -1] = p_unknown_calibrated else: print(f" -> [Standard] Classification") df_model["label"] = df_model[args.label_col].astype(str).map(mapping) df_model["label"] = np.where( df_model["label"] == -1, args.ordinal_num_classes, df_model["label"] - args.ordinal_min_label) df_model["label"] = df_model["label"].astype(int) model_probs, oof_f1 = generate_kfold_oof_predictions( current_args, df_model, "classification", [model_name], idx_to_name=internal_idx_to_name, custom_splits=final_splits, split_names=["final"] if final_splits else None) clean_name = model_name.split('/')[-1] model_names.append(model_name) f1_scores.append(float(oof_f1)) for i in range(total_classes): df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = model_probs[:, i] with open(args.metadata_path, "w") as f: json.dump({"model_names": model_names, "f1_scores": f1_scores}, f, indent=2) if final_splits is not None: # FINAL MODE: model prob columns are only populated on the holdout # rows (__is_holdout). Ensemble analysis and distillation remedies # operate over all rows and exist to craft KL soft-label targets — # both are meaningless/garbage on a 300-row honest set, so skip. df.to_parquet(args.ensemble_output_path) print("\n[FINAL MODE] Analysis & distillation remedies skipped " "(only holdout rows carry predictions).") print("[FINAL MODE] Use rows where __is_holdout is True for " "meta-learner fitting. For KL soft-label targets, use a " "kfold-mode run.") print(f"\n[SUCCESS] Final-mode predictions saved → " f"{args.ensemble_output_path}") return analyze_ensemble_characteristics(df, args, model_names, f1_scores, total_classes) if args.mode == "generate": df.to_parquet(args.ensemble_output_path) print(f"\n[SUCCESS] Raw Generation saved → {args.ensemble_output_path}") return # ========================================================================= # PROCESSING PHASE # ========================================================================= if args.mode in ["process", "generate_and_process"]: if args.mode == "process": with open(args.metadata_path, "r") as f: metadata = json.load(f) model_names, f1_scores = metadata["model_names"], metadata["f1_scores"] # In standalone process mode, df must come from the previously generated # soft-labels parquet (which has the model logprob columns), not from # the original data_path which has none of those columns. df = pd.read_parquet(args.ensemble_output_path) df = process_ensemble_predictions( df, args, model_names, f1_scores, total_classes, internal_idx_to_name) df.to_parquet(args.ensemble_output_path) print("\n" + "="*70) print(f"[SUCCESS] Final Distilled Parquet saved → {args.ensemble_output_path}") print("="*70) outputs_to_backup = [args.metadata_path, args.ensemble_output_path] for fpath in outputs_to_backup: if fpath and Path(fpath).exists(): shutil.copy2(fpath, Path(args.artifacts_dir) / Path(fpath).name) print(f" -> Backed up final outputs to {args.artifacts_dir}/") if __name__ == "__main__": main()