trainer: converge to VM2 patches + re-apply _portable export (recovered from transcript)
7ae5b2d verified | #!/usr/bin/env python3 | |
| """ | |
| Meta-Learner Trainer with Fold-Consistency Analysis | |
| Trains a configurable meta-learner on top of OOF predictions from one or two | |
| ensemble runs (CE and/or KL), analyses rule stability across folds, and | |
| benchmarks inference time vs accuracy tradeoff. | |
| Usage: | |
| python meta_learner_trainer.py \ | |
| --ce_oof_path ce_ensemble.parquet \ | |
| --kl_oof_path kl_ensemble.parquet \ | |
| --data_path data.parquet \ | |
| --label_col category \ | |
| --mapping_dict_path mapping.json \ | |
| --ce_config_path ce_ensemble_config.json \ | |
| --kl_config_path kl_ensemble_config.json \ | |
| --meta_type lgbm \ | |
| --model_subset videberta-base,mlm_listing_checkpoint-32442,tfidf_lgbm \ | |
| --use_derived_features \ | |
| --fold_consistency_threshold 0.5 \ | |
| --k_folds 5 \ | |
| --output_dir meta_outputs | |
| Notes: | |
| - OOF parquets must contain columns like: {model_clean_name}_logprob_{class} | |
| as produced by ensemble_distillation_generator.py | |
| - model_subset filters by the "clean name" (model_name.split('/')[-1]) | |
| - If kl_oof_path is omitted, only CE OOF probs are used | |
| - Inference benchmarking simulates per-model forward pass timing on CPU | |
| to reflect production conditions (no GPU guarantee at serving time) | |
| """ | |
| import argparse | |
| import gc | |
| import json | |
| import pickle | |
| import time | |
| import warnings | |
| from pathlib import Path | |
| from itertools import combinations | |
| # Shared MetaLearner class — also imported by meta_learner_inference.py. | |
| # Must be imported (not defined inline) so pickle/joblib deserialisation works | |
| # from any script that loads a saved MetaLearner instance. | |
| import sys as _sys, os as _os | |
| _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) | |
| from meta_learner_core import MetaLearner # noqa: E402 | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import matplotlib.gridspec as gridspec | |
| import seaborn as sns | |
| from scipy.stats import spearmanr | |
| from scipy.optimize import minimize | |
| from sklearn.linear_model import LogisticRegression, Ridge | |
| from sklearn.calibration import CalibratedClassifierCV | |
| from sklearn.model_selection import StratifiedKFold | |
| from sklearn.metrics import precision_recall_fscore_support, log_loss | |
| from sklearn.preprocessing import LabelEncoder | |
| import lightgbm as lgb | |
| warnings.filterwarnings("ignore") | |
| # ============================================================================= | |
| # ARGUMENT PARSING | |
| # ============================================================================= | |
| def parse_args(): | |
| p = argparse.ArgumentParser() | |
| # --- Data inputs --- | |
| p.add_argument("--ce_oof_path", type=str, default=None, | |
| help="Parquet with CE ensemble OOF logprob columns") | |
| p.add_argument("--kl_oof_path", type=str, default=None, | |
| help="Parquet with KL student OOF logprob columns (optional)") | |
| p.add_argument("--data_path", type=str, required=True, | |
| help="Original data parquet with labels") | |
| p.add_argument("--label_col", type=str, required=True) | |
| p.add_argument("--mapping_dict_path", type=str, required=True, | |
| help="JSON mapping label -> integer index") | |
| p.add_argument("--ce_config_path", type=str, default=None, | |
| help="JSON config used to train CE ensemble") | |
| p.add_argument("--kl_config_path", type=str, default=None, | |
| help="JSON config used to train KL student ensemble") | |
| # --- Model selection --- | |
| p.add_argument("--unknown_label_value", type=str, default="N", | |
| help="Raw label string in data that represents the unknown/null class " | |
| "(maps to the 'UNKNOWN' OOF column). Default: 'N'.") | |
| p.add_argument("--model_subset", type=str, default=None, | |
| help="Comma-separated clean model names to include. " | |
| "If omitted, all trained models are used.") | |
| p.add_argument("--ensemble_source", type=str, default="both", | |
| choices=["ce", "kl", "both"], | |
| help="Which ensemble(s) to draw OOF features from.") | |
| # --- Meta-learner --- | |
| p.add_argument("--meta_type", type=str, default="lgbm", | |
| choices=["lgbm", "logistic", "ridge", "weighted_avg", "mlp"], | |
| help="Meta-learner architecture. " | |
| "lgbm: LightGBM — best with derived features (entropy, KL div). " | |
| "ridge: Ridge regression OvR + softmax — fastest, rarely overfits, " | |
| "strong baseline for pure probability stacking. " | |
| "logistic: Multinomial logistic with isotonic calibration. " | |
| "weighted_avg: Nelder-Mead optimized blend weights — most interpretable. " | |
| "mlp: small MLP with dropout — best when adding embeddings.") | |
| p.add_argument("--use_derived_features", action="store_true", | |
| help="Append entropy, KL-divergence, and per-class diff features.") | |
| p.add_argument("--compare_meta_types", action="store_true", | |
| help="Run ALL meta-learner types on the full feature set and print a " | |
| "comparison table. Useful for choosing --meta_type.") | |
| # --- Fold-consistency --- | |
| p.add_argument("--k_folds", type=int, default=5) | |
| p.add_argument("--fold_consistency_threshold", type=float, default=0.5, | |
| help="Max coefficient-of-variation for a feature to be " | |
| "considered 'stable'. Features above this CV are flagged.") | |
| p.add_argument("--seed", type=int, default=42) | |
| # --- Combination selection strategy --- | |
| p.add_argument("--selection_strategy", type=str, default="greedy", | |
| choices=["greedy", "exhaustive"], | |
| help="Strategy for the accuracy-vs-speed model subset sweep. " | |
| "greedy (default): forward selection — start with best single " | |
| "model, greedily add the most complementary model at each step. " | |
| "O(n^2) evaluations. Finds near-optimal subsets without exhaustive " | |
| "enumeration. " | |
| "exhaustive: try all subsets up to --max_combo_size (original " | |
| "behaviour). Use only for small n_models.") | |
| p.add_argument("--greedy_max_models", type=int, default=6, | |
| help="Maximum number of models to select in greedy forward selection. " | |
| "Selection stops earlier if F1 improvement < --greedy_min_gain.") | |
| p.add_argument("--greedy_min_gain", type=float, default=0.001, | |
| help="Minimum CV F1 gain to continue greedy selection. " | |
| "Stops adding models once the marginal gain falls below this.") | |
| # --- Option 2: OOF embeddings from fine-tuned fold models --- | |
| p.add_argument("--use_oof_embeddings", action="store_true", | |
| help="Extract [CLS] embeddings from each fine-tuned fold model using " | |
| "the same K-fold OOF structure. PCA-reduced per model (per-fold " | |
| "fit to avoid leakage), then concatenated to the feature matrix. " | |
| "Requires --text_col, --ce_artifacts_dir / --kl_artifacts_dir.") | |
| p.add_argument("--oof_emb_n_components", type=int, default=32, | |
| help="PCA components to keep per model for OOF embeddings.") | |
| p.add_argument("--oof_emb_batch_size", type=int, default=16, | |
| help="Batch size for OOF embedding extraction inference.") | |
| p.add_argument("--oof_emb_ce_cache", type=str, default="oof_emb_ce.parquet", | |
| help="Parquet cache path for CE OOF embeddings. Re-used on subsequent " | |
| "runs if the file exists and column count matches.") | |
| p.add_argument("--oof_emb_kl_cache", type=str, default="oof_emb_kl.parquet", | |
| help="Parquet cache path for KL OOF embeddings.") | |
| # --- Option 3: Frozen encoder embeddings --- | |
| p.add_argument("--frozen_encoder", type=str, default=None, | |
| help="Path or HuggingFace name of a pretrained encoder to use as a " | |
| "frozen feature extractor. No fine-tuning involved — embeddings " | |
| "are extracted once and cached. Example: " | |
| "pretrained_checkpoints/MikeGreen2710__mlm_listing_checkpoint-32442") | |
| p.add_argument("--frozen_encoder_tokenizer", type=str, default=None, | |
| help="Tokenizer for --frozen_encoder. Defaults to --frozen_encoder " | |
| "itself if not set. Example: VinAI/phobert-base") | |
| p.add_argument("--frozen_emb_n_components", type=int, default=64, | |
| help="PCA components for frozen encoder embeddings.") | |
| p.add_argument("--frozen_emb_batch_size", type=int, default=32, | |
| help="Batch size for frozen embedding extraction.") | |
| p.add_argument("--frozen_emb_cache", type=str, default="frozen_emb.parquet", | |
| help="Parquet cache path for frozen encoder embeddings.") | |
| # --- Inference benchmarking --- | |
| p.add_argument("--benchmark_n_samples", type=int, default=200, | |
| help="Number of samples to use for timing the base model forward passes.") | |
| p.add_argument("--benchmark_repeats", type=int, default=5, | |
| help="Repeats per model for the latency benchmark (median is taken).") | |
| p.add_argument("--benchmark_device", type=str, default="cpu", | |
| help="Device for base-model latency benchmarking ('cpu' or 'cuda'). " | |
| "Use the device that matches your production serving environment.") | |
| p.add_argument("--text_col", type=str, default=None, | |
| help="Column in --data_path containing raw text, used for tokenisation " | |
| "during base-model latency benchmarking. Required when " | |
| "--ce_artifacts_dir or --kl_artifacts_dir is provided.") | |
| p.add_argument("--max_length", type=int, default=256, | |
| help="Tokenisation max_length for the latency benchmark.") | |
| p.add_argument("--ce_artifacts_dir", type=str, default=None, | |
| help="Root artifact directory from the CE ensemble run " | |
| "(contains {model_safe_name}/fold_1/model/). " | |
| "When provided, each CE model is loaded and timed individually.") | |
| p.add_argument("--kl_artifacts_dir", type=str, default=None, | |
| help="Root artifact directory from the KL student ensemble run. " | |
| "When provided, each KL model is loaded and timed individually.") | |
| p.add_argument("--max_combo_size", type=int, default=3, | |
| help="Maximum subset size for the accuracy-vs-speed combination sweep. " | |
| "All subsets of size 1..max_combo_size are evaluated. " | |
| "Warning: combinatorial — keep <=4 for large model counts.") | |
| p.add_argument("--ce_metadata_path", type=str, default=None, | |
| help="Path to the CE ensemble metadata JSON (e.g. ensemble_metadata.json). " | |
| "If latency_ms is already present it will be reused; otherwise models " | |
| "are timed and the result is written back to this file.") | |
| p.add_argument("--kl_metadata_path", type=str, default=None, | |
| help="Path to the KL ensemble metadata JSON (e.g. ensemble_metadata_kl_round1.json). " | |
| "Same read/write behaviour as --ce_metadata_path.") | |
| # --- Output --- | |
| p.add_argument("--output_dir", type=str, default="meta_outputs") | |
| p.add_argument("--export_label", type=str, default=None, | |
| help="Label from accuracy_vs_speed.csv to export as a deployment " | |
| "artifact. If not set, the best F1 config is exported. " | |
| "Example: 'lgbm/KL:mlm_listing_che+KL:rembert'") | |
| p.add_argument("--export_only", action="store_true", | |
| help="Skip all training, benchmarking, and sweep steps. " | |
| "Load an existing --results_csv, re-train only the chosen " | |
| "config's meta-learner on the OOF parquets, and write " | |
| "deployment artifacts. Use after a full run to export a " | |
| "different config without repeating expensive CV/benchmarking.") | |
| p.add_argument("--results_csv", type=str, default=None, | |
| help="Path to an existing accuracy_vs_speed.csv produced by a " | |
| "previous full run. Required when --export_only is set.") | |
| return p.parse_args() | |
| # ============================================================================= | |
| # UTILITIES | |
| # ============================================================================= | |
| def load_mapping(path: str) -> dict: | |
| with open(path) as f: | |
| return json.load(f) | |
| def get_class_order_from_mapping(mapping: dict) -> list: | |
| """ | |
| Reconstruct the class index order used by ensemble_distillation_generator. | |
| The generator assigns: | |
| known classes → mapping_value - ordinal_min_label (so sort by value asc) | |
| unknown class → ordinal_num_classes (always placed last) | |
| We identify "unknown" as any entry whose value is < 0. | |
| """ | |
| known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1]) | |
| unknown = [k for k, v in mapping.items() if v < 0] | |
| return [k for k, _ in known] + unknown | |
| def get_active_models(config_path: str) -> list[dict]: | |
| """ | |
| Return models with use=True from the config. | |
| The 'trained' flag has been removed from config files — the filesystem | |
| (artifact_exists) is the source of truth for whether a model has been | |
| trained. Here we only need the list of enabled model configs to know | |
| which OOF columns to expect in the parquet and how to configure serving. | |
| """ | |
| with open(config_path) as f: | |
| configs = json.load(f) | |
| return [c for c in configs if c.get("use", True)] | |
| def clean_name(model_name: str) -> str: | |
| return model_name.split("/")[-1] | |
| def logprob_cols_for_model(df_cols: list, model_clean_name: str, | |
| class_order: list = None) -> list: | |
| """ | |
| Return logprob columns for a model in the correct class-index order. | |
| class_order: list of class-name strings ordered by their 0-based index, | |
| as returned by get_class_order_from_mapping(mapping). | |
| When provided, columns are returned in that order so that | |
| col i corresponds to class i — matching how y is encoded. | |
| Falls back to alphabetical if not provided (fine for LightGBM | |
| features, broken for weighted_avg argmax comparisons). | |
| """ | |
| prefix = f"{model_clean_name}_logprob_" | |
| available = {c.split("_logprob_")[1]: c for c in df_cols if c.startswith(prefix)} | |
| if class_order is not None: | |
| ordered = [available[cls] for cls in class_order if cls in available] | |
| covered = set(ordered) | |
| ordered += [c for c in sorted(available.values()) if c not in covered] | |
| return ordered | |
| return sorted(available.values()) | |
| def get_class_order_from_mapping(mapping: dict) -> list: | |
| """ | |
| Return class name strings in 0-based index order, matching the generator. | |
| Known classes (value >= 0) first, sorted by value. Unknown (value < 0) last. | |
| """ | |
| known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1]) | |
| unknown = [k for k, v in mapping.items() if v < 0] | |
| return [k for k, _ in known] + unknown | |
| def entropy(probs: np.ndarray, eps: float = 1e-7) -> np.ndarray: | |
| p = np.clip(probs, eps, 1.0) | |
| return -np.sum(p * np.log(p), axis=1) | |
| def kl_div_row(p: np.ndarray, q: np.ndarray, eps: float = 1e-7) -> np.ndarray: | |
| """Symmetric KL divergence between two prob arrays, row-wise.""" | |
| p = np.clip(p, eps, 1.0) | |
| q = np.clip(q, eps, 1.0) | |
| return 0.5 * (np.sum(p * np.log(p / q), axis=1) + | |
| np.sum(q * np.log(q / p), axis=1)) | |
| # ============================================================================= | |
| # FEATURE BUILDER | |
| # ============================================================================= | |
| class OOFFeatureBuilder: | |
| """ | |
| Builds a feature matrix from OOF probability columns. | |
| Feature groups: | |
| base : raw per-class probs for every selected model | |
| derived : entropy, argmax, per-pair KL divergence, CE-KL diff | |
| """ | |
| def __init__(self, ce_df, kl_df, ce_models, kl_models, | |
| model_subset=None, use_derived=True, | |
| ensemble_source="both", class_order=None): | |
| self.ce_df = ce_df | |
| self.kl_df = kl_df | |
| self.ce_models = ce_models # list of clean names | |
| self.kl_models = kl_models # list of clean names | |
| self.subset = set(model_subset) if model_subset else None | |
| self.use_derived = use_derived | |
| self.source = ensemble_source | |
| self.class_order = class_order # ordered class names from mapping | |
| # Resolved model lists | |
| self._ce_active = self._filter(self.ce_models, "ce") | |
| self._kl_active = self._filter(self.kl_models, "kl") | |
| self.feature_names = [] | |
| def _filter(self, names, source): | |
| if source == "ce" and self.source == "kl": | |
| return [] | |
| if source == "kl" and self.source == "ce": | |
| return [] | |
| if self.subset: | |
| return [n for n in names if n in self.subset] | |
| return names | |
| def _get_probs(self, df, model_name): | |
| cols = logprob_cols_for_model(list(df.columns), model_name, self.class_order) | |
| if not cols: | |
| return None, [] | |
| return df[cols].values, cols | |
| def build(self): | |
| blocks = [] | |
| names = [] | |
| # --- CE base probs --- | |
| for m in self._ce_active: | |
| probs, cols = self._get_probs(self.ce_df, m) | |
| if probs is None: | |
| print(f" [WARN] CE model {m}: no logprob columns found — skipping") | |
| continue | |
| blocks.append(probs) | |
| names.extend([f"CE_{m}_{c.split('_logprob_')[1]}" for c in cols]) | |
| # --- KL base probs --- | |
| for m in self._kl_active: | |
| if self.kl_df is None: | |
| break | |
| probs, cols = self._get_probs(self.kl_df, m) | |
| if probs is None: | |
| print(f" [WARN] KL model {m}: no logprob columns found — skipping") | |
| continue | |
| blocks.append(probs) | |
| names.extend([f"KL_{m}_{c.split('_logprob_')[1]}" for c in cols]) | |
| if not blocks: | |
| raise ValueError("No features built — check model_subset and OOF column names.") | |
| X = np.hstack(blocks) | |
| # --- Derived features --- | |
| if self.use_derived: | |
| derived_blocks = [] | |
| derived_names = [] | |
| n_classes = blocks[0].shape[1] | |
| all_probs = {} | |
| for i, m in enumerate(self._ce_active): | |
| p, _ = self._get_probs(self.ce_df, m) | |
| if p is None: continue | |
| all_probs[f"CE_{m}"] = p | |
| ent = entropy(p) | |
| derived_blocks.append(ent.reshape(-1, 1)) | |
| derived_names.append(f"CE_{m}_entropy") | |
| am = np.argmax(p, axis=1).reshape(-1, 1).astype(float) | |
| derived_blocks.append(am) | |
| derived_names.append(f"CE_{m}_argmax") | |
| for m in self._kl_active: | |
| if self.kl_df is None: break | |
| p, _ = self._get_probs(self.kl_df, m) | |
| if p is None: continue | |
| all_probs[f"KL_{m}"] = p | |
| ent = entropy(p) | |
| derived_blocks.append(ent.reshape(-1, 1)) | |
| derived_names.append(f"KL_{m}_entropy") | |
| am = np.argmax(p, axis=1).reshape(-1, 1).astype(float) | |
| derived_blocks.append(am) | |
| derived_names.append(f"KL_{m}_argmax") | |
| # Pairwise symmetric KL between CE and KL versions of same model | |
| for m in self._ce_active: | |
| ce_key = f"CE_{m}" | |
| kl_key = f"KL_{m}" | |
| if ce_key in all_probs and kl_key in all_probs: | |
| div = kl_div_row(all_probs[ce_key], all_probs[kl_key]) | |
| derived_blocks.append(div.reshape(-1, 1)) | |
| derived_names.append(f"CE_KL_{m}_sym_kl") | |
| diff = all_probs[ce_key] - all_probs[kl_key] | |
| derived_blocks.append(diff) | |
| derived_names.extend( | |
| [f"CE_KL_{m}_diff_class{i}" for i in range(diff.shape[1])]) | |
| # Pairwise disagreement between CE models | |
| ce_prob_list = [(k, v) for k, v in all_probs.items() if k.startswith("CE_")] | |
| for (n1, p1), (n2, p2) in combinations(ce_prob_list, 2): | |
| div = kl_div_row(p1, p2) | |
| derived_blocks.append(div.reshape(-1, 1)) | |
| derived_names.append(f"CE_pair_{n1}_vs_{n2}_kl") | |
| if derived_blocks: | |
| X = np.hstack([X] + derived_blocks) | |
| names.extend(derived_names) | |
| self.feature_names = names | |
| return X, names | |
| # ============================================================================= | |
| # META-LEARNER WRAPPER | |
| # ============================================================================= | |
| # MetaLearner lives in meta_learner_core.py — imported below. | |
| # See that file to modify the class. | |
| # ============================================================================= | |
| # FOLD CONSISTENCY ANALYSER | |
| # ============================================================================= | |
| def fold_consistency_analysis(X, y, feature_names, meta_type, n_classes, | |
| k_folds, seed, threshold, n_prob_cols=None): | |
| """ | |
| Train a meta-learner on each fold's training split, record feature importances, | |
| then compute coefficient-of-variation across folds. | |
| Returns: | |
| fold_importances : (k_folds, n_features) array | |
| cv_per_feature : (n_features,) array of CV values | |
| stable_mask : boolean mask of stable features (CV <= threshold) | |
| """ | |
| print(f"\n{'='*60}") | |
| print("FOLD CONSISTENCY ANALYSIS") | |
| print(f"{'='*60}") | |
| kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed) | |
| fold_importances = [] | |
| fold_val_f1s = [] | |
| for fold, (train_idx, val_idx) in enumerate(kfold.split(X, y)): | |
| X_tr, X_val = X[train_idx], X[val_idx] | |
| y_tr, y_val = y[train_idx], y[val_idx] | |
| meta = MetaLearner(meta_type, n_classes, seed, | |
| n_prob_cols=n_prob_cols).fit(X_tr, y_tr) | |
| val_preds = np.argmax(meta.predict_proba(X_val), axis=1) | |
| f1 = precision_recall_fscore_support( | |
| y_val, val_preds, average="macro", zero_division=0)[2] | |
| fold_val_f1s.append(f1) | |
| print(f" Fold {fold+1}/{k_folds} — Val Macro F1: {f1:.4f}") | |
| imp = meta.get_feature_importances() | |
| if imp is not None: | |
| fold_importances.append(imp) | |
| if not fold_importances: | |
| print(" [WARN] Meta-learner does not expose feature importances.") | |
| return None, None, None, fold_val_f1s | |
| fold_importances = np.array(fold_importances) # (k, n_features) | |
| # Normalise each fold's importances to sum to 1 (comparable scale) | |
| fold_importances_norm = (fold_importances / | |
| fold_importances.sum(axis=1, keepdims=True).clip(min=1e-9)) | |
| mean_imp = fold_importances_norm.mean(axis=0) | |
| std_imp = fold_importances_norm.std(axis=0) | |
| cv = np.where(mean_imp > 1e-9, std_imp / mean_imp, np.inf) | |
| stable_mask = cv <= threshold | |
| n_stable = stable_mask.sum() | |
| print(f"\n Feature stability (CV threshold={threshold}):") | |
| print(f" Stable features : {n_stable}/{len(feature_names)}") | |
| print(f" Mean Val F1 : {np.mean(fold_val_f1s):.4f} ± {np.std(fold_val_f1s):.4f}") | |
| # Top 20 most stable important features | |
| rank = np.argsort(-mean_imp) | |
| print(f"\n Top-20 features by mean importance (stable=✓, unstable=✗):") | |
| for i, idx in enumerate(rank[:20]): | |
| tag = "✓" if stable_mask[idx] else "✗" | |
| print(f" {tag} [{cv[idx]:.2f} CV] {feature_names[idx]:<60s} " | |
| f"imp={mean_imp[idx]:.4f}") | |
| return fold_importances_norm, cv, stable_mask, fold_val_f1s | |
| # ============================================================================= | |
| # INFERENCE TIME BENCHMARK | |
| # ============================================================================= | |
| # ============================================================================= | |
| # PER-MODEL LATENCY BENCHMARKING | |
| # ============================================================================= | |
| def _get_model_fold_dir(artifacts_dir: str, model_name: str, stage: str = None) -> Path: | |
| """ | |
| Resolve the saved fold-1 model directory for a given model. | |
| Mirrors the artifact naming in ensemble_distillation_generator.py: | |
| artifact_name = model_name (or model_name + "__stage1" / "__stage2") | |
| safe_name = artifact_name.replace("/", "__") | |
| """ | |
| artifact_name = model_name if stage is None else f"{model_name}__{stage}" | |
| safe_name = artifact_name.replace("/", "__") | |
| return Path(artifacts_dir) / safe_name / "fold_1" / "model" | |
| def _normalise_device(device_str: str) -> str: | |
| """Map user-friendly aliases ('gpu') to PyTorch device strings ('cuda').""" | |
| return "cuda" if device_str.lower() == "gpu" else device_str.lower() | |
| def benchmark_transformer_model( | |
| original_model_name: str, | |
| tokenizer_name: str, | |
| texts: list, | |
| max_length: int, | |
| device: str, | |
| n_repeats: int, | |
| drop_token_type_ids: bool = False, | |
| use_fp16: bool = False, | |
| use_bf16: bool = False, | |
| ) -> float: | |
| """ | |
| Load the BASE ENCODER of a model from its original pretrained checkpoint and | |
| time its forward pass. | |
| Why the base encoder, not the saved fold model? | |
| ------------------------------------------------ | |
| The generator saves models as custom nn.Module wrappers: | |
| - MultimodalClassificationModel (models with other_cols) | |
| - OrdinalRegressionModel (task_type=ordinal) | |
| These are not AutoModelForSequenceClassification and cannot be loaded | |
| with it — their state_dict keys have 'base_model.*' prefixes that | |
| AutoModel* classes do not recognise. | |
| For latency benchmarking this does not matter: the transformer encoder | |
| is >99% of inference time. The classification/ordinal head and the | |
| extra tabular features (other_cols) add <1ms and are not what we are | |
| comparing across models. | |
| We load from the ORIGINAL pretrained checkpoint (always available, always | |
| has model_type, no custom wrapper) and apply the same dtype (fp16/bf16) | |
| that was used during training so the timing reflects production conditions. | |
| """ | |
| import torch | |
| from transformers import AutoModel, AutoTokenizer | |
| device = _normalise_device(device) | |
| tok_src = tokenizer_name if tokenizer_name else original_model_name | |
| tokenizer = AutoTokenizer.from_pretrained(tok_src, trust_remote_code=True) | |
| dtype = (torch.bfloat16 if use_bf16 | |
| else torch.float16 if use_fp16 | |
| else torch.float32) | |
| model = AutoModel.from_pretrained( | |
| original_model_name, trust_remote_code=True, torch_dtype=dtype) | |
| model.eval() | |
| model.to(device) | |
| enc = tokenizer( | |
| texts, padding=True, truncation=True, | |
| max_length=max_length, return_tensors="pt" | |
| ) | |
| if drop_token_type_ids: | |
| enc.pop("token_type_ids", None) | |
| enc = {k: v.to(device) for k, v in enc.items()} | |
| is_cuda = device.startswith("cuda") | |
| # Warmup | |
| with torch.no_grad(): | |
| _ = model(**enc) | |
| if is_cuda: | |
| torch.cuda.synchronize() | |
| times = [] | |
| for _ in range(n_repeats): | |
| if is_cuda: | |
| torch.cuda.synchronize() | |
| t0 = time.perf_counter() | |
| with torch.no_grad(): | |
| _ = model(**enc) | |
| if is_cuda: | |
| torch.cuda.synchronize() | |
| times.append(time.perf_counter() - t0) | |
| del model, enc | |
| if is_cuda: | |
| torch.cuda.empty_cache() | |
| gc.collect() | |
| return float(np.median(times)) * 1000.0 # ms | |
| def benchmark_lgbm_model(artifacts_dir: str, texts: list, | |
| n_tabular_features: int, n_repeats: int) -> float: | |
| """ | |
| Load the TF-IDF + LightGBM pipeline pickle from fold_1 and time it. | |
| n_tabular_features: len(cfg["other_cols"]) — the number of extra numeric | |
| columns that were appended during training (on_front_street, etc.). | |
| For timing we pad with zeros: the values don't affect latency, only the | |
| feature count matters for the LightGBM predict call. | |
| """ | |
| from scipy.sparse import hstack, csr_matrix | |
| pkl_path = Path(artifacts_dir) / "tfidf_lgbm" / "fold_1" / "model.pkl" | |
| if not pkl_path.exists(): | |
| return None | |
| with open(pkl_path, "rb") as f: | |
| bundle = pickle.load(f) | |
| cal = bundle["calibrated_model"] | |
| wtf = bundle["word_tfidf"] | |
| ctf = bundle["char_tfidf"] | |
| X = hstack([wtf.transform(texts), ctf.transform(texts)]) | |
| if n_tabular_features > 0: | |
| tab_zeros = csr_matrix((len(texts), n_tabular_features), dtype="float32") | |
| X = hstack([X, tab_zeros]) | |
| times = [] | |
| for _ in range(n_repeats): | |
| t0 = time.perf_counter() | |
| _ = cal.predict_proba(X) | |
| times.append(time.perf_counter() - t0) | |
| return float(np.median(times)) * 1000.0 # ms | |
| # ============================================================================= | |
| # EMBEDDING EXTRACTION — OPTIONS 2 AND 3 | |
| # ============================================================================= | |
| def _load_encoder_from_fold(fold_model_dir, original_model_name, | |
| use_fp16, use_bf16, device): | |
| """ | |
| Load just the base transformer encoder from a saved fold checkpoint. | |
| The generator saves models as custom wrappers (MultimodalClassificationModel, | |
| OrdinalRegressionModel) whose state_dict keys have a "base_model." prefix. | |
| We strip that prefix to reconstruct the plain AutoModel state dict. | |
| For models saved as plain AutoModelForSequenceClassification (no other_cols), | |
| keys are direct and strict=False discards the classifier head automatically. | |
| """ | |
| import torch | |
| from transformers import AutoModel | |
| fold_model_dir = Path(fold_model_dir) | |
| st_path = fold_model_dir / "model.safetensors" | |
| use_safe = st_path.exists() | |
| if not use_safe: | |
| st_path = fold_model_dir / "pytorch_model.bin" | |
| if not st_path.exists(): | |
| raise FileNotFoundError("No weights file in " + str(fold_model_dir)) | |
| if use_safe: | |
| from safetensors.torch import load_file | |
| raw_sd = load_file(str(st_path)) | |
| else: | |
| raw_sd = torch.load(str(st_path), map_location="cpu", weights_only=True) | |
| # Strip "base_model." prefix (custom wrapper models) | |
| encoder_sd = {k[len("base_model."):]: v | |
| for k, v in raw_sd.items() | |
| if k.startswith("base_model.")} | |
| if not encoder_sd: | |
| # Plain AutoModelForSequenceClassification — use full state dict, | |
| # strict=False will ignore classifier/pooler keys. | |
| encoder_sd = raw_sd | |
| dtype = (torch.bfloat16 if use_bf16 else | |
| torch.float16 if use_fp16 else | |
| torch.float32) | |
| encoder = AutoModel.from_pretrained( | |
| original_model_name, trust_remote_code=True, dtype=dtype) | |
| missing, unexpected = encoder.load_state_dict(encoder_sd, strict=False) | |
| n_loaded = len(encoder_sd) - len(unexpected) | |
| print(" weights loaded={} missing={} unexpected={}".format( | |
| n_loaded, len(missing), len(unexpected))) | |
| encoder.eval() | |
| encoder.to(device) | |
| return encoder | |
| def _encode_texts(encoder, tokenizer, texts, max_length, device, | |
| batch_size, drop_token_type_ids): | |
| """Run encoder on texts, return CLS embeddings as float32 numpy array.""" | |
| import torch | |
| all_embs = [] | |
| for start in range(0, len(texts), batch_size): | |
| batch = texts[start:start + batch_size] | |
| enc = tokenizer(batch, padding=True, truncation=True, | |
| max_length=max_length, return_tensors="pt") | |
| if drop_token_type_ids: | |
| enc.pop("token_type_ids", None) | |
| enc = {k: v.to(device) for k, v in enc.items()} | |
| with torch.no_grad(): | |
| out = encoder(**enc) | |
| cls = out.last_hidden_state[:, 0, :].float().cpu().numpy() | |
| all_embs.append(cls) | |
| return np.vstack(all_embs) | |
| def extract_oof_embeddings(ce_configs, kl_configs, | |
| ce_artifacts_dir, kl_artifacts_dir, | |
| texts, y, | |
| max_length, device, n_components, | |
| batch_size, k_folds, seed, | |
| ce_cache, kl_cache): | |
| """ | |
| Option 2: extract OOF embeddings from fine-tuned fold checkpoints. | |
| For each model and each fold: | |
| 1. Load the fold-k checkpoint encoder (fine-tuned weights). | |
| 2. Encode the fold-k validation samples -> raw CLS embeddings. | |
| After all folds, fit PCA on the full OOF embedding matrix for each model | |
| (PCA directions from embedding geometry, no label involvement — safe). | |
| Results are cached; subsequent calls with the same cache path are instant. | |
| split_unknown_stage models: use stage1 checkpoint (trained on all samples as | |
| binary; stage2 only covers known samples so cannot fill the full OOF matrix). | |
| """ | |
| from sklearn.decomposition import PCA | |
| from transformers import AutoTokenizer | |
| device = _normalise_device(device) | |
| kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed) | |
| def _extract_one_ensemble(configs, artifacts_dir, tag, cache_path): | |
| cache = Path(cache_path) | |
| if cache.exists(): | |
| print(" [{}] Loading cached OOF embeddings <- {}".format(tag, cache_path)) | |
| df_c = pd.read_parquet(cache) | |
| return df_c.values, list(df_c.columns) | |
| blocks, names = [], [] | |
| trained = [c for c in configs if c.get("use", True)] | |
| for cfg in trained: | |
| mname = cfg["model_name"] | |
| cname = clean_name(mname) | |
| tok_name = cfg.get("tokenizer_name") or mname | |
| drop_tti = cfg.get("drop_token_type_ids", False) | |
| split_unk = cfg.get("split_unknown_stage", False) | |
| use_fp16 = cfg.get("use_fp16", False) | |
| use_bf16 = cfg.get("use_bf16", False) | |
| # For split_unknown_stage use stage1 (covers all samples) | |
| stage = "stage1" if split_unk else None | |
| task = cfg.get("task_type", "classification") | |
| if task == "tfidf_lgbm": | |
| print(" [{}] {} is tfidf_lgbm — no embeddings, skipping".format(tag, cname)) | |
| continue | |
| print(" [{}] OOF embeddings: {} ...".format(tag, cname)) | |
| tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True) | |
| n_samples = len(texts) | |
| raw_oof = None # (n_samples, hidden_dim) filled fold by fold | |
| for fold_idx, (_, val_idx) in enumerate(kfold.split(texts, y)): | |
| fold_n = fold_idx + 1 | |
| artifact_name = (mname if stage is None | |
| else mname + "__" + stage) | |
| safe_name = artifact_name.replace("/", "__") | |
| fold_dir = (Path(artifacts_dir) / safe_name | |
| / ("fold_" + str(fold_n)) / "model") | |
| if not fold_dir.exists(): | |
| print(" [WARN] fold {} dir not found: {}".format(fold_n, fold_dir)) | |
| continue | |
| encoder = _load_encoder_from_fold( | |
| fold_dir, mname, use_fp16, use_bf16, device) | |
| val_texts = [texts[i] for i in val_idx] | |
| val_embs = _encode_texts( | |
| encoder, tokenizer, val_texts, max_length, | |
| device, batch_size, drop_tti) # (n_val, H) | |
| if raw_oof is None: | |
| raw_oof = np.zeros((n_samples, val_embs.shape[1]), | |
| dtype=np.float32) | |
| raw_oof[val_idx] = val_embs | |
| del encoder | |
| gc.collect() | |
| import torch | |
| if device.startswith("cuda"): | |
| torch.cuda.empty_cache() | |
| print(" fold {}/{} done".format(fold_n, k_folds)) | |
| if raw_oof is None: | |
| print(" [{}] {} — no folds loaded, skipping".format(tag, cname)) | |
| continue | |
| # PCA fitted on full OOF matrix (no label info in embeddings -> safe) | |
| n_keep = min(n_components, raw_oof.shape[1], raw_oof.shape[0]) | |
| pca = PCA(n_components=n_keep, random_state=seed) | |
| reduced = pca.fit_transform(raw_oof).astype(np.float32) | |
| var = pca.explained_variance_ratio_.sum() | |
| print(" PCA {}->{} var_explained={:.1%}".format( | |
| raw_oof.shape[1], n_keep, var)) | |
| blocks.append(reduced) | |
| names.extend(["{}_OOF_{}_pc{}".format(tag, cname, i) | |
| for i in range(n_keep)]) | |
| if not blocks: | |
| return np.zeros((len(texts), 0), dtype=np.float32), [] | |
| X_emb = np.hstack(blocks) | |
| emb_df = pd.DataFrame(X_emb, columns=names) | |
| emb_df.to_parquet(cache_path) | |
| print(" [{}] OOF embeddings cached -> {} shape={}".format( | |
| tag, cache_path, X_emb.shape)) | |
| return X_emb, names | |
| X_ce, n_ce = _extract_one_ensemble( | |
| ce_configs, ce_artifacts_dir, "CE", ce_cache) if ce_artifacts_dir else ( | |
| np.zeros((len(texts), 0)), []) | |
| X_kl, n_kl = _extract_one_ensemble( | |
| kl_configs, kl_artifacts_dir, "KL", kl_cache) if kl_artifacts_dir else ( | |
| np.zeros((len(texts), 0)), []) | |
| parts = [x for x in [X_ce, X_kl] if x.shape[1] > 0] | |
| nparts = n_ce + n_kl | |
| if not parts: | |
| return np.zeros((len(texts), 0), dtype=np.float32), [] | |
| return np.hstack(parts), nparts | |
| def extract_frozen_embeddings(model_name, tokenizer_name, texts, | |
| max_length, device, n_components, | |
| batch_size, cache_path): | |
| """ | |
| Option 3: extract embeddings from a frozen (non-fine-tuned) pretrained encoder. | |
| No fold structure needed — pretrained weights never see labels so there is no | |
| leakage risk. PCA is fitted on the full dataset. Results are cached. | |
| """ | |
| from sklearn.decomposition import PCA | |
| from transformers import AutoModel, AutoTokenizer | |
| import torch | |
| cache = Path(cache_path) | |
| if cache.exists(): | |
| print(" Loading cached frozen embeddings <- {}".format(cache_path)) | |
| df_c = pd.read_parquet(cache) | |
| return df_c.values, list(df_c.columns) | |
| device = _normalise_device(device) | |
| cname = clean_name(model_name) | |
| tok_src = tokenizer_name if tokenizer_name else model_name | |
| print(" Frozen encoder embeddings: {} ({} samples)...".format( | |
| model_name, len(texts))) | |
| tokenizer = AutoTokenizer.from_pretrained(tok_src, trust_remote_code=True) | |
| encoder = AutoModel.from_pretrained(model_name, trust_remote_code=True) | |
| encoder.eval() | |
| encoder.to(device) | |
| all_embs = [] | |
| n_batches = (len(texts) + batch_size - 1) // batch_size | |
| for b_idx, start in enumerate(range(0, len(texts), batch_size)): | |
| batch = texts[start:start + batch_size] | |
| enc = tokenizer(batch, padding=True, truncation=True, | |
| max_length=max_length, return_tensors="pt") | |
| enc = {k: v.to(device) for k, v in enc.items()} | |
| with torch.no_grad(): | |
| out = encoder(**enc) | |
| cls = out.last_hidden_state[:, 0, :].float().cpu().numpy() | |
| all_embs.append(cls) | |
| if b_idx % 50 == 0 or b_idx == n_batches - 1: | |
| print(" batch {}/{}".format(b_idx + 1, n_batches)) | |
| del encoder | |
| gc.collect() | |
| if device.startswith("cuda"): | |
| torch.cuda.empty_cache() | |
| embeddings = np.vstack(all_embs) # (n_samples, H) | |
| n_keep = min(n_components, embeddings.shape[1], embeddings.shape[0]) | |
| pca = PCA(n_components=n_keep) | |
| reduced = pca.fit_transform(embeddings).astype(np.float32) | |
| var = pca.explained_variance_ratio_.sum() | |
| print(" PCA {}->{} var_explained={:.1%}".format( | |
| embeddings.shape[1], n_keep, var)) | |
| col_names = ["FROZEN_{}_pc{}".format(cname, i) for i in range(n_keep)] | |
| pd.DataFrame(reduced, columns=col_names).to_parquet(cache_path) | |
| print(" Frozen embeddings cached -> {} shape={}".format( | |
| cache_path, reduced.shape)) | |
| # CRITICAL: save the fitted PCA + the exact tokenisation settings so that | |
| # inference reproduces the SAME transform. Re-fitting PCA on inference data | |
| # would yield different components and break the meta-learner. | |
| import joblib | |
| pca_path = str(Path(cache_path).with_suffix("")) + "_pca.joblib" | |
| joblib.dump({ | |
| "pca": pca, | |
| "col_names": col_names, | |
| "model_name": model_name, | |
| "tokenizer_name": tok_src, | |
| "max_length": max_length, | |
| "n_components": n_keep, | |
| "hidden_dim": embeddings.shape[1], | |
| }, pca_path) | |
| print(" Frozen PCA transform saved -> {}".format(pca_path)) | |
| return reduced, col_names | |
| def _load_metadata(path: str) -> dict: | |
| if path and Path(path).exists(): | |
| with open(path) as f: | |
| return json.load(f) | |
| return {} | |
| def _save_metadata(path: str, data: dict): | |
| with open(path, "w") as f: | |
| json.dump(data, f, indent=2) | |
| print(f" Saved latency_ms → {path}") | |
| def build_latency_map( | |
| ce_configs: list, | |
| kl_configs: list, | |
| ce_artifacts_dir: str, | |
| kl_artifacts_dir: str, | |
| ce_metadata_path: str, | |
| kl_metadata_path: str, | |
| texts: list, | |
| max_length: int, | |
| device: str, | |
| n_repeats: int, | |
| ) -> dict: | |
| """ | |
| Return a latency map: {"CE:{clean_name}": ms, "KL:{clean_name}": ms, ...} | |
| For each ensemble (CE / KL): | |
| 1. Load its metadata JSON. | |
| 2. If "latency_ms" key already exists → use cached values, skip loading models. | |
| 3. Otherwise → benchmark every trained model, write results back to the metadata file. | |
| Latency is stored in metadata as {clean_name: ms} (no CE/KL prefix, since each | |
| metadata file already belongs to one ensemble). The combined latency_map uses the | |
| "CE:" / "KL:" prefix so callers can look up models unambiguously. | |
| """ | |
| latency_map = {} | |
| device = _normalise_device(device) # "gpu" -> "cuda" etc. | |
| def _bench_ensemble(configs, artifacts_dir, metadata_path, tag): | |
| """Handle one ensemble (CE or KL): check cache, bench if needed, write back.""" | |
| meta = _load_metadata(metadata_path) | |
| cached = meta.get("latency_ms", {}) # {clean_name: ms} | |
| # Check which trained models already have cached latency | |
| trained = [c for c in configs if c.get("use", True)] | |
| trained_names = [clean_name(c["model_name"]) for c in trained] | |
| missing_names = [n for n in trained_names if n not in cached] | |
| if not missing_names: | |
| print(f" [{tag}] All {len(trained_names)} model latencies loaded from {metadata_path}") | |
| for n in trained_names: | |
| latency_map[f"{tag}:{n}"] = cached[n] | |
| return | |
| # Some or all need benchmarking | |
| if cached: | |
| print(f" [{tag}] {len(cached)} cached, {len(missing_names)} need benchmarking: " | |
| f"{missing_names}") | |
| else: | |
| print(f" [{tag}] No cached latencies in {metadata_path} — timing all models.") | |
| newly_measured = {} | |
| def _bench_one(cfg): | |
| mname = cfg["model_name"] | |
| cname = clean_name(mname) | |
| task = cfg.get("task_type", "classification") | |
| tok_name = cfg.get("tokenizer_name", None) | |
| drop_tti = cfg.get("drop_token_type_ids", False) | |
| split_unk = cfg.get("split_unknown_stage", False) | |
| use_fp16 = cfg.get("use_fp16", False) | |
| use_bf16 = cfg.get("use_bf16", False) | |
| # Use cache if available | |
| if cname in cached: | |
| print(f" [{tag}] {cname}: using cached {cached[cname]:.1f} ms") | |
| latency_map[f"{tag}:{cname}"] = cached[cname] | |
| return | |
| print(f" [{tag}] Timing {cname} ...") | |
| if task == "tfidf_lgbm": | |
| n_tab = len(cfg.get("other_cols", [])) | |
| ms = benchmark_lgbm_model(artifacts_dir, texts, n_tab, n_repeats) | |
| if ms is None: | |
| print(f" [WARN] pickle not found — skipping") | |
| return | |
| elif split_unk: | |
| # 2-stage model: encoder runs twice (once per stage) with the same | |
| # base architecture, so we time once and double it. | |
| ms_single = benchmark_transformer_model( | |
| mname, tok_name, texts, max_length, device, n_repeats, | |
| drop_tti, use_fp16, use_bf16) | |
| ms = ms_single * 2.0 | |
| print(f" encoder x2 (stage1+stage2): {ms:.1f} ms / {len(texts)} samples") | |
| else: | |
| ms = benchmark_transformer_model( | |
| mname, tok_name, texts, max_length, device, n_repeats, | |
| drop_tti, use_fp16, use_bf16) | |
| print(f" {ms:.1f} ms / {len(texts)} samples") | |
| latency_map[f"{tag}:{cname}"] = ms | |
| newly_measured[cname] = round(ms, 3) | |
| for cfg in trained: | |
| _bench_one(cfg) | |
| # Write back to metadata only if we measured anything new | |
| if newly_measured and metadata_path: | |
| meta["latency_ms"] = {**cached, **newly_measured} | |
| meta["latency_benchmark_n_samples"] = len(texts) | |
| meta["latency_benchmark_device"] = device | |
| _save_metadata(metadata_path, meta) | |
| if ce_artifacts_dir: | |
| _bench_ensemble(ce_configs, ce_artifacts_dir, ce_metadata_path, "CE") | |
| if kl_artifacts_dir: | |
| _bench_ensemble(kl_configs, kl_artifacts_dir, kl_metadata_path, "KL") | |
| return latency_map | |
| def lookup_subset_latency(ce_sub, kl_sub, latency_map, | |
| extra_latency_ms: float = 0.0): | |
| """ | |
| Sum latencies for all models in a subset. Returns (total_ms, any_missing). | |
| extra_latency_ms: fixed overhead to add to every config regardless of which | |
| base models are selected (e.g. frozen encoder that always runs at inference, | |
| OOF embedding encoders that run at inference time). | |
| """ | |
| total = extra_latency_ms | |
| missing = [] | |
| for m in ce_sub: | |
| key = f"CE:{m}" | |
| if key in latency_map: | |
| total += latency_map[key] | |
| else: | |
| missing.append(key) | |
| for m in kl_sub: | |
| key = f"KL:{m}" | |
| if key in latency_map: | |
| total += latency_map[key] | |
| else: | |
| missing.append(key) | |
| return total, missing | |
| def benchmark_inference(X_subset, meta_learner, n_repeats=20): | |
| """Median wall-clock time for a single predict_proba call over X_subset.""" | |
| times = [] | |
| for _ in range(n_repeats): | |
| t0 = time.perf_counter() | |
| _ = meta_learner.predict_proba(X_subset) | |
| times.append(time.perf_counter() - t0) | |
| return np.median(times), np.std(times) | |
| # ============================================================================= | |
| # COMPLEMENTARITY ANALYSIS & GREEDY FORWARD SELECTION | |
| # ============================================================================= | |
| def compute_complementarity_matrix(X_all, y, tagged, n_classes): | |
| """ | |
| For every pair of models, compute the joint error ratio: | |
| P(A wrong AND B wrong) / P(A wrong OR B wrong) | |
| Low ratio = high complementarity (errors on different samples). | |
| High ratio = redundant pair. | |
| tagged: list of (clean_name, "CE"|"KL") | |
| """ | |
| preds = {} | |
| for i, (name, src) in enumerate(tagged): | |
| key = f"{src}:{name}" | |
| start = i * n_classes | |
| probs = X_all[:, start:start + n_classes] | |
| preds[key] = np.argmax(probs, axis=1) | |
| keys = list(preds.keys()) | |
| wrong = {k: (preds[k] != y) for k in keys} | |
| rows = [] | |
| for i, a in enumerate(keys): | |
| for j, b in enumerate(keys): | |
| if i >= j: | |
| continue | |
| both = (wrong[a] & wrong[b]).sum() | |
| either = (wrong[a] | wrong[b]).sum() | |
| ratio = both / max(either, 1) | |
| rows.append({"model_a": a, "model_b": b, | |
| "joint_error_ratio": round(ratio, 4), | |
| "a_err_rate": round(wrong[a].mean(), 4), | |
| "b_err_rate": round(wrong[b].mean(), 4)}) | |
| return pd.DataFrame(rows).sort_values("joint_error_ratio") | |
| def greedy_forward_selection(X_full, y, tagged, n_classes, class_order, | |
| df_ce, df_kl, use_derived, meta_type, | |
| k_folds, seed, max_models, min_gain, | |
| extra_features=None): | |
| """ | |
| Greedy forward selection of model subsets. | |
| Start with best single model; at each step add the candidate that gives | |
| the largest CV F1 gain. Stop when max_models reached or gain < min_gain. | |
| Returns singles + every greedy prefix as (label, ce_subset, kl_subset). | |
| extra_features: optional (n_samples, d) numpy array of fixed features | |
| (e.g. frozen encoder embeddings, OOF embeddings) that are concatenated | |
| to every subset's feature matrix. These are fixed regardless of which | |
| base models are selected — they represent encoders that always run at | |
| serving time. | |
| """ | |
| kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed) | |
| def _cv_f1(ce_sub, kl_sub): | |
| b = OOFFeatureBuilder( | |
| ce_df=df_ce, kl_df=df_kl, | |
| ce_models=ce_sub, kl_models=kl_sub, | |
| use_derived=use_derived, | |
| ensemble_source="both", | |
| class_order=class_order, | |
| ) | |
| try: | |
| Xs, _ = b.build() | |
| except ValueError: | |
| return 0.0 | |
| n_prob = Xs.shape[1] # prob cols before any embeddings are appended | |
| if extra_features is not None and extra_features.shape[1] > 0: | |
| Xs = np.hstack([Xs, extra_features]) | |
| f1s = [] | |
| for tr, val in kfold.split(Xs, y): | |
| m = MetaLearner(meta_type, n_classes, seed, | |
| n_prob_cols=n_prob).fit(Xs[tr], y[tr]) | |
| p = np.argmax(m.predict_proba(Xs[val]), axis=1) | |
| f1s.append(precision_recall_fscore_support( | |
| y[val], p, average="macro", zero_division=0)[2]) | |
| return float(np.mean(f1s)) | |
| remaining = list(tagged) | |
| selected = [] | |
| best_f1 = 0.0 | |
| path = [] | |
| print(" Greedy forward selection" | |
| f" (max_models={max_models}, min_gain={min_gain}):") | |
| for step in range(max_models): | |
| best_candidate = None | |
| best_candidate_f1 = best_f1 | |
| for candidate in remaining: | |
| trial = selected + [candidate] | |
| ce_sub = [n for n, s in trial if s == "CE"] | |
| kl_sub = [n for n, s in trial if s == "KL"] | |
| f1 = _cv_f1(ce_sub, kl_sub) | |
| if f1 > best_candidate_f1: | |
| best_candidate_f1 = f1 | |
| best_candidate = candidate | |
| if best_candidate is None or (best_candidate_f1 - best_f1) < min_gain: | |
| print(f" Step {step+1}: no gain >={min_gain:.4f} — stopping.") | |
| break | |
| selected.append(best_candidate) | |
| remaining.remove(best_candidate) | |
| gain = best_candidate_f1 - best_f1 | |
| best_f1 = best_candidate_f1 | |
| name, src = best_candidate | |
| ce_sub = [n for n, s in selected if s == "CE"] | |
| kl_sub = [n for n, s in selected if s == "KL"] | |
| label = "+".join(f"{s}:{n.split('__')[-1][:15]}" for n, s in selected) | |
| short = name.split("__")[-1][:25] | |
| print(f" Step {step+1}: +{src}:{short:<25} " | |
| f"F1={best_f1:.4f} gain=+{gain:.4f}") | |
| path.append((label, list(ce_sub), list(kl_sub), best_f1)) | |
| # Singles always included for reference | |
| singles = [] | |
| for name, src in tagged: | |
| ce_sub = [name] if src == "CE" else [] | |
| kl_sub = [name] if src == "KL" else [] | |
| lbl = f"{src}:{name.split('__')[-1][:25]}" | |
| singles.append((lbl, ce_sub, kl_sub)) | |
| path_configs = [(lbl, ce, kl) for lbl, ce, kl, _ in path] | |
| seen = set() | |
| result = [] | |
| for cfg in singles + path_configs: | |
| key = (frozenset(f"CE:{m}" for m in cfg[1]) | | |
| frozenset(f"KL:{m}" for m in cfg[2])) | |
| if key not in seen: | |
| seen.add(key) | |
| result.append(cfg) | |
| return result | |
| def build_subset_configs(ce_models, kl_models, max_combo_size=3): | |
| """ | |
| Generate candidate model subsets for the accuracy-vs-speed sweep. | |
| Each model is tagged with its source ("CE" or "KL"). All subsets of | |
| size 1..max_combo_size are generated, plus the full ALL_CE, ALL_KL, | |
| and ALL_CE+KL aggregates. | |
| Returns list of (label, ce_subset, kl_subset) tuples. | |
| """ | |
| # Tag every model with its source so we can split them back out | |
| tagged = [(m, "CE") for m in ce_models] + [(m, "KL") for m in kl_models] | |
| n_total = len(tagged) | |
| seen = set() | |
| configs = [] | |
| def add(label, ce_sub, kl_sub): | |
| key = (frozenset(f"CE:{m}" for m in ce_sub) | | |
| frozenset(f"KL:{m}" for m in kl_sub)) | |
| if key not in seen: | |
| seen.add(key) | |
| configs.append((label, list(ce_sub), list(kl_sub))) | |
| # All subsets of size 1..max_combo_size | |
| cap = min(max_combo_size, n_total) | |
| for size in range(1, cap + 1): | |
| for combo in combinations(tagged, size): | |
| ce_sub = [m for m, src in combo if src == "CE"] | |
| kl_sub = [m for m, src in combo if src == "KL"] | |
| # Build a readable label: prefix only when mixing sources | |
| parts = [f"CE:{m.split('__')[-1][:18]}" if src == "CE" | |
| else f"KL:{m.split('__')[-1][:18]}" | |
| for m, src in combo] | |
| label = "+".join(parts) if len(parts) <= 3 else f"COMBO_{len(parts)}m" | |
| add(label, ce_sub, kl_sub) | |
| # Full aggregates (always include regardless of max_combo_size) | |
| add("ALL_CE", ce_models, []) | |
| if kl_models: | |
| add("ALL_KL", [], kl_models) | |
| add("ALL_CE+KL", ce_models, kl_models) | |
| return configs | |
| # ============================================================================= | |
| # PLOTTING | |
| # ============================================================================= | |
| def plot_fold_consistency(fold_importances, cv, feature_names, stable_mask, output_dir): | |
| """Heatmap of per-fold importances for top features, and CV bar plot.""" | |
| # weighted_avg importances cover only the leading prob columns (see | |
| # MetaLearner.get_feature_importances) — align names/counts to the array. | |
| feature_names = list(feature_names)[:fold_importances.shape[1]] | |
| top_n = min(30, fold_importances.shape[1]) | |
| mean_imp = fold_importances.mean(axis=0) | |
| top_idx = np.argsort(-mean_imp)[:top_n] | |
| fig, axes = plt.subplots(1, 2, figsize=(18, 8)) | |
| fig.suptitle("Fold Consistency Analysis", fontsize=14, fontweight="bold") | |
| # Heatmap | |
| data = fold_importances[:, top_idx] | |
| cols = [feature_names[i] for i in top_idx] | |
| # Truncate long names for display | |
| cols_short = [c[-40:] if len(c) > 40 else c for c in cols] | |
| sns.heatmap(data.T, ax=axes[0], xticklabels=[f"Fold {i+1}" for i in range(len(fold_importances))], | |
| yticklabels=cols_short, cmap="YlOrRd", fmt=".3f", annot=True, | |
| annot_kws={"size": 6}, linewidths=0.3) | |
| axes[0].set_title("Normalised Importance per Fold (Top Features)") | |
| axes[0].tick_params(axis='y', labelsize=6) | |
| # CV bar chart | |
| cv_top = cv[top_idx] | |
| colours = ["#2ecc71" if stable_mask[i] else "#e74c3c" for i in top_idx] | |
| axes[1].barh(range(top_n), cv_top[::-1], color=colours[::-1]) | |
| axes[1].set_yticks(range(top_n)) | |
| axes[1].set_yticklabels(cols_short[::-1], fontsize=6) | |
| axes[1].axvline(x=cv.mean(), color="grey", linestyle="--", label=f"mean CV={cv.mean():.2f}") | |
| axes[1].set_xlabel("Coefficient of Variation (lower = more stable)") | |
| axes[1].set_title("Feature Stability (green=stable, red=unstable)") | |
| axes[1].legend(fontsize=8) | |
| plt.tight_layout() | |
| out = Path(output_dir) / "fold_consistency.png" | |
| plt.savefig(out, dpi=150, bbox_inches="tight") | |
| plt.close() | |
| print(f" Saved → {out}") | |
| def plot_accuracy_vs_speed(results_df, output_dir): | |
| """Scatter plot: inference time (x) vs macro F1 (y), annotated by config label.""" | |
| fig, ax = plt.subplots(figsize=(12, 7)) | |
| # Colour by whether the config uses KL features | |
| colours = ["#3498db" if "KL" in r["label"] else "#e67e22" | |
| for _, r in results_df.iterrows()] | |
| time_col = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms" | |
| scatter = ax.scatter(results_df[time_col], results_df["meta_f1"], | |
| c=colours, s=120, alpha=0.85, edgecolors="white", linewidth=0.5) | |
| for _, row in results_df.iterrows(): | |
| ax.annotate(row["label"], (row[time_col], row["meta_f1"]), | |
| textcoords="offset points", xytext=(6, 3), fontsize=7) | |
| ax.set_xlabel(f"Estimated Total Inference Time ({time_col}, ms) for {len(results_df)} samples") | |
| ax.set_ylabel("Meta-Learner Macro F1 (OOF CV)") | |
| ax.set_title("Accuracy vs Inference Speed\n(blue=KL involved, orange=CE only)") | |
| ax.grid(True, alpha=0.3) | |
| # Pareto frontier | |
| pareto = _pareto_frontier(results_df[[time_col, "meta_f1"]].values) | |
| if len(pareto) >= 2: | |
| pareto = pareto[np.argsort(pareto[:, 0])] | |
| ax.plot(pareto[:, 0], pareto[:, 1], "k--", linewidth=1.2, alpha=0.6, | |
| label="Pareto frontier") | |
| ax.legend(fontsize=9) | |
| plt.tight_layout() | |
| out = Path(output_dir) / "accuracy_vs_speed.png" | |
| plt.savefig(out, dpi=150, bbox_inches="tight") | |
| plt.close() | |
| print(f" Saved → {out}") | |
| def _pareto_frontier(points): | |
| """Return points on the Pareto frontier (minimise time, maximise F1).""" | |
| dominated = np.zeros(len(points), dtype=bool) | |
| for i in range(len(points)): | |
| for j in range(len(points)): | |
| if i == j: continue | |
| # j dominates i if j is faster AND has >= F1 | |
| if points[j, 0] <= points[i, 0] and points[j, 1] >= points[i, 1]: | |
| if points[j, 0] < points[i, 0] or points[j, 1] > points[i, 1]: | |
| dominated[i] = True | |
| break | |
| return points[~dominated] | |
| def plot_model_agreement(X, feature_names, ce_models, kl_models, n_classes, output_dir): | |
| """ | |
| Pairwise Spearman correlation between each model's argmax predictions. | |
| Helps visualise which models are redundant. | |
| """ | |
| argmax_preds = {} | |
| for m in ce_models: | |
| idx = [i for i, f in enumerate(feature_names) if f.startswith(f"CE_{m}_") and "_entropy" not in f and "_argmax" not in f and "_kl" not in f and "_diff" not in f] | |
| if idx: | |
| probs = X[:, idx] | |
| argmax_preds[f"CE_{m[:20]}"] = np.argmax(probs, axis=1) | |
| for m in kl_models: | |
| idx = [i for i, f in enumerate(feature_names) if f.startswith(f"KL_{m}_") and "_entropy" not in f and "_argmax" not in f and "_kl" not in f and "_diff" not in f] | |
| if idx: | |
| probs = X[:, idx] | |
| argmax_preds[f"KL_{m[:20]}"] = np.argmax(probs, axis=1) | |
| if len(argmax_preds) < 2: | |
| return | |
| keys = list(argmax_preds.keys()) | |
| n = len(keys) | |
| corr_mat = np.eye(n) | |
| for i in range(n): | |
| for j in range(i+1, n): | |
| rho, _ = spearmanr(argmax_preds[keys[i]], argmax_preds[keys[j]]) | |
| corr_mat[i, j] = corr_mat[j, i] = rho | |
| fig, ax = plt.subplots(figsize=(max(6, n), max(5, n-1))) | |
| sns.heatmap(corr_mat, xticklabels=keys, yticklabels=keys, | |
| annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1, ax=ax, | |
| linewidths=0.3) | |
| ax.set_title("Pairwise Spearman Correlation of Model Argmax Predictions\n" | |
| "(high correlation = redundant pair)") | |
| plt.tight_layout() | |
| out = Path(output_dir) / "model_agreement.png" | |
| plt.savefig(out, dpi=150, bbox_inches="tight") | |
| plt.close() | |
| print(f" Saved → {out}") | |
| # ============================================================================= | |
| # MAIN | |
| # ============================================================================= | |
| # ============================================================================= | |
| # DEPLOYMENT EXPORT | |
| # ============================================================================= | |
| def _export_deployment(export_row, results_df, out_dir, ce_configs, kl_configs, | |
| df_ce, df_kl, y, idx_to_label, class_order, | |
| extra_features_arr, n_classes, args, time_col_s): | |
| """ | |
| Re-train a meta-learner for the chosen config on the full training set and | |
| write all deployment artifacts to out_dir/deployment/: | |
| meta_learner.pkl - joblib-serialised MetaLearner | |
| deployment_config.json - everything the inference script needs | |
| """ | |
| import joblib | |
| export_dir = out_dir / "deployment" | |
| export_dir.mkdir(exist_ok=True) | |
| label = export_row["label"] | |
| exp_mt = export_row["meta_type"] | |
| exp_ce = [m for m in str(export_row.get("ce_models", "")).split(",") if m] | |
| exp_kl = [m for m in str(export_row.get("kl_models", "")).split(",") if m] | |
| print("\n Exporting deployment artifacts for:", label) | |
| # Re-train on full training data (not just a fold) | |
| exp_builder = OOFFeatureBuilder( | |
| ce_df=df_ce, kl_df=df_kl, | |
| ce_models=exp_ce, kl_models=exp_kl, | |
| use_derived=args.use_derived_features, | |
| ensemble_source="both", | |
| class_order=class_order, | |
| ) | |
| X_exp, fn_exp = exp_builder.build() | |
| n_prob_exp = X_exp.shape[1] | |
| if extra_features_arr is not None and extra_features_arr.shape[1] > 0: | |
| X_exp = np.hstack([X_exp, extra_features_arr]) | |
| exp_meta = MetaLearner(exp_mt, n_classes, args.seed, | |
| n_prob_cols=n_prob_exp).fit(X_exp, y) | |
| meta_path = export_dir / "meta_learner.pkl" | |
| joblib.dump({ | |
| "model": exp_meta, | |
| "feature_names": fn_exp, | |
| "n_prob_cols": n_prob_exp, | |
| "n_classes": n_classes, | |
| "class_order": class_order, | |
| "idx_to_label": idx_to_label, | |
| }, meta_path) | |
| print(" meta_learner.pkl ->", meta_path) | |
| # Per-model serving info: everything the inference script needs to load | |
| # and run each model (architecture, tokenizer, fold paths, other_cols, dtype) | |
| def _model_info(cname, source): | |
| cfgs = ce_configs if source == "CE" else kl_configs | |
| for c in cfgs: | |
| if clean_name(c["model_name"]) == cname: | |
| return c | |
| return {} | |
| def _verify_other_cols(model_name, artifacts_dir, declared_cols, split_unk): | |
| """ | |
| Cross-check declared other_cols against the actual trained checkpoint. | |
| The checkpoint's head input width tells us whether tabular features were | |
| used at training: a multimodal head has input dim = hidden + len(other_cols), | |
| a plain head has input dim = hidden. If the declared other_cols disagree | |
| with the checkpoint, the config is stale — trust the checkpoint and warn. | |
| Returns the corrected other_cols (possibly cleared to []). | |
| """ | |
| if not artifacts_dir: | |
| return declared_cols | |
| try: | |
| from safetensors.torch import load_file | |
| safe_name = model_name.replace("/", "__") | |
| if split_unk: | |
| safe_name += "__stage1" | |
| # Find fold_1 model dir | |
| base = Path(artifacts_dir) / ("pretrained_checkpoints__" + safe_name) | |
| if not base.exists(): | |
| base = Path(artifacts_dir) / safe_name | |
| st = base / "fold_1" / "model" / "model.safetensors" | |
| if not st.exists(): | |
| return declared_cols # can't verify, keep declared | |
| sd = load_file(str(st)) | |
| # Find the head's input width | |
| head_in = None | |
| hidden = None | |
| for k, v in sd.items(): | |
| kk = k[len("base_model."):] if k.startswith("base_model.") else k | |
| first = kk.split(".", 1)[0] | |
| if first in ("classifier", "feature_extractor") and kk.endswith(".weight"): | |
| # First head linear: input width is v.shape[1] | |
| if kk in ("classifier.0.weight", "feature_extractor.0.weight", | |
| "classifier.weight"): | |
| if head_in is None or kk.endswith("0.weight"): | |
| head_in = v.shape[1] | |
| # encoder hidden size: word embeddings width | |
| if "embeddings.word_embeddings.weight" in kk: | |
| hidden = v.shape[1] | |
| if head_in is None or hidden is None: | |
| return declared_cols | |
| checkpoint_tab = head_in - hidden # tabular feature count in checkpoint | |
| declared_tab = len(declared_cols or []) | |
| if checkpoint_tab != declared_tab: | |
| print(" [WARN] {}: declared other_cols={} ({} features) but " | |
| "checkpoint head expects {} tabular features. " | |
| "Trusting checkpoint.".format( | |
| clean_name(model_name), declared_cols, | |
| declared_tab, checkpoint_tab)) | |
| if checkpoint_tab <= 0: | |
| return [] | |
| # checkpoint expects tab but declared has wrong count — keep declared | |
| # names if count matches, else warn and keep as-is | |
| return declared_cols | |
| except Exception as e: | |
| print(" [NOTE] Could not verify other_cols for {}: {}".format( | |
| clean_name(model_name), e)) | |
| return declared_cols | |
| def _portable(path): | |
| """Deployment configs must survive machine moves (VM1 <-> VM2 <-> HF). | |
| Store artifact dirs relative to the project root (cwd at export time); | |
| the inference script's resolver finds them via its cwd rule on any | |
| machine. Absolute paths are kept only if outside the project tree.""" | |
| if not path: | |
| return None | |
| rp = Path(path).resolve() | |
| try: | |
| return str(rp.relative_to(Path.cwd())) | |
| except ValueError: | |
| return str(rp) | |
| model_entries = [] | |
| for cname in exp_ce: | |
| c = _model_info(cname, "CE") | |
| ce_art = _portable(args.ce_artifacts_dir) | |
| verified_cols = _verify_other_cols( | |
| c.get("model_name", cname), ce_art, | |
| c.get("other_cols", []), c.get("split_unknown_stage", False)) | |
| model_entries.append({ | |
| "source": "CE", | |
| "clean_name": cname, | |
| "model_name": c.get("model_name", cname), | |
| "tokenizer_name": c.get("tokenizer_name"), | |
| "task_type": c.get("task_type", "classification"), | |
| "split_unknown_stage": c.get("split_unknown_stage", False), | |
| "other_cols": verified_cols, | |
| "drop_token_type_ids": c.get("drop_token_type_ids", False), | |
| "use_fp16": c.get("use_fp16", False), | |
| "use_bf16": c.get("use_bf16", False), | |
| "artifacts_dir": ce_art, | |
| }) | |
| for cname in exp_kl: | |
| c = _model_info(cname, "KL") | |
| kl_art = _portable(args.kl_artifacts_dir) | |
| verified_cols = _verify_other_cols( | |
| c.get("model_name", cname), kl_art, | |
| c.get("other_cols", []), c.get("split_unknown_stage", False)) | |
| model_entries.append({ | |
| "source": "KL", | |
| "clean_name": cname, | |
| "model_name": c.get("model_name", cname), | |
| "tokenizer_name": c.get("tokenizer_name"), | |
| "task_type": c.get("task_type", "classification"), | |
| "split_unknown_stage": c.get("split_unknown_stage", False), | |
| "other_cols": verified_cols, | |
| "drop_token_type_ids": c.get("drop_token_type_ids", False), | |
| "use_fp16": c.get("use_fp16", False), | |
| "use_bf16": c.get("use_bf16", False), | |
| "artifacts_dir": kl_art, | |
| }) | |
| # Store meta_learner_path as just the filename — it always lives next to | |
| # the config. This makes the deployment dir portable (move it anywhere and | |
| # inference still works without editing the JSON). | |
| # artifacts_dir paths are absolute — they live outside the deployment dir. | |
| # frozen_emb_cache: absolute path (may be in a different experiment subdir). | |
| deployment_cfg = { | |
| "label": label, | |
| "meta_type": exp_mt, | |
| "meta_f1_cv": float(export_row["meta_f1"]), | |
| "est_total_ms": float(export_row.get(time_col_s, 0)), | |
| "benchmark_n_samples": args.benchmark_n_samples, | |
| "n_classes": n_classes, | |
| "class_order": class_order, | |
| "idx_to_label": {str(k): v for k, v in idx_to_label.items()}, | |
| "k_folds": args.k_folds, | |
| "use_derived_features": args.use_derived_features, | |
| "max_length": args.max_length, | |
| "n_prob_cols": n_prob_exp, | |
| "meta_learner_path": meta_path.name, # filename only — resolved relative to config dir | |
| "models": model_entries, | |
| "frozen_encoder": args.frozen_encoder, | |
| "frozen_encoder_tokenizer": args.frozen_encoder_tokenizer, | |
| "frozen_emb_n_components": args.frozen_emb_n_components if args.frozen_encoder else None, | |
| "frozen_emb_cache": str(Path(args.frozen_emb_cache).resolve()) if args.frozen_encoder and args.frozen_emb_cache else None, | |
| } | |
| cfg_path = export_dir / "deployment_config.json" | |
| with open(cfg_path, "w") as f: | |
| json.dump(deployment_cfg, f, indent=2) | |
| print(" deployment_config ->", cfg_path) | |
| print("\n To run inference:") | |
| print(" python meta_learner_inference.py \\") | |
| print(" --config", cfg_path, "\\") | |
| print(" --data_path <new_data.parquet> \\") | |
| print(" --text_col text \\") | |
| print(" --output_path predictions.parquet") | |
| def main(): | |
| args = parse_args() | |
| out_dir = Path(args.output_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| # ── Fast export-only path ───────────────────────────────────────────────── | |
| if args.export_only: | |
| if not args.results_csv: | |
| raise ValueError("--results_csv is required when --export_only is set.") | |
| if not Path(args.results_csv).exists(): | |
| raise FileNotFoundError("results_csv not found: " + args.results_csv) | |
| print("\n" + "="*60) | |
| print("META-LEARNER TRAINER [export-only mode]") | |
| print("="*60) | |
| print("Loading existing results from:", args.results_csv) | |
| results_df = pd.read_csv(args.results_csv) | |
| best = results_df.sort_values("meta_f1", ascending=False).iloc[0] | |
| # Minimal data reload for re-training the meta-learner | |
| df_data = pd.read_parquet(args.data_path) | |
| df_ce = pd.read_parquet(args.ce_oof_path) if args.ce_oof_path else None | |
| df_kl = pd.read_parquet(args.kl_oof_path) if args.kl_oof_path else None | |
| mapping = load_mapping(args.mapping_dict_path) | |
| known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1]) | |
| unknown = [(k, v) for k, v in mapping.items() if v < 0] | |
| n_known = len(known) | |
| label_to_idx = {} | |
| for new_idx, (label_str, _) in enumerate(known): | |
| label_to_idx[label_str] = new_idx | |
| for i, (label_str, _) in enumerate(unknown): | |
| label_to_idx[label_str] = n_known + i | |
| idx_to_label = {v: k for k, v in label_to_idx.items()} | |
| n_classes = len(label_to_idx) | |
| class_order = get_class_order_from_mapping(mapping) | |
| raw_labels = df_data[args.label_col].astype(str).values | |
| valid_mask = np.array([l in label_to_idx for l in raw_labels]) | |
| y = np.array([label_to_idx[l] for l in raw_labels[valid_mask]]) | |
| if df_ce is not None: | |
| df_ce = df_ce.iloc[valid_mask].reset_index(drop=True) | |
| if df_kl is not None: | |
| df_kl = df_kl.iloc[valid_mask].reset_index(drop=True) | |
| # Load configs | |
| ce_configs = get_active_models(args.ce_config_path) if args.ce_config_path else [] | |
| kl_configs = get_active_models(args.kl_config_path) if args.kl_config_path else [] | |
| # Load frozen embeddings if applicable | |
| extra_features_arr = None | |
| if args.frozen_encoder and args.frozen_emb_cache: | |
| cache = Path(args.frozen_emb_cache) | |
| if cache.exists(): | |
| print("Loading cached frozen embeddings from:", args.frozen_emb_cache) | |
| emb_df = pd.read_parquet(args.frozen_emb_cache) | |
| extra_features_arr = emb_df.values[valid_mask] | |
| else: | |
| print("[WARN] frozen_emb_cache not found — embeddings will not be included.") | |
| # Pick export row | |
| if args.export_label: | |
| match = results_df[results_df["label"] == args.export_label] | |
| export_row = match.iloc[0] if not match.empty else best | |
| if match.empty: | |
| print("[WARN] --export_label not found; using best F1 config.") | |
| else: | |
| export_row = best | |
| time_col_s = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms" | |
| _export_deployment( | |
| export_row=export_row, results_df=results_df, out_dir=out_dir, | |
| ce_configs=ce_configs, kl_configs=kl_configs, | |
| df_ce=df_ce, df_kl=df_kl, y=y, idx_to_label=idx_to_label, | |
| class_order=class_order, extra_features_arr=extra_features_arr, | |
| n_classes=n_classes, args=args, time_col_s=time_col_s, | |
| ) | |
| return | |
| # ── Full training path ──────────────────────────────────────────────────── | |
| print("\n" + "="*60) | |
| print("META-LEARNER TRAINER") | |
| print("="*60) | |
| # --- Load data --- | |
| print("\n[1] Loading data...") | |
| df_data = pd.read_parquet(args.data_path) | |
| df_ce = pd.read_parquet(args.ce_oof_path) if args.ce_oof_path else None | |
| df_kl = pd.read_parquet(args.kl_oof_path) if args.kl_oof_path else None | |
| mapping = load_mapping(args.mapping_dict_path) | |
| # Encode labels exactly as the generator does: | |
| # known classes (value >= 0): 0-based index = value - ordinal_min_label | |
| # unknown classes (value < 0): placed last, index = n_known_classes + i | |
| # valid_mask keeps any row whose label string is a key in mapping. | |
| # Rows whose label string is not in mapping at all (e.g. NaN coerced to "nan") are dropped. | |
| known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1]) | |
| unknown = [(k, v) for k, v in mapping.items() if v < 0] | |
| n_known = len(known) | |
| label_to_idx = {} | |
| for new_idx, (label_str, _) in enumerate(known): | |
| label_to_idx[label_str] = new_idx # "ON_MAIN_STREET" -> 0, etc. | |
| for i, (label_str, _) in enumerate(unknown): | |
| label_to_idx[label_str] = n_known + i # "UNKNOWN" -> 5 | |
| idx_to_label = {v: k for k, v in label_to_idx.items()} | |
| n_classes = len(label_to_idx) | |
| raw_labels = df_data[args.label_col].astype(str).values | |
| valid_mask = np.array([l in label_to_idx for l in raw_labels]) | |
| if not valid_mask.all(): | |
| dropped = (~valid_mask).sum() | |
| examples = list(set(raw_labels[~valid_mask]))[:5] | |
| print(f" Dropping {dropped} rows with label strings not in mapping. Examples: {examples}") | |
| y = np.array([label_to_idx[l] for l in raw_labels[valid_mask]]) | |
| print(f" Label mapping (from mapping.json):") | |
| for idx in range(n_classes): | |
| lbl = idx_to_label[idx] | |
| count = int((y == idx).sum()) | |
| print(f" class {idx}: '{lbl}' [{count:,} samples]") | |
| # Align all dataframes to valid rows | |
| if df_ce is not None: | |
| df_ce = df_ce.iloc[valid_mask].reset_index(drop=True) | |
| if df_kl is not None: | |
| df_kl = df_kl.iloc[valid_mask].reset_index(drop=True) | |
| print(f" Samples: {len(y):,} | Classes: {n_classes}") | |
| # --- Load configs --- | |
| ce_configs = get_active_models(args.ce_config_path) if args.ce_config_path else [] | |
| ce_model_names = [clean_name(c["model_name"]) for c in ce_configs] | |
| kl_model_names = [] | |
| if args.kl_config_path: | |
| kl_configs = get_active_models(args.kl_config_path) | |
| kl_model_names = [clean_name(c["model_name"]) for c in kl_configs] | |
| # Apply model_subset filter | |
| model_subset = None | |
| if args.model_subset: | |
| model_subset = [s.strip() for s in args.model_subset.split(",")] | |
| print(f" Filtering to subset: {model_subset}") | |
| print(f" CE models: {ce_model_names}") | |
| print(f" KL models: {kl_model_names}") | |
| # --- Build features --- | |
| print("\n[2] Building OOF feature matrix...") | |
| class_order = get_class_order_from_mapping(mapping) | |
| builder = OOFFeatureBuilder( | |
| ce_df=df_ce, | |
| kl_df=df_kl, | |
| ce_models=ce_model_names, | |
| kl_models=kl_model_names, | |
| model_subset=model_subset, | |
| use_derived=args.use_derived_features, | |
| ensemble_source=args.ensemble_source, | |
| class_order=class_order, | |
| ) | |
| X, feature_names = builder.build() | |
| print(f" Feature matrix shape: {X.shape}") | |
| print(f" Feature groups:") | |
| for prefix in ["CE_", "KL_", "CE_KL_", "CE_pair_"]: | |
| count = sum(1 for f in feature_names if f.startswith(prefix)) | |
| if count: | |
| print(f" {prefix:<12} {count} features") | |
| # Sanity check: class_order (from mapping) drives both y encoding and column ordering. | |
| # Both should always be ✓ now. Printed so any future regression is immediately visible. | |
| print(f" Label ↔ OOF column alignment (class_order from mapping):") | |
| all_ok = True | |
| for i, cls in enumerate(class_order): | |
| expected_y_label = idx_to_label.get(i, "???") | |
| ok = (cls == expected_y_label) | |
| tag = "✓" if ok else f"✗ y has '{expected_y_label}'" | |
| if not ok: all_ok = False | |
| count = int((y == i).sum()) | |
| print(f" class {i}: '{cls}' {tag} [{count:,} samples]") | |
| if all_ok: | |
| print(" All aligned.") | |
| print() | |
| # --- Embedding features (Options 2 and 3) --- | |
| extra_features_arr = None # populated below if any embedding flags are set | |
| X_oof_emb = np.zeros((len(y), 0), dtype=np.float32) | |
| X_frozen = np.zeros((len(y), 0), dtype=np.float32) | |
| emb_needs_text = args.use_oof_embeddings or args.frozen_encoder | |
| if emb_needs_text and not args.text_col: | |
| raise ValueError("--text_col is required when using --use_oof_embeddings " | |
| "or --frozen_encoder.") | |
| if emb_needs_text: | |
| all_texts = df_data.iloc[valid_mask][args.text_col].fillna("").tolist() | |
| emb_device = _normalise_device(args.benchmark_device) | |
| if args.use_oof_embeddings: | |
| need_dirs = (not args.ce_artifacts_dir and not args.kl_artifacts_dir) | |
| if need_dirs: | |
| raise ValueError("--use_oof_embeddings requires at least one of " | |
| "--ce_artifacts_dir / --kl_artifacts_dir.") | |
| print("\n[2b] Extracting OOF embeddings (Option 2)...") | |
| X_oof_emb, oof_emb_names = extract_oof_embeddings( | |
| ce_configs = ce_configs, | |
| kl_configs = kl_configs, | |
| ce_artifacts_dir = args.ce_artifacts_dir, | |
| kl_artifacts_dir = args.kl_artifacts_dir, | |
| texts = all_texts, | |
| y = y, | |
| max_length = args.max_length, | |
| device = emb_device, | |
| n_components = args.oof_emb_n_components, | |
| batch_size = args.oof_emb_batch_size, | |
| k_folds = args.k_folds, | |
| seed = args.seed, | |
| ce_cache = args.oof_emb_ce_cache, | |
| kl_cache = args.oof_emb_kl_cache, | |
| ) | |
| if X_oof_emb.shape[1] > 0: | |
| X = np.hstack([X, X_oof_emb]) | |
| feature_names = feature_names + oof_emb_names | |
| print(" Added {} OOF embedding features. " | |
| "Total features: {}".format(len(oof_emb_names), X.shape[1])) | |
| if args.frozen_encoder: | |
| print("\n[2c] Extracting frozen encoder embeddings (Option 3)...") | |
| X_frozen, frozen_names = extract_frozen_embeddings( | |
| model_name = args.frozen_encoder, | |
| tokenizer_name = args.frozen_encoder_tokenizer, | |
| texts = all_texts, | |
| max_length = args.max_length, | |
| device = emb_device, | |
| n_components = args.frozen_emb_n_components, | |
| batch_size = args.frozen_emb_batch_size, | |
| cache_path = args.frozen_emb_cache, | |
| ) | |
| if X_frozen.shape[1] > 0: | |
| X = np.hstack([X, X_frozen]) | |
| feature_names = feature_names + frozen_names | |
| print(" Added {} frozen embedding features. " | |
| "Total features: {}".format(len(frozen_names), X.shape[1])) | |
| # Collect fixed embedding features to pass into greedy selection and sweep. | |
| # These are "always-on" at serving time — every request runs these encoders | |
| # regardless of which base models are selected. | |
| extra_feature_parts = [] | |
| if args.use_oof_embeddings and "X_oof_emb" in dir(): | |
| if X_oof_emb.shape[1] > 0: | |
| extra_feature_parts.append(X_oof_emb) | |
| if args.frozen_encoder and "X_frozen" in dir(): | |
| if X_frozen.shape[1] > 0: | |
| extra_feature_parts.append(X_frozen) | |
| extra_features_arr = (np.hstack(extra_feature_parts) | |
| if extra_feature_parts else None) | |
| if extra_features_arr is not None: | |
| print(" Fixed embedding features for sweep/greedy: {} dims".format( | |
| extra_features_arr.shape[1])) | |
| # --- Model agreement plot --- | |
| print("\n[3] Plotting model agreement...") | |
| plot_model_agreement(X, feature_names, | |
| builder._ce_active, builder._kl_active, | |
| n_classes, out_dir) | |
| # --- Fold consistency analysis --- | |
| print("\n[4] Running fold consistency analysis...") | |
| # n_prob_cols: columns that are valid probability distributions. | |
| # Embedding columns appended after are real-valued and not prob distributions. | |
| n_prob_cols = X.shape[1] - (extra_features_arr.shape[1] | |
| if extra_features_arr is not None else 0) | |
| fold_importances, cv, stable_mask, fold_f1s = fold_consistency_analysis( | |
| X=X, | |
| y=y, | |
| feature_names=feature_names, | |
| meta_type=args.meta_type, | |
| n_classes=n_classes, | |
| k_folds=args.k_folds, | |
| seed=args.seed, | |
| threshold=args.fold_consistency_threshold, | |
| n_prob_cols=n_prob_cols, | |
| ) | |
| if fold_importances is not None: | |
| plot_fold_consistency(fold_importances, cv, feature_names, stable_mask, out_dir) | |
| # Save stability report | |
| stability_df = pd.DataFrame({ | |
| "feature": list(feature_names)[:fold_importances.shape[1]], | |
| "mean_importance": fold_importances.mean(axis=0), | |
| "std_importance": fold_importances.std(axis=0), | |
| "cv": cv, | |
| "stable": stable_mask, | |
| }).sort_values("mean_importance", ascending=False) | |
| stability_df.to_csv(out_dir / "feature_stability.csv", index=False) | |
| print(f" Saved → {out_dir / 'feature_stability.csv'}") | |
| # --- Train final meta-learner on stable features --- | |
| print("\n[5] Training final meta-learner...") | |
| X_final = X | |
| if stable_mask is not None and len(stable_mask) != X.shape[1]: | |
| # weighted_avg importances (hence this mask) cover only the leading | |
| # prob columns; column selection would also break the per-model | |
| # n_classes block structure its blending relies on. Keep all features. | |
| print(" Stability mask covers %d of %d columns (weighted_avg " | |
| "prob-cols only) — skipping stable-feature selection." | |
| % (len(stable_mask), X.shape[1])) | |
| stable_mask = None | |
| if stable_mask is not None and stable_mask.any() and stable_mask.sum() > n_classes: | |
| print(f" Using {stable_mask.sum()} stable features out of {X.shape[1]}") | |
| X_final = X[:, stable_mask] | |
| feature_names_final = [f for f, s in zip(feature_names, stable_mask) if s] | |
| else: | |
| print(" Using all features (stable mask not applicable or too few stable).") | |
| feature_names_final = feature_names | |
| final_meta = MetaLearner(args.meta_type, n_classes, args.seed, | |
| n_prob_cols=n_prob_cols).fit(X_final, y) | |
| final_preds = np.argmax(final_meta.predict_proba(X_final), axis=1) | |
| final_f1 = precision_recall_fscore_support(y, final_preds, average="macro", | |
| zero_division=0)[2] | |
| print(f" Final meta-learner (train) Macro F1: {final_f1:.4f}") | |
| print(f" Cross-val Macro F1: {np.mean(fold_f1s):.4f} ± {np.std(fold_f1s):.4f}") | |
| # --- Accuracy vs Speed sweep --- | |
| print("\n[6] Accuracy vs Inference Speed analysis...") | |
| bm_idx = np.random.default_rng(args.seed).choice( | |
| len(X), size=min(args.benchmark_n_samples, len(X)), replace=False) | |
| # Build per-model latency map by loading and timing each checkpoint | |
| latency_map = {} | |
| has_latency = args.ce_artifacts_dir or args.kl_artifacts_dir | |
| if has_latency: | |
| if not args.text_col: | |
| raise ValueError("--text_col is required when --ce_artifacts_dir or " | |
| "--kl_artifacts_dir is provided.") | |
| texts_for_bench = df_data.iloc[valid_mask][args.text_col].fillna("").tolist() | |
| texts_for_bench = [texts_for_bench[i] for i in bm_idx] | |
| print(f" Benchmarking base model latency on {len(texts_for_bench)} samples " | |
| f"(device={args.benchmark_device}, repeats={args.benchmark_repeats})...") | |
| latency_map = build_latency_map( | |
| ce_configs = ce_configs if args.ce_artifacts_dir else [], | |
| kl_configs = kl_configs if args.kl_artifacts_dir else [], | |
| ce_artifacts_dir = args.ce_artifacts_dir, | |
| kl_artifacts_dir = args.kl_artifacts_dir, | |
| ce_metadata_path = args.ce_metadata_path, | |
| kl_metadata_path = args.kl_metadata_path, | |
| texts = texts_for_bench, | |
| max_length = args.max_length, | |
| device = args.benchmark_device, | |
| n_repeats = args.benchmark_repeats, | |
| ) | |
| print(f" Latency map ({len(latency_map)} models):") | |
| for k, v in sorted(latency_map.items()): | |
| print(f" {k:<60s} {v:.1f} ms / {len(texts_for_bench)} samples") | |
| else: | |
| print(" NOTE: --ce_artifacts_dir / --kl_artifacts_dir not provided.") | |
| print(" Only meta overhead is timed. Transformer latency dominates in production.") | |
| print(" Re-run with those flags for realistic per-model timing.") | |
| # Measure inference-time latency of embedding encoders. | |
| # These run on EVERY request at serving time regardless of which base models | |
| # are selected — they are a fixed overhead added to every config's total_ms. | |
| # The parquet cache is only for training; at serving time you re-run them. | |
| extra_inference_ms = 0.0 | |
| extra_notes = [] | |
| if args.frozen_encoder and has_latency: | |
| print(" Timing frozen encoder inference latency...") | |
| frozen_ms = benchmark_transformer_model( | |
| original_model_name = args.frozen_encoder, | |
| tokenizer_name = args.frozen_encoder_tokenizer, | |
| texts = texts_for_bench, | |
| max_length = args.max_length, | |
| device = args.benchmark_device, | |
| n_repeats = args.benchmark_repeats, | |
| use_fp16 = False, | |
| use_bf16 = False, | |
| ) | |
| extra_inference_ms += frozen_ms | |
| extra_notes.append("frozen_encoder={:.1f}ms".format(frozen_ms)) | |
| print(" Frozen encoder: {:.1f} ms / {} samples".format( | |
| frozen_ms, len(texts_for_bench))) | |
| if args.use_oof_embeddings and has_latency: | |
| # OOF encoders at serving time = run each fine-tuned base model a second | |
| # time to extract embeddings. We approximate as the sum of CE encoder | |
| # latencies (stage1 for split_unknown models) since those are already | |
| # in latency_map and represent the same forward pass cost. | |
| oof_enc_ms = 0.0 | |
| for cfg in ce_configs: | |
| if not cfg.get("use", True): continue | |
| if cfg.get("task_type") == "tfidf_lgbm": continue | |
| cname = clean_name(cfg["model_name"]) | |
| key = "CE:" + cname | |
| if key in latency_map: | |
| oof_enc_ms += latency_map[key] | |
| extra_inference_ms += oof_enc_ms | |
| extra_notes.append("oof_emb_encoders={:.1f}ms".format(oof_enc_ms)) | |
| print(" OOF embedding encoder overhead: {:.1f} ms / {} samples".format( | |
| oof_enc_ms, len(texts_for_bench))) | |
| if extra_notes: | |
| print(" Fixed inference overhead per request: {:.1f} ms ({})".format( | |
| extra_inference_ms, ", ".join(extra_notes))) | |
| else: | |
| extra_inference_ms = 0.0 | |
| # --- Complementarity table (always computed, cheap) --- | |
| all_tagged = ([(m, "CE") for m in builder._ce_active] + | |
| [(m, "KL") for m in builder._kl_active]) | |
| # Build base-probs-only feature matrix for complementarity (no derived features) | |
| b_base = OOFFeatureBuilder( | |
| ce_df=df_ce, kl_df=df_kl, | |
| ce_models=builder._ce_active, kl_models=builder._kl_active, | |
| use_derived=False, ensemble_source="both", class_order=class_order) | |
| X_base, _ = b_base.build() | |
| comp_df = compute_complementarity_matrix(X_base, y, all_tagged, n_classes) | |
| comp_path = out_dir / "complementarity.csv" | |
| comp_df.to_csv(comp_path, index=False) | |
| print(" Model pair complementarity (top-10 most complementary pairs):") | |
| print(comp_df.head(10).to_string(index=False)) | |
| print(" Full table saved ->", comp_path) | |
| # --- Subset generation and meta-type comparison --- | |
| # When --compare_meta_types: run greedy selection for every meta-learner type | |
| # so the comparison reflects (learner, subset) pairs — not just which learner | |
| # wins on the full feature set. Different learners may reach their plateau with | |
| # different numbers of models. Results are merged into a single sweep table. | |
| # | |
| # Without --compare_meta_types: run greedy/exhaustive for --meta_type only. | |
| META_TYPES = ["ridge", "logistic", "weighted_avg", "lgbm", "mlp"] | |
| types_to_run = META_TYPES if args.compare_meta_types else [args.meta_type] | |
| results = [] | |
| all_subset_configs = {} # meta_type -> list of (label, ce_sub, kl_sub) | |
| for mt in types_to_run: | |
| if args.compare_meta_types: | |
| print() | |
| print(" ---- meta_type:", mt, "----") | |
| if args.selection_strategy == "greedy": | |
| mt_configs = greedy_forward_selection( | |
| X_full=X_base, y=y, | |
| tagged=all_tagged, | |
| n_classes=n_classes, | |
| class_order=class_order, | |
| df_ce=df_ce, df_kl=df_kl, | |
| use_derived=args.use_derived_features, | |
| meta_type=mt, | |
| k_folds=args.k_folds, | |
| seed=args.seed, | |
| max_models=args.greedy_max_models, | |
| min_gain=args.greedy_min_gain, | |
| extra_features=extra_features_arr, | |
| ) | |
| print(" Greedy selected", len(mt_configs), "configs for", mt) | |
| else: | |
| mt_configs = build_subset_configs( | |
| builder._ce_active, builder._kl_active, | |
| max_combo_size=args.max_combo_size, | |
| ) | |
| if mt == types_to_run[0]: | |
| print(" Exhaustive:", len(mt_configs), | |
| "subsets (max_combo_size={})".format(args.max_combo_size)) | |
| all_subset_configs[mt] = mt_configs | |
| # Flatten: tag each config with its meta_type for the results table | |
| sweep_tasks = [] # (meta_type, label, ce_sub, kl_sub) | |
| seen_labels = set() | |
| for mt, cfgs in all_subset_configs.items(): | |
| for label, ce_sub, kl_sub in cfgs: | |
| tagged_label = label if not args.compare_meta_types else mt + "/" + label | |
| sweep_tasks.append((mt, tagged_label, ce_sub, kl_sub)) | |
| seen_labels.add(tagged_label) | |
| # When only one meta_type, deduplicate configs evaluated multiple times | |
| if not args.compare_meta_types: | |
| seen = set() | |
| deduped = [] | |
| for task in sweep_tasks: | |
| key = (task[0], frozenset(task[2]), frozenset(task[3])) | |
| if key not in seen: | |
| seen.add(key) | |
| deduped.append(task) | |
| sweep_tasks = deduped | |
| kfold_cv = StratifiedKFold(n_splits=args.k_folds, shuffle=True, random_state=args.seed) | |
| # Build a lookup of pre-computed single-model OOF F1 scores. | |
| # For single-model sweep configs the meta-learner is a no-op, so we skip | |
| # expensive CV and use the pre-computed OOF F1 directly. | |
| # | |
| # Source: metadata.json (written by the generator), NOT the config file. | |
| # The config no longer stores oof_f1 — that was removed to keep configs | |
| # immutable. metadata.json is the canonical record of training results. | |
| def _load_f1_from_metadata(meta_path): | |
| """Return {clean_name: oof_f1} from a metadata.json, or {} if unavailable.""" | |
| if not meta_path or not Path(meta_path).exists(): | |
| return {} | |
| with open(meta_path) as f: | |
| meta = json.load(f) | |
| names = meta.get("model_names", []) | |
| scores = meta.get("f1_scores", []) | |
| return {clean_name(n): float(s) for n, s in zip(names, scores)} | |
| ce_f1_map = _load_f1_from_metadata(args.ce_metadata_path) | |
| kl_f1_map = _load_f1_from_metadata(args.kl_metadata_path) | |
| single_model_f1: dict = {} # "CE:<cname>" | "KL:<cname>" -> oof_f1 | |
| for cfg in ce_configs: | |
| cname = clean_name(cfg["model_name"]) | |
| if cname in ce_f1_map: | |
| single_model_f1["CE:" + cname] = ce_f1_map[cname] | |
| for cfg in kl_configs: | |
| cname = clean_name(cfg["model_name"]) | |
| if cname in kl_f1_map: | |
| single_model_f1["KL:" + cname] = kl_f1_map[cname] | |
| if single_model_f1: | |
| print(" Single-model F1 loaded from metadata ({} models):".format( | |
| len(single_model_f1))) | |
| for k, v in sorted(single_model_f1.items()): | |
| print(" {:<55s} {:.4f}".format(k, v)) | |
| else: | |
| print(" [NOTE] No single-model F1 from metadata " | |
| "(--ce_metadata_path / --kl_metadata_path not set or files missing).") | |
| print(" Single-model configs will run full CV instead of using cached F1.") | |
| for mt, label, ce_sub, kl_sub in sweep_tasks: | |
| n_base_models = len(ce_sub) + len(kl_sub) | |
| # --- Fast path: single-model configs --- | |
| # The meta-learner sees only one model's OOF probs -> it cannot improve on | |
| # the model's own OOF F1. Skip CV and read from metadata directly. | |
| # (weighted_avg weight = [1.0], ridge/logistic ≈ identity on well-calibrated | |
| # probs, lgbm/mlp may marginally differ but not worth the compute.) | |
| if n_base_models == 1: | |
| key = ("CE:" + ce_sub[0]) if ce_sub else ("KL:" + kl_sub[0]) | |
| if key in single_model_f1: | |
| mean_f1 = single_model_f1[key] | |
| cv_f1s = [mean_f1] # single value — std will be 0 | |
| # Still time the meta overhead (fast, just one predict call) | |
| sub_builder = OOFFeatureBuilder( | |
| ce_df=df_ce, kl_df=df_kl, | |
| ce_models=ce_sub, kl_models=kl_sub, | |
| use_derived=args.use_derived_features, | |
| ensemble_source="both", class_order=class_order) | |
| try: | |
| X_sub, _ = sub_builder.build() | |
| except ValueError: | |
| continue | |
| n_prob_sub = X_sub.shape[1] | |
| if extra_features_arr is not None and extra_features_arr.shape[1] > 0: | |
| X_sub = np.hstack([X_sub, extra_features_arr]) | |
| m_bench = MetaLearner(mt, n_classes, args.seed, | |
| n_prob_cols=n_prob_sub).fit(X_sub, y) | |
| base_ms, missing = lookup_subset_latency(ce_sub, kl_sub, latency_map, extra_inference_ms) | |
| meta_med_ms, _ = benchmark_inference(X_sub[bm_idx], m_bench, n_repeats=20) | |
| meta_med_ms *= 1000 | |
| total_ms = base_ms + meta_med_ms | |
| total_per_smp = total_ms / max(len(bm_idx), 1) | |
| tag_str = label + " [F1 from metadata]" | |
| print(" ", tag_str) | |
| if has_latency: | |
| print(" F1={:.4f} models={} transformer={:.1f}ms " | |
| "meta={:.2f}ms total={:.1f}ms / {} samples".format( | |
| mean_f1, n_base_models, base_ms, | |
| meta_med_ms, total_ms, len(bm_idx))) | |
| else: | |
| print(" F1={:.4f} models={} meta_overhead={:.2f}ms".format( | |
| mean_f1, n_base_models, meta_med_ms)) | |
| results.append({ | |
| "label": label, "meta_type": mt, | |
| "ce_models": ",".join(ce_sub), "kl_models": ",".join(kl_sub), | |
| "n_models": n_base_models, "meta_f1": round(mean_f1, 4), | |
| "f1_std": 0.0, | |
| "base_model_ms": round(base_ms - extra_inference_ms, 2), | |
| "extra_enc_ms": round(extra_inference_ms, 2), | |
| "transformer_ms": round(base_ms, 2), | |
| "meta_overhead_ms": round(meta_med_ms, 3), | |
| "est_total_ms": round(total_ms, 2), | |
| "ms_per_sample": round(total_per_smp, 5), | |
| }) | |
| continue # skip the full CV block below | |
| sub_builder = OOFFeatureBuilder( | |
| ce_df=df_ce, kl_df=df_kl, | |
| ce_models=ce_sub, kl_models=kl_sub, | |
| use_derived=args.use_derived_features, | |
| ensemble_source="both", | |
| class_order=class_order, | |
| ) | |
| try: | |
| X_sub, fn_sub = sub_builder.build() | |
| except ValueError: | |
| continue | |
| # Append fixed embedding features (frozen encoder, OOF embeddings). | |
| # These are identical for every subset — they don't depend on which | |
| # base models are selected, only on the text input. | |
| n_prob_sub = X_sub.shape[1] # record before appending embeddings | |
| if extra_features_arr is not None and extra_features_arr.shape[1] > 0: | |
| X_sub = np.hstack([X_sub, extra_features_arr]) | |
| # CV F1 — use the meta_type for this task, not the global --meta_type | |
| cv_f1s = [] | |
| for tr_idx, val_idx in kfold_cv.split(X_sub, y): | |
| m = MetaLearner(mt, n_classes, args.seed, | |
| n_prob_cols=n_prob_sub).fit(X_sub[tr_idx], y[tr_idx]) | |
| preds = np.argmax(m.predict_proba(X_sub[val_idx]), axis=1) | |
| f1 = precision_recall_fscore_support(y[val_idx], preds, average="macro", | |
| zero_division=0)[2] | |
| cv_f1s.append(f1) | |
| mean_f1 = np.mean(cv_f1s) | |
| # Meta overhead — use the task's meta_type | |
| m_bench = MetaLearner(mt, n_classes, args.seed, | |
| n_prob_cols=n_prob_sub).fit(X_sub, y) | |
| X_bm = X_sub[bm_idx] | |
| meta_med_ms, _ = benchmark_inference(X_bm, m_bench, n_repeats=20) | |
| meta_med_ms *= 1000 | |
| # Per-model transformer latency (sum over all models in subset) | |
| n_base_models = len(ce_sub) + len(kl_sub) | |
| base_ms, missing = lookup_subset_latency(ce_sub, kl_sub, latency_map, extra_inference_ms) | |
| total_ms = base_ms + meta_med_ms | |
| total_per_smp = total_ms / max(len(bm_idx), 1) | |
| if missing and has_latency: | |
| print(f" {label} [WARN missing latency for: {missing}]") | |
| else: | |
| print(f" {label}") | |
| if has_latency: | |
| print(f" F1={mean_f1:.4f} models={n_base_models} " | |
| f"transformer={base_ms:.1f}ms meta={meta_med_ms:.2f}ms " | |
| f"total={total_ms:.1f}ms / {len(bm_idx)} samples") | |
| else: | |
| print(f" F1={mean_f1:.4f} models={n_base_models} " | |
| f"meta_overhead={meta_med_ms:.2f}ms (⚠ transformer latency not measured)") | |
| results.append({ | |
| "label": label, | |
| "meta_type": mt, | |
| "ce_models": ",".join(ce_sub), | |
| "kl_models": ",".join(kl_sub), | |
| "n_models": n_base_models, | |
| "meta_f1": round(mean_f1, 4), | |
| "f1_std": round(np.std(cv_f1s), 4), | |
| "base_model_ms": round(base_ms - extra_inference_ms, 2), | |
| "extra_enc_ms": round(extra_inference_ms, 2), | |
| "transformer_ms": round(base_ms, 2), | |
| "meta_overhead_ms": round(meta_med_ms, 3), | |
| "est_total_ms": round(total_ms, 2), | |
| "ms_per_sample": round(total_per_smp, 5), | |
| }) | |
| results_df = pd.DataFrame(results).sort_values("meta_f1", ascending=False) | |
| results_df.to_csv(out_dir / "accuracy_vs_speed.csv", index=False) | |
| print(f"\n Saved → {out_dir / 'accuracy_vs_speed.csv'}") | |
| print("\n Top configs by F1:") | |
| display_cols = ["meta_type", "label", "meta_f1", "f1_std", | |
| "base_model_ms", "extra_enc_ms", "meta_overhead_ms", | |
| "est_total_ms", "n_models"] | |
| display_cols = [c for c in display_cols if c in results_df.columns] | |
| print(results_df[display_cols].to_string(index=False)) | |
| plot_accuracy_vs_speed(results_df, out_dir) | |
| # --- Summary --- | |
| print("\n" + "="*60) | |
| print("SUMMARY") | |
| print("="*60) | |
| best = results_df.iloc[0] | |
| time_col_s = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms" | |
| pareto_pts = _pareto_frontier(results_df[[time_col_s, "meta_f1"]].values) | |
| fastest_pareto_ms = min(p[0] for p in pareto_pts) | |
| fastest_pareto = results_df[results_df[time_col_s] == fastest_pareto_ms].iloc[0] | |
| print(f" Best F1 config : {best['label']} " | |
| f"(F1={best['meta_f1']:.4f}, total={best[time_col_s]:.1f}ms / {args.benchmark_n_samples} samples)") | |
| print(f" Fastest Pareto cfg : {fastest_pareto['label']} " | |
| f"(F1={fastest_pareto['meta_f1']:.4f}, total={fastest_pareto[time_col_s]:.1f}ms / {args.benchmark_n_samples} samples)") | |
| print(f"\n Outputs in: {out_dir}/") | |
| print("="*60) | |
| # --- Deployment export --- | |
| # Select config row to export (explicit label or best F1) | |
| if args.export_label: | |
| match = results_df[results_df["label"] == args.export_label] | |
| export_row = match.iloc[0] if not match.empty else best | |
| if match.empty: | |
| print("[WARN] --export_label not found; exporting best F1 config.") | |
| else: | |
| export_row = best | |
| _export_deployment( | |
| export_row = export_row, | |
| results_df = results_df, | |
| out_dir = out_dir, | |
| ce_configs = ce_configs, | |
| kl_configs = kl_configs, | |
| df_ce = df_ce, | |
| df_kl = df_kl, | |
| y = y, | |
| idx_to_label = idx_to_label, | |
| class_order = class_order, | |
| extra_features_arr = extra_features_arr, | |
| n_classes = n_classes, | |
| args = args, | |
| time_col_s = time_col_s, | |
| ) | |
| if __name__ == "__main__": | |
| main() |