"""Train and compare TF-IDF baseline vs fine-tuned Afro-XLMR encoder, saving under artifacts/.""" import json import random import shutil import time from typing import Dict, List import joblib import numpy as np import pandas as pd import torch from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix, f1_score from sklearn.pipeline import FeatureUnion, Pipeline from torch.utils.data import Dataset from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments, set_seed, ) from src.config import ( ARTIFACTS_DIR, BASELINE_DIR, CLASSIFIER_COMPARISON_PATH, ENCODER_BASE_MODEL_ID, FINE_TUNED_DIR, INTENT_DATASET_PATH, INTENT_LABELS, LABEL_MAP_PATH, RANDOM_SEED, TFIDF_MODEL_PATH, ) def seed_everything(seed: int = RANDOM_SEED) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) set_seed(seed) class IntentTextDataset(Dataset): def __init__(self, texts: List[str], labels: List[int], tokenizer, max_length: int = 96): self.encodings = tokenizer( texts, truncation=True, padding=True, max_length=max_length, ) self.labels = labels def __len__(self) -> int: return len(self.labels) def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]: item = {k: torch.tensor(v[idx]) for k, v in self.encodings.items()} item["labels"] = torch.tensor(self.labels[idx], dtype=torch.long) return item def build_tfidf_pipeline(mode: str, c_val: float) -> Pipeline: if mode == "word": features = TfidfVectorizer(ngram_range=(1, 2), lowercase=True, sublinear_tf=True) elif mode == "char_wb": features = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), lowercase=True, sublinear_tf=True) elif mode == "word+char": features = FeatureUnion( [ ("word", TfidfVectorizer(ngram_range=(1, 2), lowercase=True, sublinear_tf=True)), ("char", TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), lowercase=True, sublinear_tf=True)), ] ) else: raise ValueError(mode) return Pipeline( [ ("tfidf", features), ("clf", LogisticRegression(C=c_val, max_iter=2000, random_state=RANDOM_SEED, class_weight="balanced")), ] ) def train_tfidf_baseline(df: pd.DataFrame) -> dict: train_df = df[df["split"] == "train"] val_df = df[df["split"] == "val"] test_df = df[df["split"] == "test"] best_cfg = None best_val_f1 = -1.0 val_trials = [] for mode in ["word", "char_wb", "word+char"]: for c_val in [0.5, 1.0, 2.0, 5.0]: pipe = build_tfidf_pipeline(mode, c_val) pipe.fit(train_df["text"].tolist(), train_df["intent"].tolist()) val_preds = pipe.predict(val_df["text"].tolist()) vf1 = float(f1_score(val_df["intent"], val_preds, labels=INTENT_LABELS, average="macro")) val_trials.append({"mode": mode, "C": c_val, "val_macro_f1": round(vf1, 4)}) if vf1 > best_val_f1: best_val_f1 = vf1 best_cfg = (mode, c_val) best_mode, best_c = best_cfg final_pipe = build_tfidf_pipeline(best_mode, best_c) final_pipe.fit(train_df["text"].tolist(), train_df["intent"].tolist()) BASELINE_DIR.mkdir(parents=True, exist_ok=True) joblib.dump(final_pipe, TFIDF_MODEL_PATH) start = time.perf_counter() test_preds = final_pipe.predict(test_df["text"].tolist()) test_latency_ms = ((time.perf_counter() - start) * 1000.0) / len(test_df) test_f1 = float(f1_score(test_df["intent"], test_preds, labels=INTENT_LABELS, average="macro")) cm = confusion_matrix(test_df["intent"], test_preds, labels=INTENT_LABELS).tolist() report = classification_report( test_df["intent"], test_preds, labels=INTENT_LABELS, output_dict=True, zero_division=0 ) confused = [] for row, pred in zip(test_df.to_dict(orient="records"), test_preds): if row["intent"] != pred: confused.append( { "request_id": row["request_id"], "language": row["language"], "text": row["text"], "true_intent": row["intent"], "predicted_intent": str(pred), } ) return { "model_name": "TF-IDF + LogisticRegression", "selected_settings": {"feature_mode": best_mode, "C": best_c}, "validation_trials": val_trials, "val_macro_f1": round(best_val_f1, 4), "test_macro_f1": round(test_f1, 4), "test_latency_ms_per_query": round(test_latency_ms, 3), "confusion_matrix_labels": INTENT_LABELS, "confusion_matrix": cm, "classification_report": report, "confused_examples": confused, } def train_finetuned_encoder(df: pd.DataFrame) -> dict: seed_everything(RANDOM_SEED) train_df = df[df["split"] == "train"] val_df = df[df["split"] == "val"] test_df = df[df["split"] == "test"] label2id = {lbl: idx for idx, lbl in enumerate(INTENT_LABELS)} id2label = {idx: lbl for idx, lbl in enumerate(INTENT_LABELS)} tokenizer = AutoTokenizer.from_pretrained(ENCODER_BASE_MODEL_ID) config = AutoConfig.from_pretrained( ENCODER_BASE_MODEL_ID, num_labels=len(INTENT_LABELS), id2label=id2label, label2id=label2id, ) model_revision = getattr(config, "_commit_hash", None) or "main" train_ds = IntentTextDataset(train_df["text"].tolist(), [label2id[x] for x in train_df["intent"]], tokenizer) val_ds = IntentTextDataset(val_df["text"].tolist(), [label2id[x] for x in val_df["intent"]], tokenizer) def compute_metrics(eval_pred): logits, labels = eval_pred preds = np.argmax(logits, axis=-1) return {"macro_f1": float(f1_score(labels, preds, average="macro"))} best_lr = None best_val_f1 = -1.0 best_trainer = None val_trials = [] tmp_dir = ARTIFACTS_DIR / "_encoder_runs" for lr in [3e-5, 5e-5]: seed_everything(RANDOM_SEED) model = AutoModelForSequenceClassification.from_pretrained(ENCODER_BASE_MODEL_ID, config=config) args = TrainingArguments( output_dir=str(tmp_dir / f"lr_{lr}"), learning_rate=lr, per_device_train_batch_size=8, per_device_eval_batch_size=16, num_train_epochs=8, weight_decay=0.01, warmup_steps=5, eval_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="macro_f1", greater_is_better=True, save_total_limit=1, seed=RANDOM_SEED, logging_strategy="epoch", report_to="none", use_cpu=not torch.cuda.is_available(), ) trainer = Trainer( model=model, args=args, train_dataset=train_ds, eval_dataset=val_ds, compute_metrics=compute_metrics, ) trainer.train() eval_metrics = trainer.evaluate(val_ds) vf1 = float(eval_metrics["eval_macro_f1"]) val_trials.append({"learning_rate": lr, "epochs": 8, "val_macro_f1": round(vf1, 4)}) if vf1 > best_val_f1: best_val_f1 = vf1 best_lr = lr best_trainer = trainer FINE_TUNED_DIR.mkdir(parents=True, exist_ok=True) best_trainer.save_model(str(FINE_TUNED_DIR)) tokenizer.save_pretrained(str(FINE_TUNED_DIR)) shutil.rmtree(tmp_dir, ignore_errors=True) label_payload = json.dumps( { "base_model_id": ENCODER_BASE_MODEL_ID, "model_revision": model_revision, "seed": RANDOM_SEED, "label2id": label2id, "id2label": {str(k): v for k, v in id2label.items()}, }, indent=2, ) LABEL_MAP_PATH.write_text(label_payload, encoding="utf-8") (FINE_TUNED_DIR / "label_map.json").write_text(label_payload, encoding="utf-8") reloaded_tok = AutoTokenizer.from_pretrained(FINE_TUNED_DIR) reloaded_model = AutoModelForSequenceClassification.from_pretrained(FINE_TUNED_DIR) reloaded_model.eval() device = "cuda" if torch.cuda.is_available() else "cpu" reloaded_model.to(device) test_preds: List[str] = [] start = time.perf_counter() with torch.inference_mode(): for text in test_df["text"].tolist(): enc = reloaded_tok(text, truncation=True, max_length=96, return_tensors="pt").to(device) logits = reloaded_model(**enc).logits[0] test_preds.append(id2label[int(torch.argmax(logits).item())]) test_latency_ms = ((time.perf_counter() - start) * 1000.0) / len(test_df) test_f1 = float(f1_score(test_df["intent"], test_preds, labels=INTENT_LABELS, average="macro")) cm = confusion_matrix(test_df["intent"], test_preds, labels=INTENT_LABELS).tolist() report = classification_report( test_df["intent"], test_preds, labels=INTENT_LABELS, output_dict=True, zero_division=0 ) confused = [] for row, pred in zip(test_df.to_dict(orient="records"), test_preds): if row["intent"] != pred: confused.append( { "request_id": row["request_id"], "language": row["language"], "text": row["text"], "true_intent": row["intent"], "predicted_intent": pred, } ) return { "model_name": ENCODER_BASE_MODEL_ID, "model_revision": model_revision, "seed": RANDOM_SEED, "selected_settings": { "learning_rate": best_lr, "epochs": 8, "batch_size": 8, "max_length": 96, "weight_decay": 0.01, "warmup_steps": 5, }, "validation_trials": val_trials, "val_macro_f1": round(best_val_f1, 4), "test_macro_f1": round(test_f1, 4), "test_latency_ms_per_query": round(test_latency_ms, 3), "confusion_matrix_labels": INTENT_LABELS, "confusion_matrix": cm, "classification_report": report, "confused_examples": confused, "checkpoint_reloaded_verified": True, } def main() -> None: df = pd.read_csv(INTENT_DATASET_PATH) test_counts = df[df["split"] == "test"]["intent"].value_counts().to_dict() split_counts = df["split"].value_counts().to_dict() tfidf_res = train_tfidf_baseline(df) encoder_res = train_finetuned_encoder(df) comparison = { "dataset_path": str(INTENT_DATASET_PATH.name), "split_counts": split_counts, "test_counts_per_intent": test_counts, "family_overlap_across_splits": 0, "baseline": tfidf_res, "fine_tuned_encoder": encoder_res, } CLASSIFIER_COMPARISON_PATH.write_text(json.dumps(comparison, indent=2), encoding="utf-8") print(f"Saved classifier comparison to {CLASSIFIER_COMPARISON_PATH}") if __name__ == "__main__": main()