#!/usr/bin/env python3 """ Meta-Learner Inference Script Loads a deployment config exported by meta_learner_trainer.py and runs inference on new data. Usage: python meta_learner_inference.py \ --config meta_outputs/deployment/deployment_config.json \ --data_path new_data.parquet \ --text_col text \ --output_path predictions.parquet The output parquet contains: - All original columns from new_data.parquet - predicted_label : string label (e.g. "NEAR") - predicted_class : integer class index - prob_{class} : softmax probability for each class - meta_confidence : max probability (argmax confidence) How base model inference works ------------------------------- Each selected model has K fold checkpoints. All K are loaded and their probability outputs are averaged before feeding to the meta-learner. This matches training: the meta-learner was trained on OOF probs which are averaged fold outputs. Using a single fold would introduce bias. For split_unknown_stage models, stage1 and stage2 are run independently and their outputs composed to the final class probabilities. For tfidf_lgbm, the fold_1 pickle is used (TF-IDF models are deterministic so fold averaging doesn't apply in the same way). """ # ============================================================================= # LABEL MAPPING CONVENTION (read this before creating a new task!) # # The --mapping_dict_path json MUST contain EVERY label value present in the # data, in this form (example from condition_tier): # # { "N": -1, "D": 1, "C": 2, "B": 3, "A": 4 } # # * UNKNOWN class -> value -1 (sentinel: "not part of the ordinal scale"). # It must ALSO be named via --unknown_label_value. Omitting it from the # mapping makes label lookup produce NaN and crashes at astype(int). # * Known classes -> 1-indexed integers whose ORDER defines the ordinal # scale (1 = one end, N = the other; e.g. worst -> best). # # OUTPUT COLUMN ORDER produced everywhere downstream (oof_probs.npy, # *_logprob_* columns, soft labels, deployment prob_* columns): # # [ known classes sorted by mapping value ASCENDING, then UNKNOWN last ] # # e.g. condition_tier: [D, C, B, A, N] # dist_to_main_street: [ON_MAIN_STREET, ADJACENT, NEAR, MODERATE, FAR, UNKNOWN] # # Any consumer that hard-codes a class list must match this order exactly. # (Forensic note: the May-2026 condition_tier "phobert collapse", F1 0.087, # was an eval comparing against this order REVERSED; true F1 was 0.9008.) # ============================================================================= import os # Reduce CUDA allocator fragmentation. Must be set before torch initialises # CUDA (torch is imported lazily below, so top-of-module is early enough). # A value already set in the shell takes precedence. os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import argparse import gc import json import pickle import time import warnings from pathlib import Path import numpy as np import pandas as pd warnings.filterwarnings("ignore") # MetaLearner lives in meta_learner_core.py — shared with meta_learner_trainer.py. # Importing it here ensures pickle/joblib can deserialise saved MetaLearner instances # regardless of which script originally created them. 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 # ============================================================================= # ARGUMENT PARSING # ============================================================================= def parse_args(): p = argparse.ArgumentParser() p.add_argument("--config", type=str, required=True, help="Path to deployment_config.json") p.add_argument("--data_path", type=str, required=True, help="Parquet with new data to score") p.add_argument("--text_col", type=str, required=True, help="Column in data_path containing raw text") p.add_argument("--output_path", type=str, default="predictions.parquet", help="Output parquet path") p.add_argument("--device", type=str, default="cpu", help="Device for model inference ('cpu' or 'cuda')") p.add_argument("--batch_size", type=int, default=64, help="Tokenisation batch size for transformer inference") p.add_argument("--num_workers", type=int, default=4, help="Number of CPU workers for parallel tokenisation. " "Set to 0 to disable (single-threaded). " "Rule of thumb: number of physical CPU cores - 1.") p.add_argument("--prefetch", type=int, default=2, help="Number of batches to prefetch per worker. " "Higher values use more CPU RAM but keep GPU busier.") p.add_argument("--chunk_size", type=int, default=50000, help="Number of rows to process per write chunk. Controls peak " "memory usage for the feature assembly + meta predict step. " "Model inference (transformers / tfidf) always runs over the " "full dataset in a single sequential pass per model to avoid " "reloading weights repeatedly. Default: 50000.") p.add_argument("--keep_cols", type=str, default=None, help="Comma-separated list of extra columns from --data_path to " "carry through to the output (in addition to text_col and " "other_cols required by the models). If not set, only the " "prediction columns are written (no original columns). " "Use --keep_cols '*' to keep everything (memory-intensive " "for large datasets).") p.add_argument("--cache_dir", type=str, default=None, help="Override the resume-cache directory. Default: " "/inference_cache. Use distinct dirs for " "kfold vs final checkpoint runs — cache filenames are " "identical across modes and would collide.") p.add_argument("--clear_cache", action="store_true", help="Delete the inference cache dir after a successful run. " "Default: keep it (reusable for re-runs on the same data, " "e.g. after swapping the meta-learner).") p.add_argument("--no_dedup", action="store_true", help="Disable text deduplication. Use when per-row tabular features " "(other_cols) vary significantly across duplicate texts and you " "want each row inferred independently. Increases compute by " "n_total/n_unique factor.") return p.parse_args() # ============================================================================= # NORMALISE DEVICE # ============================================================================= def _normalise_device(d): return "cuda" if d.lower() == "gpu" else d.lower() # ============================================================================= # MODEL LOADING HELPERS # ============================================================================= def _load_encoder(model_name, dtype, device): from transformers import AutoModel enc = AutoModel.from_pretrained(model_name, trust_remote_code=True, dtype=dtype) enc.eval() enc.to(device) return enc def _load_fold_model(fold_dir: Path, original_model_name: str, dtype, device): """ Load the fine-tuned fold encoder, stripping the base_model. prefix used by MultimodalClassificationModel / OrdinalRegressionModel wrappers. Falls back to direct load for plain AutoModel checkpoints. """ import torch from transformers import AutoModel st = fold_dir / "model.safetensors" use_safe = st.exists() if not use_safe: st = fold_dir / "pytorch_model.bin" if not st.exists(): raise FileNotFoundError("No weights in " + str(fold_dir)) if use_safe: from safetensors.torch import load_file raw_sd = load_file(str(st)) else: raw_sd = torch.load(str(st), map_location="cpu", weights_only=True) encoder_sd = {k[len("base_model."):]: v for k, v in raw_sd.items() if k.startswith("base_model.")} if not encoder_sd: encoder_sd = raw_sd enc = AutoModel.from_pretrained( original_model_name, trust_remote_code=True, dtype=dtype) enc.load_state_dict(encoder_sd, strict=False) enc.eval() enc.to(device) return enc def _get_fold_dir(artifacts_dir, model_name, fold_n, stage=None): artifact_name = model_name if stage is None else model_name + "__" + stage safe_name = artifact_name.replace("/", "__") # 'final' is the single-checkpoint layout from --training_mode final; # numbered folds come from the kfold layout. sub = "final" if str(fold_n) == "final" else "fold_" + str(fold_n) return Path(artifacts_dir) / safe_name / sub / "model" # ============================================================================= # FEATURE EXTRACTION # ============================================================================= def _encode_texts(encoder, tokenizer, texts, max_length, device, batch_size, drop_token_type_ids): 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) all_embs.append(out.last_hidden_state[:, 0, :].float().cpu().numpy()) return np.vstack(all_embs) # ============================================================================= # PARALLEL TOKENISATION DATASET # ============================================================================= class _TextDataset: """ Simple torch Dataset wrapping a list of strings + optional tabular features. Each worker tokenises its own shard, keeping GPU fed without waiting. """ def __init__(self, texts, tokenizer, max_length, drop_token_type_ids, tabular_features=None): self.texts = texts self.tok = tokenizer self.max_length = max_length self.drop_tti = drop_token_type_ids self.tab = tabular_features # (N, d) numpy or None def __len__(self): return len(self.texts) def __getitem__(self, idx): enc = self.tok( self.texts[idx], padding = False, # pad in collate to max length of batch truncation = True, max_length = self.max_length, return_tensors = None, # return plain lists — faster to collate ) if self.drop_tti: enc.pop("token_type_ids", None) item = {"__idx": idx, **{k: v for k, v in enc.items()}} if self.tab is not None: item["__tab"] = self.tab[idx] return item def _collate(batch): """Pad a list of tokenised items to the longest sequence in the batch.""" import torch indices = [x.pop("__idx") for x in batch] tab_rows = [x.pop("__tab", None) for x in batch] keys = list(batch[0].keys()) out = {} for k in keys: seqs = [x[k] for x in batch] # Determine pad value: 0 for attention_mask, 1 for input_ids (safe default) pad_val = 0 max_len = max(len(s) for s in seqs) padded = [s + [pad_val] * (max_len - len(s)) for s in seqs] out[k] = torch.tensor(padded, dtype=torch.long) out["__idx"] = torch.tensor(indices, dtype=torch.long) if tab_rows[0] is not None: import numpy as np out["__tab"] = torch.tensor(np.stack(tab_rows), dtype=torch.float32) return out def _build_head(head_keys, device, model_type=None): """ Reconstruct the task head from saved weight keys, matching the EXACT architectures defined in ensemble_distillation_generator.py: 1. Multimodal classification (MultimodalClassificationModel): classifier.0 = Linear(hidden+tab, hidden) classifier.3 = Linear(hidden, num_labels) keys: classifier.0.{weight,bias}, classifier.3.{weight,bias} 2. Ordinal regression (OrdinalRegressionModel): feature_extractor.0 = Linear(hidden+tab, hidden) ordinal_head = Linear(hidden, num_classes-1) keys: feature_extractor.0.{weight,bias}, ordinal_head.{weight,bias} 3. Plain sequence classification (AutoModelForSequenceClassification, used when other_cols is empty, e.g. rembert): classifier = Linear(hidden, num_labels) keys: classifier.{weight,bias} (NO numeric index) 3b. HF two-layer classification head (other_cols empty, roberta/electra families): classifier.dense + classifier.out_proj on the RAW CLS token (never the AutoModel pooler, which is untrained in these checkpoints). Activation differs by family: roberta=tanh, electra=gelu. keys: classifier.dense.{weight,bias}, classifier.out_proj.{weight,bias} Returns (head_module, head_type, expects_tabular, n_out) where head_type = "classification" | "ordinal" | "plain" expects_tabular= whether the head's input dim includes tabular features n_out = output dimension (num_labels or num_thresholds) """ import torch.nn as nn def _lin(w, b): m = nn.Linear(w.shape[1], w.shape[0]) m.weight = nn.Parameter(w.float()) if b is not None: m.bias = nn.Parameter(b.float()) return m keys = set(head_keys.keys()) # Case 2: ordinal if "ordinal_head.weight" in keys and "feature_extractor.0.weight" in keys: fe_w = head_keys["feature_extractor.0.weight"] fe_b = head_keys.get("feature_extractor.0.bias") oh_w = head_keys["ordinal_head.weight"] oh_b = head_keys.get("ordinal_head.bias") head = nn.Sequential( _lin(fe_w, fe_b), nn.ReLU(), nn.Dropout(0.1), _lin(oh_w, oh_b), ).to(device) in_dim = fe_w.shape[1] # hidden + tab n_out = oh_w.shape[0] # num_thresholds = num_classes - 1 return head, "ordinal", in_dim, n_out # Case 1: multimodal classification (classifier.0 + classifier.3) if "classifier.0.weight" in keys and "classifier.3.weight" in keys: c0_w = head_keys["classifier.0.weight"]; c0_b = head_keys.get("classifier.0.bias") c3_w = head_keys["classifier.3.weight"]; c3_b = head_keys.get("classifier.3.bias") head = nn.Sequential( _lin(c0_w, c0_b), nn.ReLU(), nn.Dropout(0.1), _lin(c3_w, c3_b), ).to(device) in_dim = c0_w.shape[1] n_out = c3_w.shape[0] return head, "classification", in_dim, n_out # Case 3b: HF two-layer head (RobertaClassificationHead / Electra- # ClassificationHead). Consumes the RAW CLS token; head_type "hf_head" # (NOT "plain") so the forward pass never routes through pooler_output — # roberta AutoModels have an UNTRAINED pooler in these checkpoints. if "classifier.dense.weight" in keys and "classifier.out_proj.weight" in keys: d_w = head_keys["classifier.dense.weight"]; d_b = head_keys.get("classifier.dense.bias") o_w = head_keys["classifier.out_proj.weight"]; o_b = head_keys.get("classifier.out_proj.bias") mt = (model_type or "").lower() act = nn.GELU() if mt == "electra" else nn.Tanh() if mt not in ("electra", "roberta", "xlm-roberta", "camembert"): print(" [WARN] hf_head activation defaulting to tanh for " "model_type=%r — verify against the HF head class." % model_type) head = nn.Sequential(_lin(d_w, d_b), act, _lin(o_w, o_b)).to(device) return head, "hf_head", d_w.shape[1], o_w.shape[0] # Case 3: plain classification (single classifier.{weight,bias}) if "classifier.weight" in keys: w = head_keys["classifier.weight"]; b = head_keys.get("classifier.bias") head = _lin(w, b).to(device) in_dim = w.shape[1] n_out = w.shape[0] return head, "plain", in_dim, n_out # Fallback: any output_layer if "output_layer.weight" in keys: w = head_keys["output_layer.weight"]; b = head_keys.get("output_layer.bias") head = _lin(w, b).to(device) return head, "plain", w.shape[1], w.shape[0] return None, None, None, None def _load_sd(fold_dir): """Load state dict from safetensors or pytorch_model.bin.""" import torch st = fold_dir / "model.safetensors" if not st.exists(): st = fold_dir / "pytorch_model.bin" if st.suffix == ".safetensors": from safetensors.torch import load_file return load_file(str(st)) return torch.load(str(st), map_location="cpu", weights_only=True) # Head parameter name stems — anything starting with these is a task head, # NOT part of the transformer encoder. Matches the architectures defined in # ensemble_distillation_generator.py plus HF's default seq-classification heads. _HEAD_STEMS = ("classifier", "ordinal_head", "feature_extractor", "output_layer", "score", "pre_classifier") def _split_sd(raw_sd): """ Split a checkpoint state dict into (encoder_sd, head_keys). Handles three checkpoint layouts: 1. Multimodal/ordinal wrapper: encoder under 'base_model..*', head at top level (classifier.* / ordinal_head.* / feature_extractor.*). 2. Plain HF AutoModelForSequenceClassification: encoder under '.*' (e.g. 'rembert.', 'roberta.', 'electra.', 'bert.'), head at top level (classifier.weight/bias). 3. Bare encoder: everything is encoder. Head keys are identified by their parameter name stem, independent of any prefix. Encoder keys have their leading prefix stripped so they load into a plain AutoModel. """ head_keys = {} encoder_raw = {} for k, v in raw_sd.items(): # Strip a leading "base_model." if present (multimodal wrapper) kk = k[len("base_model."):] if k.startswith("base_model.") else k # Is this a head parameter? Check the FIRST path component. first = kk.split(".", 1)[0] if first in _HEAD_STEMS: head_keys[kk] = v else: encoder_raw[kk] = v # encoder_raw may still be prefixed by the model type (rembert., roberta., # electra., bert., deberta., etc). Detect and strip a single common prefix # so keys match a plain AutoModel (which expects e.g. 'embeddings.*'). prefixes = {k.split(".", 1)[0] for k in encoder_raw if "." in k} # A real encoder prefix is one shared by (almost) all keys and is a known # backbone name. If there's exactly one dominant prefix, strip it. encoder_sd = {} known_backbones = {"rembert", "roberta", "electra", "bert", "deberta", "deberta_v2", "xlm_roberta", "camembert", "distilbert", "albert", "mpnet", "model", "transformer"} strip_prefix = None if len(prefixes) == 1: only = next(iter(prefixes)) if only in known_backbones: strip_prefix = only else: # Multiple prefixes — pick the one that's a known backbone if unique bk = [p for p in prefixes if p in known_backbones] if len(bk) == 1: strip_prefix = bk[0] if strip_prefix: plen = len(strip_prefix) + 1 for k, v in encoder_raw.items(): if k.startswith(strip_prefix + "."): encoder_sd[k[plen:]] = v else: encoder_sd[k] = v else: encoder_sd = encoder_raw return encoder_sd, head_keys class _PreTokenizedDataset: """ Dataset backed by already-tokenised arrays stored on disk. Workers just index into numpy mmaps — zero CPU tokenisation overhead. """ def __init__(self, cache_dir, n, tabular_features=None): self.input_ids = np.load(str(cache_dir / "input_ids.npy"), mmap_mode="r") self.attention_mask = np.load(str(cache_dir / "attention_mask.npy"), mmap_mode="r") tok_type_path = cache_dir / "token_type_ids.npy" self.token_type_ids = (np.load(str(tok_type_path), mmap_mode="r") if tok_type_path.exists() else None) self.tab = tabular_features self.n = n def __len__(self): return self.n def __getitem__(self, idx): item = { "__idx": idx, "input_ids": self.input_ids[idx].tolist(), "attention_mask": self.attention_mask[idx].tolist(), } if self.token_type_ids is not None: item["token_type_ids"] = self.token_type_ids[idx].tolist() if self.tab is not None: item["__tab"] = self.tab[idx] return item def _tokenize_and_cache(texts, tokenizer, max_length, drop_tti, cache_dir, num_workers): """ Tokenize all texts once, padding to max_length, saving as numpy arrays. Subsequent folds/stages read via mmap — zero re-tokenisation cost. """ import torch from torch.utils.data import DataLoader print(" Tokenising {:,} texts (once for all folds)...".format(len(texts))) cache_dir.mkdir(parents=True, exist_ok=True) # Use _TextDataset + DataLoader for parallel tokenisation class _RawTextDS: def __init__(self, texts, tok, ml, drop): self.texts = texts; self.tok = tok self.ml = ml; self.drop = drop def __len__(self): return len(self.texts) def __getitem__(self, i): enc = self.tok(self.texts[i], padding="max_length", truncation=True, max_length=self.ml, return_tensors=None) if self.drop: enc.pop("token_type_ids", None) return {k: v for k, v in enc.items()} def _collate_raw(batch): import torch out = {} for k in batch[0]: out[k] = torch.tensor([x[k] for x in batch], dtype=torch.long) return out ds = _RawTextDS(texts, tokenizer, max_length, drop_tti) dl = DataLoader(ds, batch_size=512, shuffle=False, num_workers=num_workers, collate_fn=_collate_raw) n = len(texts) id_arr = np.zeros((n, max_length), dtype=np.int32) mask_arr = np.zeros((n, max_length), dtype=np.int8) tti_arr = None has_tti = False for b_idx, batch in enumerate(dl): start = b_idx * 512 end = min(start + 512, n) sl = batch["input_ids"].numpy()[:end-start] id_arr[start:end] = sl mask_arr[start:end] = batch["attention_mask"].numpy()[:end-start] if "token_type_ids" in batch and not has_tti: tti_arr = np.zeros((n, max_length), dtype=np.int8) has_tti = True if has_tti: tti_arr[start:end] = batch["token_type_ids"].numpy()[:end-start] if b_idx % 100 == 0: print(" Tokenising... {:.0f}%".format(end / n * 100), flush=True) np.save(str(cache_dir / "input_ids.npy"), id_arr) np.save(str(cache_dir / "attention_mask.npy"), mask_arr) if has_tti: np.save(str(cache_dir / "token_type_ids.npy"), tti_arr) print(" Tokenisation cached -> {}".format(cache_dir)) def run_transformer_model(model_cfg, texts, tabular_features, max_length, device, batch_size, k_folds, num_workers=4, prefetch=2, token_cache_dir=None): """ Run a transformer model (all K folds), returning averaged probabilities. Optimisations vs naive approach: 1. Tokenise ONCE before the fold loop, cache to disk as numpy arrays. All folds read from mmap — zero re-tokenisation. 2. Load encoder ARCHITECTURE once (AutoConfig + empty init), then per fold just call load_state_dict(). Avoids re-downloading/re-reading the original pretrained weights K times. 3. Running average accumulation — O(N×C) memory regardless of K folds. 4. DataLoader with num_workers for prefetch during GPU forward pass. """ import torch import torch.nn as nn import torch.nn.functional as F from transformers import AutoTokenizer, AutoModel, AutoConfig from torch.utils.data import DataLoader mname = model_cfg["model_name"] cname = model_cfg["clean_name"] task = model_cfg["task_type"] tok_name = model_cfg.get("tokenizer_name") or mname drop_tti = model_cfg.get("drop_token_type_ids", False) split_unk = model_cfg.get("split_unknown_stage", False) other_cols = model_cfg.get("other_cols", []) use_fp16 = model_cfg.get("use_fp16", False) use_bf16 = model_cfg.get("use_bf16", False) art_dir = model_cfg["artifacts_dir"] tab_feats = tabular_features if (other_cols and tabular_features is not None) else None dtype = (torch.bfloat16 if use_bf16 else torch.float16 if use_fp16 else torch.float32) n = len(texts) # ── Step 1: Tokenise once ──────────────────────────────────────────────── tok_cache = (token_cache_dir / "{}.tokens".format( cname.replace("/", "__"))) if tok_cache.exists() and (tok_cache / "input_ids.npy").exists(): print(" Tokenisation cache found for {} — skipping re-tokenisation.".format(cname)) else: tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True) _tokenize_and_cache(texts, tokenizer, max_length, drop_tti, tok_cache, num_workers) del tokenizer gc.collect() pre_tok_ds = _PreTokenizedDataset(tok_cache, n, tab_feats) # ── Step 2: Load encoder architecture ONCE (no pretrained weights) ─────── print(" Loading encoder architecture for {} ...".format(cname)) config = AutoConfig.from_pretrained(mname, trust_remote_code=True) encoder = AutoModel.from_config(config) encoder = encoder.to(dtype) # Don't move to device yet — weights are wrong; load_state_dict first def _run_fold(fold_dir, fold_label, partial_cache_path=None): """ Swap weights into the shared encoder, run inference, return (N,C) array. Intra-fold resumability: - Every `save_every` batches, fold_sum and samples_done are written to a .npz partial cache file. - On entry, if the partial cache exists, the running sum is restored and already-processed samples are skipped via a sliced DataLoader. - On completion the partial cache is deleted (full fold cache takes over). """ # How often to checkpoint within a fold (every ~5% of batches, min 50) n_batches_total = (n + batch_size - 1) // batch_size save_every = max(50, n_batches_total // 20) # ── Resume partial fold if checkpoint exists ────────────────────────── fold_sum = None samples_done = 0 if partial_cache_path and partial_cache_path.exists(): try: data = np.load(str(partial_cache_path)) fold_sum = data["fold_sum"] samples_done = int(data["samples_done"]) print(" {} — resuming from sample {:,} / {:,} ({:.0f}%)".format( fold_label, samples_done, n, samples_done / n * 100)) except Exception as e: print(" {} — partial cache load failed ({}), starting fresh".format( fold_label, e)) fold_sum = None samples_done = 0 # ── Load weights only if we actually need to run inference ──────────── if samples_done < n: raw_sd = _load_sd(fold_dir) encoder_sd, head_keys = _split_sd(raw_sd) del raw_sd gc.collect() load_res = encoder.load_state_dict(encoder_sd, strict=False) n_missing = len(load_res.missing_keys) n_unexpected = len(load_res.unexpected_keys) if n_missing or n_unexpected: print(" {} — load report: {} missing, {} unexpected keys".format( fold_label, n_missing, n_unexpected)) if n_missing > 5: print(" [WARN] Many missing keys — encoder may be " "partially random. First few: {}".format( load_res.missing_keys[:4])) del encoder_sd encoder.eval() encoder.to(device) head, head_type, head_in_dim, n_out = _build_head( head_keys, device, model_type=getattr(getattr(encoder, "config", None), "model_type", None)) if head is None: raise RuntimeError( "Could not reconstruct head for {} — keys: {}".format( fold_label, sorted(head_keys.keys())[:10])) del head_keys gc.collect() # Determine whether the head expects tabular features concatenated. # head_in_dim is the head's input width; encoder hidden size is the # CLS dim. If head_in_dim > hidden, the head was trained with tabular # features appended (multimodal). If equal, it's a plain head (no tab). encoder_hidden = encoder.config.hidden_size head_wants_tab = head_in_dim is not None and head_in_dim > encoder_hidden tab_width = (head_in_dim - encoder_hidden) if head_wants_tab else 0 print(" {} — head={} n_out={} hidden={} tab={}".format( fold_label, head_type, n_out, encoder_hidden, tab_width if head_wants_tab else "none"), flush=True) from torch.utils.data import Subset remaining_ds = (Subset(pre_tok_ds, list(range(samples_done, n))) if samples_done > 0 else pre_tok_ds) loader = DataLoader( remaining_ds, batch_size = batch_size, shuffle = False, num_workers = num_workers, prefetch_factor = prefetch if num_workers > 0 else None, pin_memory = device.startswith("cuda"), collate_fn = _collate, ) n_batches = len(loader) report_every = max(1, n_batches // 20) for b_idx, batch in enumerate(loader): indices = batch.pop("__idx") tab_b = batch.pop("__tab", None) enc_in = {k: v.to(device, non_blocking=True) for k, v in batch.items()} with torch.no_grad(): out = encoder(**enc_in) # Feature extraction must match how the head was TRAINED: # - Multimodal/ordinal wrapper models (classification/ordinal # head types) classify on the raw CLS token: # last_hidden_state[:, 0, :] — the wrapper's design. # - Plain HF AutoModelForSequenceClassification (head_type # "plain", e.g. rembert) classifies on the POOLER output: # tanh(dense(CLS)). Feeding raw CLS into that classifier # produces near-constant garbage predictions. if head_type == "plain" and getattr(out, "pooler_output", None) is not None: cls_emb = out.pooler_output.float() else: cls_emb = out.last_hidden_state[:, 0, :].float() # Concatenate tabular features ONLY if the head expects them. if head_wants_tab: if tab_b is not None: tab_t = tab_b.to(device, non_blocking=True).float() else: # Head expects tab but none provided — pad with zeros tab_t = torch.zeros(cls_emb.shape[0], tab_width, device=device) # Match width exactly (guard against mismatch) if tab_t.shape[1] != tab_width: if tab_t.shape[1] > tab_width: tab_t = tab_t[:, :tab_width] else: pad = torch.zeros(cls_emb.shape[0], tab_width - tab_t.shape[1], device=device) tab_t = torch.cat([tab_t, pad], dim=1) cls_emb = torch.cat([cls_emb, tab_t], dim=1) logits = head(cls_emb) if head_type == "ordinal": # logits: (B, num_thresholds=num_classes-1) # Cumulative P(label > i) via sigmoid, expand to num_classes cum = torch.sigmoid(logits) K = cum.shape[1] # thresholds p = torch.zeros(cum.shape[0], K + 1, device=device) p[:, 0] = 1 - cum[:, 0] for i in range(1, K): p[:, i] = cum[:, i-1] - cum[:, i] p[:, -1] = cum[:, -1] probs_np = p.clamp(min=0).cpu().numpy() else: # classification / plain probs_np = F.softmax(logits, dim=-1).cpu().numpy() if fold_sum is None: fold_sum = np.zeros((n, probs_np.shape[1]), dtype=np.float64) fold_sum[indices.numpy()] += probs_np samples_done += len(indices) if b_idx % report_every == 0 or b_idx == n_batches - 1: print(" {} — {}/{} batches ({:.0f}%)".format( fold_label, b_idx + 1, n_batches, (b_idx + 1) / n_batches * 100), flush=True) # Periodic intra-fold checkpoint if partial_cache_path and (b_idx + 1) % save_every == 0: np.savez(str(partial_cache_path), fold_sum=fold_sum.astype(np.float32), samples_done=np.array(samples_done)) # Move encoder back to CPU to free GPU memory encoder.cpu() if head is not None: del head gc.collect() if device.startswith("cuda"): torch.cuda.empty_cache() # Delete partial cache — full fold result saved by caller if partial_cache_path and partial_cache_path.exists(): partial_cache_path.unlink() return fold_sum.astype(np.float32) def _fold_cache_path(key, fold_n, stage=None): """Per-fold cache: saved immediately after each fold completes.""" tag = "{}_fold{}".format(key, fold_n) if stage: tag += "_{}".format(stage) safe = tag.replace(":", "_").replace("/", "__") return token_cache_dir / "{}.npy".format(safe) def _run_fold_cached(fold_dir, fold_n, stage, label): """ Run a fold or load from cache. - If the completed fold .npy exists: load instantly. - Otherwise: run with intra-fold partial checkpointing. A .partial.npz is written every ~5% of batches so a crash mid-fold can resume from the last checkpoint rather than fold 1. """ model_key = "{}:{}".format(model_cfg["source"], cname) fold_cache = _fold_cache_path(model_key, fold_n, stage) partial_key = "{}_fold{}{}".format( model_key, fold_n, "_{}".format(stage) if stage else "") safe = partial_key.replace(":", "_").replace("/", "__") partial_cache = token_cache_dir / "{}.partial.npz".format(safe) # Completed fold already cached if fold_cache.exists(): arr = np.load(str(fold_cache)) if arr.shape[0] == n: print(" {} — loaded from fold cache".format(label)) return arr print(" {} — fold cache shape mismatch, re-running".format(label)) # Run with intra-fold checkpointing arr = _run_fold(fold_dir, label, partial_cache_path=partial_cache) np.save(str(fold_cache), arr) print(" {} — fold cached -> {}".format(label, fold_cache.name)) return arr # ── Checkpoint layout detection: final (single-pass) vs K folds ────────── # --training_mode final saves ONE checkpoint per model under final/model/. # When present it is preferred: 1/K the serving cost, trained on all # non-holdout data. Fold checkpoints remain the fallback. _probe = _get_fold_dir(art_dir, mname, "final", "stage1" if split_unk else None) if _probe.exists(): fold_ids = ["final"] print(" Using FINAL checkpoint for {} (single pass)".format(cname)) else: fold_ids = list(range(1, k_folds + 1)) # ── Stage 1 (all models) ───────────────────────────────────────────────── s1_sum = None; s1_count = 0 for fold_n in fold_ids: stage = "stage1" if split_unk else None fold_dir = _get_fold_dir(art_dir, mname, fold_n, stage) if not fold_dir.exists(): print(" [WARN] Fold {} not found for {} — skipping".format(fold_n, cname)) continue label = ("fold {}/{} [stage1]".format(fold_n, len(fold_ids)) if split_unk else "fold {}/{}".format(fold_n, len(fold_ids))) fold_arr = _run_fold_cached(fold_dir, fold_n, stage, label) s1_sum = fold_arr.astype(np.float64) if s1_sum is None else s1_sum + fold_arr s1_count += 1 del fold_arr; gc.collect() if s1_count == 0: raise RuntimeError("No fold checkpoints loaded for " + cname) s1_avg = (s1_sum / s1_count).astype(np.float32) del s1_sum; gc.collect() # ── Stage 2 (split_unknown_stage only) ─────────────────────────────────── if split_unk: s2_sum = None; s2_count = 0 for fold_n in fold_ids: fold_dir2 = _get_fold_dir(art_dir, mname, fold_n, "stage2") if not fold_dir2.exists(): continue label2 = "fold {}/{} [stage2]".format(fold_n, len(fold_ids)) fold_arr = _run_fold_cached(fold_dir2, fold_n, "stage2", label2) s2_sum = fold_arr.astype(np.float64) if s2_sum is None else s2_sum + fold_arr s2_count += 1 del fold_arr; gc.collect() if s2_count > 0: s2_avg = (s2_sum / s2_count).astype(np.float32) del s2_sum # Compose EXACTLY as the generator does (split_unknown_stage): # stage1 (plain classification, label 1=unknown, 0=known): # stage1_probs[:, 0] = P(known), stage1_probs[:, 1] = P(unknown) # Calibrate P(unknown) by dividing odds by ordinal_num_classes: # odds = p_unknown / p_known # adj = odds / ordinal_num_classes # p_unknown_cal = adj / (1 + adj); p_known_cal = 1 - p_unknown_cal # stage2 (ordinal) gives P(class | known) over ordinal_num_classes. # Final: [p_known_cal * stage2_i for each known class] + [p_unknown_cal] # Known classes come first, UNKNOWN last — matches class_order. ordinal_num_classes = s2_avg.shape[1] # = n_classes - 1 p_known = s1_avg[:, 0] p_unknown = s1_avg[:, 1] odds_unknown = p_unknown / np.clip(p_known, 1e-7, 1.0) adj_odds = odds_unknown / ordinal_num_classes p_unknown_cal = adj_odds / (1.0 + adj_odds) p_known_cal = 1.0 - p_unknown_cal composed = np.zeros((s1_avg.shape[0], ordinal_num_classes + 1), dtype=np.float32) for i in range(ordinal_num_classes): composed[:, i] = p_known_cal * s2_avg[:, i] composed[:, -1] = p_unknown_cal return composed del encoder; gc.collect() return s1_avg def run_tfidf_lgbm(model_cfg, texts, tabular_features, k_folds): """Run TF-IDF + LightGBM from fold_1 pickle.""" from scipy.sparse import hstack, csr_matrix art_dir = model_cfg["artifacts_dir"] pkl_path = Path(art_dir) / "tfidf_lgbm" / "fold_1" / "model.pkl" if not pkl_path.exists(): raise FileNotFoundError("tfidf_lgbm pickle not found: " + str(pkl_path)) 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 tabular_features is not None and tabular_features.shape[1] > 0: tab = csr_matrix(tabular_features.astype("float32")) X = hstack([X, tab]) return cal.predict_proba(X) # ============================================================================= # DERIVED FEATURES (mirrors OOFFeatureBuilder) # ============================================================================= def entropy(probs, eps=1e-7): p = np.clip(probs, eps, 1.0) return -np.sum(p * np.log(p), axis=1) def sym_kl(p, q, eps=1e-7): 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)) def build_feature_vector(probs_by_key, class_order, n_classes, use_derived, expected_names=None): """ Build the feature vector to EXACTLY match the trainer's OOFFeatureBuilder. probs_by_key: dict "CE:" / "KL:" -> (N, n_classes) array Strategy: compute every candidate feature into a name->column dict, then emit columns in the order given by `expected_names` (the training feature list stored in the meta-learner pickle). This guarantees the inference matrix matches the trained model's expected feature set and order exactly, eliminating count/order mismatches. Trainer naming conventions (must match exactly): base: "CE__" e.g. CE_mlm_listing_NEAR derived: "CE__entropy", "CE__argmax" "CE_KL__sym_kl", "CE_KL__diff_class" "CE_pair_CE__vs_CE__kl" Note: trainer uses underscore between source and name (CE_), while keys here use colon (CE:). """ feat = {} # name -> (N,) or (N,1) column # ── Base probabilities ──────────────────────────────────────────────────── for key, probs in probs_by_key.items(): src, cname = key.split(":", 1) for i, cls in enumerate(class_order): feat["{}_{}_{}".format(src, cname, cls)] = probs[:, i] if use_derived: all_p = dict(probs_by_key) # entropy + argmax per model for key, probs in probs_by_key.items(): src, cname = key.split(":", 1) feat["{}_{}_entropy".format(src, cname)] = entropy(probs) feat["{}_{}_argmax".format(src, cname)] = np.argmax(probs, axis=1).astype(float) # CE-KL pair divergence (same model name in both CE and KL) ce_keys = [k for k in all_p if k.startswith("CE:")] for ce_k in ce_keys: cname = ce_k.split(":", 1)[1] kl_k = "KL:" + cname if kl_k in all_p: feat["CE_KL_{}_sym_kl".format(cname)] = sym_kl(all_p[ce_k], all_p[kl_k]) diff = all_p[ce_k] - all_p[kl_k] for i in range(diff.shape[1]): feat["CE_KL_{}_diff_class{}".format(cname, i)] = diff[:, i] # Pairwise CE disagreement — trainer key format: CE_pair_CE__vs_CE__kl from itertools import combinations ce_prob_list = [(k.split(":", 1)[1], all_p[k]) for k in ce_keys] for (n1, p1), (n2, p2) in combinations(ce_prob_list, 2): feat["CE_pair_CE_{}_vs_CE_{}_kl".format(n1, n2)] = sym_kl(p1, p2) # ── Assemble in the trainer's exact order ───────────────────────────────── if expected_names: N = next(iter(feat.values())).shape[0] cols = [] missing = [] for name in expected_names: if name in feat: cols.append(feat[name].reshape(-1, 1)) else: missing.append(name) cols.append(np.zeros((N, 1))) # placeholder; will warn if missing: print(" [WARN] {} expected features not produced (filled 0): {}".format( len(missing), missing[:8])) # Warn about extra features we built that the model doesn't expect extra = [k for k in feat if k not in set(expected_names)] if extra: print(" [INFO] {} computed features not used by model (ignored): {}".format( len(extra), extra[:8])) return np.hstack(cols), list(expected_names) # No expected names — fall back to deterministic order (base then derived) names = list(feat.keys()) return np.hstack([feat[k].reshape(-1, 1) for k in names]), names # ============================================================================= # FROZEN ENCODER EMBEDDINGS # ============================================================================= def get_frozen_embeddings(texts, cfg, device, batch_size, cache_dir=None): """ Extract embeddings from the frozen encoder and apply PCA. The PCA transform is reconstructed from the cached training embeddings (frozen_emb_cache) by re-fitting on those — since frozen encoder weights never change, this is equivalent to the original fit. """ from sklearn.decomposition import PCA from transformers import AutoTokenizer, AutoModel import torch model_name = cfg["frozen_encoder"] tok_name = cfg.get("frozen_encoder_tokenizer") or model_name n_comp = cfg["frozen_emb_n_components"] cache_path = cfg.get("frozen_emb_cache") tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True) encoder = AutoModel.from_pretrained(model_name, trust_remote_code=True) encoder.eval() encoder.to(device) vocab_size = encoder.config.vocab_size # Cap max_length at the model's position-embedding limit. Models like # PhoBERT have max_position_embeddings=258 (256 usable + 2 special tokens); # tokenising to 512 produces position IDs beyond the table -> CUDA OOB assert # in the embeddings LayerNorm. Use the config value, with the standard # RoBERTa offset of 2 for the padding-idx position scheme. max_pos = getattr(encoder.config, "max_position_embeddings", 512) # RoBERTa reserves positions 0,1 (pad/offset) so usable length is max_pos - 2 safe_max_len = max_pos - 2 if max_pos <= 600 else 512 frozen_max_len = int(cfg.get("frozen_max_length", safe_max_len)) frozen_max_len = min(frozen_max_len, safe_max_len) print(" frozen encoder max_length = {} (model max_position={})".format( frozen_max_len, max_pos)) n_batches = (len(texts) + batch_size - 1) // batch_size report_every = max(1, n_batches // 10) # ── Crash-safe persistence: raw embeddings in a resumable memmap ──────── # This stage is the slowest in the pipeline (serial slow-BPE tokenisation # starves the GPU); losing it to a downstream crash costs ~10h. Progress # is checkpointed every 200 batches. hidden = encoder.config.hidden_size raw_path = prog_path = None start_batch = 0 emb_mm = None if cache_dir: Path(cache_dir).mkdir(parents=True, exist_ok=True) raw_path = Path(cache_dir) / "_frozen_emb_raw.npy" prog_path = Path(cache_dir) / "_frozen_emb_raw.progress" if raw_path.exists() and prog_path.exists(): try: cand = np.lib.format.open_memmap(str(raw_path), mode="r+") done = int(prog_path.read_text().strip() or 0) if cand.shape == (len(texts), hidden) and 0 < done <= n_batches: emb_mm, start_batch = cand, done print(" frozen emb: RESUMING from batch {}/{}".format( done, n_batches), flush=True) except Exception as e: print(" frozen emb: cache unreadable ({}) — restarting".format(e)) if emb_mm is None: emb_mm = np.lib.format.open_memmap(str(raw_path), mode="w+", dtype=np.float32, shape=(len(texts), hidden)) else: emb_mm = np.zeros((len(texts), hidden), dtype=np.float32) # Tokenise ONCE in parallel to cached arrays (proven _tokenize_and_cache # machinery), then stream the mmap through the GPU. Long-lived DataLoader # workers over the raw text list leak memory via fork copy-on-write; this # bounds worker lifetime to the tokenisation phase. max_length padding is # attention-masked, so embeddings match dynamic padding. frozen_tok_dir = Path(cache_dir) / "_frozen_tokens" if cache_dir else None if frozen_tok_dir is None: raise RuntimeError("frozen embeddings now require --cache_dir") if not (frozen_tok_dir / "input_ids.npy").exists(): _tokenize_and_cache(texts, tokenizer, frozen_max_len, True, frozen_tok_dir, num_workers=8) ids = np.load(str(frozen_tok_dir / "input_ids.npy"), mmap_mode="r") mask = np.load(str(frozen_tok_dir / "attention_mask.npy"), mmap_mode="r") for b_idx in range(start_batch, n_batches): s = b_idx * batch_size e = min(s + batch_size, len(texts)) input_ids = torch.from_numpy(np.ascontiguousarray(ids[s:e])).long() \ .clamp(0, vocab_size - 1).to(device) attn = torch.from_numpy(np.ascontiguousarray(mask[s:e])).long().to(device) with torch.no_grad(): out = encoder(input_ids=input_ids, attention_mask=attn) emb_mm[s:e] = out.last_hidden_state[:, 0, :].float().cpu().numpy() if prog_path is not None and (b_idx % 200 == 0 or b_idx == n_batches - 1): emb_mm.flush() prog_path.write_text(str(b_idx + 1)) if b_idx % report_every == 0 or b_idx == n_batches - 1: print(" frozen emb {}/{} ({:.0f}%)".format( b_idx + 1, n_batches, (b_idx + 1) / n_batches * 100), flush=True) del encoder gc.collect() if device.startswith("cuda"): torch.cuda.empty_cache() raw = np.asarray(emb_mm) # Apply the SAME PCA fitted during training. Re-fitting here would produce # different components and feed the meta-learner inconsistent features. import joblib pca_path = str(Path(cache_path).with_suffix("")) + "_pca.joblib" if cache_path else None if pca_path and Path(pca_path).exists(): bundle = joblib.load(pca_path) pca = bundle["pca"] reduced = pca.transform(raw).astype(np.float32) # transform, NOT fit_transform print(" Applied saved training PCA ({} -> {} dims)".format( raw.shape[1], reduced.shape[1])) else: raise FileNotFoundError( "Frozen PCA transform not found at {}.\n".format(pca_path) + "The meta-learner was trained with a specific PCA fit that must be " "reused at inference. Regenerate it by running the trainer's frozen " "embedding step on the TRAINING data, which saves _pca.joblib.\n" "Quick fix command:\n" " python scripts/regenerate_frozen_pca.py \\\n" " --frozen_encoder {} \\\n".format(model_name) + " --frozen_encoder_tokenizer {} \\\n".format(tok_name) + " --data_path data/labelled/.parquet \\\n" " --text_col text --max_length {} --n_components {} \\\n".format( frozen_max_len, n_comp) + " --cache_path {}".format(cache_path)) return reduced # ============================================================================= # MAIN # ============================================================================= def main(): args = parse_args() device = _normalise_device(args.device) # ── Load config, resolving all paths relative to the config file ────────── config_dir = Path(args.config).parent.resolve() with open(args.config) as f: cfg = json.load(f) def _resolve(p): """ Resolve a path from the config to an absolute path. Priority: 1. Absolute path in config -> use as-is 2. Relative to config_dir -> use if exists 3. Relative to cwd (project root) -> use if exists (catches paths like "experiments/ce_v1/artifacts" that were stored relative to the project root rather than the config file) 4. Just the filename next to config -> fallback for configs written before directory restructuring """ if p is None: return None pp = Path(p) if pp.is_absolute(): return str(pp) # Try relative to config dir by_config = (config_dir / pp).resolve() if by_config.exists(): return str(by_config) # Try relative to cwd (project root — most common for artifacts_dir) by_cwd = (Path.cwd() / pp).resolve() if by_cwd.exists(): return str(by_cwd) # Try just the filename next to the config by_name = (config_dir / pp.name).resolve() if by_name.exists(): print(" [NOTE] '{}' resolved to '{}' (filename fallback).".format( p, by_name)) return str(by_name) # Nothing found — return cwd-relative resolution so the error is readable print(" [WARN] Could not resolve path '{}' — tried:".format(p)) print(" config-relative : {}".format(by_config)) print(" cwd-relative : {}".format(by_cwd)) print(" filename : {}".format(by_name)) return str(by_cwd) # Patch all paths in cfg to be absolute cfg["meta_learner_path"] = _resolve(cfg["meta_learner_path"]) if cfg.get("frozen_emb_cache"): cfg["frozen_emb_cache"] = _resolve(cfg["frozen_emb_cache"]) for m in cfg.get("models", []): if m.get("artifacts_dir"): m["artifacts_dir"] = _resolve(m["artifacts_dir"]) print("="*60) print("META-LEARNER INFERENCE") print("="*60) print("Config :", cfg["label"]) print("Meta type :", cfg["meta_type"], " | CV F1:", cfg["meta_f1_cv"]) print("Classes :", cfg["class_order"]) print("Config dir:", config_dir) # ── Determine which columns to load from the parquet ───────────────────── # Load only what's needed: text + any tabular cols the models use. # This is critical for 1.7M-row datasets — loading all columns is wasteful. required_cols = {args.text_col} for m_cfg in cfg.get("models", []): required_cols.update(m_cfg.get("other_cols", [])) keep_all = args.keep_cols == "*" extra_keep = [] if args.keep_cols and args.keep_cols != "*": extra_keep = [c.strip() for c in args.keep_cols.split(",")] required_cols.update(extra_keep) print("\nLoading parquet columns:", sorted(required_cols) if not keep_all else "(all)") if keep_all: df = pd.read_parquet(args.data_path) else: import pyarrow.parquet as pq available = pq.read_schema(args.data_path).names cols_to_read = [c for c in required_cols if c in available] missing_at_load = required_cols - set(available) if missing_at_load: print(" [WARN] Columns not in parquet (will be filled with 0):", sorted(missing_at_load)) df = pd.read_parquet(args.data_path, columns=cols_to_read) n_total = len(df) print("Total rows:", n_total) # ── Separate null/empty text rows — assign UNKNOWN directly ────────────── # Handles actual NaN, Python None, empty string, and string "None". null_mask = ( df[args.text_col].isna() | (df[args.text_col].astype(str).str.strip() == "") | (df[args.text_col].astype(str).str.strip().str.lower() == "none") ) n_null = null_mask.sum() if n_null: print(" Null/empty text rows: {:,} — will be assigned UNKNOWN directly.".format(n_null)) # ── Deduplicate on text for inference efficiency ─────────────────────────── # Rows sharing the same text get inferred once and results are broadcast back. # Note: tabular other_cols may differ across dup rows — we use values from the # first occurrence. Use --no_dedup to run every row independently. df_valid = df[~null_mask].copy() if args.no_dedup: df_unique = df_valid n_unique = len(df_valid) n_dups = 0 print(" Deduplication disabled (--no_dedup).") else: df_unique = df_valid.drop_duplicates(subset=[args.text_col], keep="first") n_unique = len(df_unique) n_dups = len(df_valid) - n_unique print(" Valid rows : {:,}".format(len(df_valid))) print(" Unique texts : {:,}".format(n_unique)) print(" Duplicate rows : {:,} (will be filled from unique results)".format(n_dups)) print(" Inference on : {:,} rows ({:.1f}% of total)".format( n_unique, n_unique / n_total * 100)) texts = df_unique[args.text_col].fillna("").tolist() n = len(texts) # n is now unique count # ── Load meta-learner ───────────────────────────────────────────────────── import joblib bundle = joblib.load(cfg["meta_learner_path"]) meta = bundle["model"] class_order = bundle["class_order"] idx_to_lbl = bundle["idx_to_label"] n_classes = bundle["n_classes"] n_prob_cols = bundle["n_prob_cols"] feature_names = bundle.get("feature_names") # exact training feature order meta._n_prob_cols = n_prob_cols if feature_names: print(" Meta-learner expects {} features: {} prob/derived + {} embedding".format( len(feature_names), n_prob_cols, len(feature_names) - n_prob_cols)) k_folds = cfg.get("k_folds", 5) max_length = cfg.get("max_length", 256) use_derived = cfg.get("use_derived_features", False) # ── [1] Run each base model over the FULL dataset sequentially ──────────── # Models are loaded once and run end-to-end. This avoids reloading K fold # checkpoints per chunk, which would be extremely slow for 1.7M rows. # Memory: each model's output is (N, n_classes) float32 — ~39MB for 1.7M rows. # Cache dir: store per-model prob arrays next to output so a crash can resume. cache_dir = (Path(args.cache_dir) if args.cache_dir else Path(args.output_path).parent / "inference_cache") cache_dir.mkdir(parents=True, exist_ok=True) def _model_cache_path(key): safe = key.replace(":", "_").replace("/", "__") return cache_dir / "{}.npy".format(safe) def _frozen_cache_path(): return cache_dir / "_frozen_emb.npy" print("\n[1] Running base models (full dataset, sequential)...") print(" Resume cache dir: {}".format(cache_dir)) probs_by_key = {} for m_cfg in cfg["models"]: cname = m_cfg["clean_name"] src = m_cfg["source"] key = "{}:{}".format(src, cname) task = m_cfg.get("task_type", "classification") other_cols = m_cfg.get("other_cols", []) cache_path = _model_cache_path(key) # Resume: load cached probs if this model already completed if cache_path.exists(): probs = np.load(str(cache_path)) if probs.shape[0] == n: print(" [{}] {} — loaded from cache ({})".format( src, cname, cache_path.name)) probs_by_key[key] = probs continue else: print(" [{}] {} — cache shape mismatch ({}), re-running.".format( src, cname, probs.shape)) tab_feats = None if other_cols: tab_arr = np.zeros((n, len(other_cols)), dtype=np.float32) for i, col in enumerate(other_cols): if col in df_unique.columns: tab_arr[:, i] = df_unique[col].fillna(0).values.astype(np.float32) else: print(" [WARN] Tabular col '{}' missing for {} — using 0.".format( col, cname)) # --- train/serve parity: standardize tab features exactly like the generator # (ensemble_distillation_generator.py ~1833-1835: fillna(0) then StandardScaler) import joblib as _joblib _scaler_path = os.path.join(os.path.dirname(os.path.abspath(args.config)), 'tab_scaler.joblib') if not os.path.exists(_scaler_path): raise FileNotFoundError( 'other_cols=%s requires %s — heads were trained on standardized ' 'features; refusing to feed raw values' % (other_cols, _scaler_path)) _bundle = _joblib.load(_scaler_path) assert list(_bundle['other_cols']) == list(other_cols), ( 'scaler cols %s != config other_cols %s' % (_bundle['other_cols'], other_cols)) tab_arr = _bundle['scaler'].transform(tab_arr).astype(np.float32) tab_feats = tab_arr t0 = time.perf_counter() if task == "tfidf_lgbm": print(" [{}] {} — tfidf_lgbm...".format(src, cname)) probs = run_tfidf_lgbm(m_cfg, texts, tab_feats, k_folds) else: print(" [{}] {} — {} folds...".format(src, cname, k_folds)) probs = run_transformer_model( m_cfg, texts, tab_feats, max_length, device, args.batch_size, k_folds, num_workers=args.num_workers, prefetch=args.prefetch, token_cache_dir=cache_dir) elapsed = (time.perf_counter() - t0) * 1000 mem_mb = probs.nbytes / 1e6 print(" done shape={} {:.0f}ms {:.1f}MB".format( probs.shape, elapsed, mem_mb)) # Save to cache immediately — crash-safe np.save(str(cache_path), probs) print(" cached -> {}".format(cache_path.name)) probs_by_key[key] = probs # ── [2] Frozen encoder embeddings (full dataset) ────────────────────────── frozen_emb = None if cfg.get("frozen_encoder"): frozen_cache = _frozen_cache_path() if frozen_cache.exists(): frozen_emb = np.load(str(frozen_cache)) if frozen_emb.shape[0] == n: print("\n[2] Frozen embeddings loaded from cache ({}).".format( frozen_cache.name)) else: print("\n[2] Frozen cache shape mismatch — re-extracting...") frozen_emb = None if frozen_emb is None: print("\n[2] Frozen encoder embeddings (full dataset)...") t0 = time.perf_counter() frozen_emb = get_frozen_embeddings(texts, cfg, device, args.batch_size, cache_dir=args.cache_dir) np.save(str(frozen_cache), frozen_emb) print(" done shape={} {:.0f}ms {:.1f}MB cached->{}".format( frozen_emb.shape, (time.perf_counter() - t0) * 1000, frozen_emb.nbytes / 1e6, frozen_cache.name)) # Free the text list — no longer needed del texts gc.collect() # ── [3] Chunked feature assembly + meta predict on UNIQUE texts ───────── # Assemble features and run meta-learner in chunks over the unique-text rows. # Results are stored as arrays indexed by unique-row position. print("\n[3] Chunked meta-learner inference on {:,} unique texts " "(chunk_size={})...".format(n_unique, args.chunk_size)) all_preds = np.empty(n_unique, dtype=np.int32) all_proba = np.empty((n_unique, n_classes), dtype=np.float32) n_chunks = (n_unique + args.chunk_size - 1) // args.chunk_size # The bundle's feature_names lists ALL features (prob/derived + embeddings). # The first n_prob_cols are the prob/derived features build_feature_vector # must reproduce; the rest are embedding columns appended separately. prob_feat_names = feature_names[:n_prob_cols] if feature_names else None for chunk_idx in range(n_chunks): start = chunk_idx * args.chunk_size end = min(start + args.chunk_size, n_unique) sl = slice(start, end) chunk_probs = {k: v[sl] for k, v in probs_by_key.items()} X_chunk, _ = build_feature_vector( chunk_probs, class_order, n_classes, use_derived, expected_names=prob_feat_names) if frozen_emb is not None: X_chunk = np.hstack([X_chunk, frozen_emb[sl]]) proba_chunk = meta.predict_proba(X_chunk) all_preds[start:end] = np.argmax(proba_chunk, axis=1) all_proba[start:end] = proba_chunk if chunk_idx % 10 == 0 or chunk_idx == n_chunks - 1: print(" chunk {}/{} rows {}-{} ({:.0f}%)".format( chunk_idx + 1, n_chunks, start, end, end / n_unique * 100)) del X_chunk, proba_chunk gc.collect() # Free model prob arrays — no longer needed del probs_by_key, frozen_emb gc.collect() # ── [4] Build unique-text result lookup and broadcast to all rows ───────── print("\n[4] Broadcasting results to {:,} total rows...".format(n_total)) # Build a text -> (pred, proba) lookup using the unique results unique_texts_list = df_unique[args.text_col].tolist() text_to_pred = dict(zip(unique_texts_list, all_preds.tolist())) text_to_proba = dict(zip(unique_texts_list, all_proba.tolist())) del all_preds, all_proba, unique_texts_list gc.collect() # Unknown label index # Normalise idx_to_lbl keys to int — the pickle may store them as int OR str, # and inconsistent key types caused every label lookup to silently fall back # to UNKNOWN. Build one canonical int-keyed map used everywhere below. idx_to_lbl_int = {int(k): v for k, v in idx_to_lbl.items()} print(" Label map: {}".format( {k: idx_to_lbl_int[k] for k in sorted(idx_to_lbl_int)})) unknown_idx = next( (k for k, v in idx_to_lbl_int.items() if v == "UNKNOWN"), n_classes - 1) unknown_label = idx_to_lbl_int.get(unknown_idx, "UNKNOWN") unknown_proba = [0.0] * n_classes unknown_proba[unknown_idx] = 1.0 # Write output in chunks, reading original row index to broadcast output_path = Path(args.output_path) output_path.parent.mkdir(parents=True, exist_ok=True) pred_cols = (["predicted_class", "predicted_label", "meta_confidence"] + ["prob_" + cls for cls in class_order]) first_chunk = True label_counts = {} out_chunks = (n_total + args.chunk_size - 1) // args.chunk_size orig_texts = df[args.text_col].astype(str).str.strip().values for chunk_idx in range(out_chunks): start = chunk_idx * args.chunk_size end = min(start + args.chunk_size, n_total) out = {} if extra_keep: for col in extra_keep: if col in df.columns: out[col] = df[col].iloc[start:end].values else: out[col] = np.zeros(end - start, dtype=np.float32) preds_out = [] labels_out = [] conf_out = [] proba_out = [[] for _ in range(n_classes)] for row_text, is_null in zip( orig_texts[start:end], null_mask.values[start:end]): if is_null or row_text.lower() == "none" or row_text == "": # Null text — assign UNKNOWN p_idx = unknown_idx p_lbl = unknown_label p_prob = unknown_proba else: p_idx = text_to_pred.get(row_text, unknown_idx) p_lbl = idx_to_lbl_int.get(int(p_idx), unknown_label) p_prob = text_to_proba.get(row_text, unknown_proba) preds_out.append(p_idx) labels_out.append(p_lbl) conf_out.append(max(p_prob)) for i, v in enumerate(p_prob): proba_out[i].append(v) out["predicted_class"] = preds_out out["predicted_label"] = labels_out out["meta_confidence"] = conf_out for i, cls in enumerate(class_order): out["prob_" + cls] = proba_out[i] chunk_df = pd.DataFrame(out) # Track distribution for lbl, cnt in chunk_df["predicted_label"].value_counts().items(): label_counts[lbl] = label_counts.get(lbl, 0) + cnt # Write / append try: if first_chunk: chunk_df.to_parquet(str(output_path), index=False, engine="fastparquet") else: chunk_df.to_parquet(str(output_path), index=False, engine="fastparquet", append=True) except Exception: chunk_path = output_path.parent / "_chunk_{:05d}.parquet".format(chunk_idx) chunk_df.to_parquet(str(chunk_path), index=False) if chunk_idx % 10 == 0 or chunk_idx == out_chunks - 1: print(" wrote chunk {}/{} ({:.0f}%)".format( chunk_idx + 1, out_chunks, end / n_total * 100)) first_chunk = False del chunk_df gc.collect() # Merge loose chunk files if fastparquet wasn't available chunk_files = sorted(output_path.parent.glob("_chunk_*.parquet")) if chunk_files: print(" Merging {} chunk files...".format(len(chunk_files))) pd.concat([pd.read_parquet(f) for f in chunk_files], ignore_index=True).to_parquet(str(output_path), index=False) for f in chunk_files: f.unlink() # Keep the cache by default: base-model outputs and tokenisation are # expensive and reusable for re-runs on the same pool (e.g. after a # meta-learner swap, which needs no GPU work at all). Pass --clear_cache # to remove it on success. if args.clear_cache and cache_dir.exists(): import shutil shutil.rmtree(cache_dir) print(" Resume cache cleared (--clear_cache).") else: print(" Resume cache kept -> {}".format(cache_dir)) print("\n Predictions saved ->", output_path) print(" Total rows : {:,}".format(n_total)) print(" Null rows (UNKNOWN): {:,}".format(n_null)) print(" Deduped rows saved : {:,}".format(n_dups)) print(" Label distribution :") for lbl, cnt in sorted(label_counts.items(), key=lambda x: -x[1]): print(" {:<20s} {:>8,} ({:.1f}%)".format( lbl, cnt, cnt / n_total * 100)) print("="*60) if __name__ == "__main__": main()