script-fidelity-benchmark / scripts /eval_downstream_mt.py
themechanism's picture
Clean artifact layout and dataset viewer configs
cc7d399 verified
#!/usr/bin/env python3
"""Downstream MT validation for Gemma 4 ASR outputs.
The script translates gold FLEURS transcripts, baseline Gemma 4 ASR outputs,
and script-aware Gemma 4 ASR outputs into English with NLLB. It then measures
how much translation quality drops relative to gold-transcript MT.
"""
from __future__ import annotations
import argparse
import json
import logging
import random
import sys
from collections import defaultdict, deque
from pathlib import Path
from types import ModuleType
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).parent))
from runtime_cache import configure_runtime_cache
configure_runtime_cache(ROOT)
import pandas as pd
import torch
from huggingface_hub import hf_hub_download
from tqdm import tqdm
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from script_fidelity import SCRIPT_CONFIGS, compute_sfr
LANGUAGES = [
"pashto",
"urdu",
"arabic",
"persian",
"hindi",
"bengali",
"malayalam",
"tamil",
"somali",
"georgian",
]
NLLB_LANG_CODES = {
"pashto": "pbt_Arab",
"urdu": "urd_Arab",
"arabic": "arb_Arab",
"persian": "pes_Arab",
"hindi": "hin_Deva",
"bengali": "ben_Beng",
"malayalam": "mal_Mlym",
"tamil": "tam_Taml",
"somali": "som_Latn",
"georgian": "kat_Geor",
}
VARIANTS = {
"gold": "Gold transcript",
"baseline": "Gemma 4 baseline ASR",
"script_hint": "Gemma 4 script-aware ASR",
}
MODEL_ID = "unsloth/gemma-4-E2B-it"
TARGET_LANG = "eng_Latn"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("downstream_mt")
sacrebleu: ModuleType | None = None
def require_sacrebleu() -> ModuleType:
global sacrebleu
if sacrebleu is not None:
return sacrebleu
try:
import sacrebleu as sacrebleu_module
except ModuleNotFoundError as exc:
raise SystemExit(
"Missing dependency: sacrebleu. Run `uv pip install -r requirements.txt` "
"from paper_sfr, then rerun this script."
) from exc
sacrebleu = sacrebleu_module
return sacrebleu
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Translate Gemma 4 ASR outputs to English and score downstream MT damage."
)
parser.add_argument("--mt-model", default="facebook/nllb-200-distilled-600M")
parser.add_argument("--baseline-predictions-dir", default=str(ROOT / "results_gemma4" / "predictions"))
parser.add_argument(
"--script-hint-predictions-dir",
default=str(ROOT / "results_gemma4_prompt_mitigation" / "predictions"),
)
parser.add_argument("--mitigation-summary", default=str(ROOT / "analysis" / "gemma4_prompt_mitigation_summary.csv"))
parser.add_argument("--results-dir", default=str(ROOT / "results_gemma4_downstream_mt"))
parser.add_argument("--summary-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_summary.csv"))
parser.add_argument("--utterance-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_utterances.csv"))
parser.add_argument("--correlation-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_correlations.csv"))
parser.add_argument("--languages", nargs="+", default=LANGUAGES)
parser.add_argument(
"--max-examples-per-language",
type=int,
default=100,
help="Use 0 for all aligned examples. The default keeps the run deadline-friendly.",
)
parser.add_argument(
"--sample-mode",
choices=["random", "stratified_sfr", "first"],
default="stratified_sfr",
help="stratified_sfr includes low-, mixed-, and high-SFR baseline examples when available.",
)
parser.add_argument("--batch-size", type=int, default=16)
parser.add_argument("--max-input-tokens", type=int, default=256)
parser.add_argument("--max-new-tokens", type=int, default=128)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--force", action="store_true", help="Recompute translation JSON files.")
parser.add_argument("--summarize-only", action="store_true", help="Reuse saved translation JSON files.")
parser.add_argument("--validate-only", action="store_true", help="Check alignment and exit before loading MT.")
parser.add_argument("--device", choices=["auto", "cpu", "cuda", "mps"], default="auto")
return parser.parse_args()
def clean_model_name(model_id: str) -> str:
return (
model_id.replace("/", "_")
.replace("-", "_")
.replace(".", "_")
.replace(" ", "_")
)
def prediction_path(preds_dir: Path, language: str, variant: str) -> Path:
if variant == "baseline":
return preds_dir / f"gemma4_{language}_predictions.json"
if variant == "script_hint":
return preds_dir / f"gemma4_script_hint_{language}_predictions.json"
raise ValueError(f"Prediction variant has no file: {variant}")
def read_prediction_file(path: Path) -> tuple[list[str], list[str]]:
if not path.exists():
raise FileNotFoundError(path)
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
refs = data.get("references", [])
preds = data.get("predictions", [])
if not refs or not preds:
raise ValueError(f"Prediction file lacks references or predictions: {path}")
return refs, preds
def download_fleurs_tsv(fleurs_code: str) -> Path:
try:
return Path(
hf_hub_download(
repo_id="google/fleurs",
filename=f"data/{fleurs_code}/test.tsv",
repo_type="dataset",
)
)
except Exception as exc:
raise SystemExit(
"Could not load FLEURS test metadata. The downstream MT script only "
"needs data/{lang}/test.tsv files, but Hugging Face access is required "
"unless those files are already cached. Check network access or pre-cache "
"the FLEURS metadata files."
) from exc
def read_fleurs_tsv(path: Path) -> list[dict]:
records = []
with open(path, encoding="utf-8") as handle:
for line in handle:
parts = line.rstrip("\n").split("\t")
if len(parts) < 4:
continue
records.append(
{
"id": str(parts[0]),
"file_name": parts[1],
"raw_transcription": parts[2],
"text": parts[3],
}
)
return records
def load_fleurs_text_records(language: str) -> list[dict]:
code = SCRIPT_CONFIGS[language].fleurs_code
return read_fleurs_tsv(download_fleurs_tsv(code))
def load_english_reference_by_id() -> dict[str, str]:
return {record["id"]: record["text"] for record in read_fleurs_tsv(download_fleurs_tsv("en_us"))}
def align_records_to_prediction_refs(language: str, records: list[dict], refs: list[str]) -> list[dict]:
by_text: dict[str, deque[dict]] = defaultdict(deque)
for record in records:
by_text[record["text"]].append(record)
aligned = []
missing = []
for idx, ref in enumerate(refs):
bucket = by_text.get(ref)
if not bucket:
missing.append((idx, ref))
continue
aligned.append(bucket.popleft())
if missing:
preview = "; ".join(f"{idx}: {text[:80]}" for idx, text in missing[:3])
raise ValueError(
f"{language}: could not align {len(missing)} prediction references "
f"to FLEURS test.tsv transcriptions. First misses: {preview}"
)
return aligned
def make_aligned_examples(
language: str,
english_by_id: dict[str, str],
baseline_preds_dir: Path,
script_hint_preds_dir: Path,
) -> list[dict]:
src_records = load_fleurs_text_records(language)
gold_refs, baseline_preds = read_prediction_file(
prediction_path(baseline_preds_dir, language, "baseline")
)
_, hint_preds = read_prediction_file(
prediction_path(script_hint_preds_dir, language, "script_hint")
)
if len(hint_preds) != len(gold_refs):
raise ValueError(
f"{language}: script-hint predictions ({len(hint_preds)}) do not match "
f"baseline references ({len(gold_refs)})."
)
aligned_records = align_records_to_prediction_refs(language, src_records, gold_refs)
examples = []
missing_english = 0
for idx, record in enumerate(aligned_records):
english_ref = english_by_id.get(record["id"])
if english_ref is None:
missing_english += 1
continue
examples.append(
{
"language": language,
"example_id": record["id"],
"source_ref": gold_refs[idx],
"english_ref": english_ref,
"baseline_pred": baseline_preds[idx],
"script_hint_pred": hint_preds[idx],
"baseline_sfr_utt": compute_sfr(baseline_preds[idx], language),
"script_hint_sfr_utt": compute_sfr(hint_preds[idx], language),
}
)
if missing_english:
log.warning("%s: skipped %d examples without English FLEURS reference IDs", language, missing_english)
if not examples:
raise ValueError(f"{language}: no examples aligned to English FLEURS by ID")
return examples
def select_examples(
examples: list[dict],
max_examples: int,
mode: str,
seed: int,
) -> list[dict]:
if max_examples <= 0 or len(examples) <= max_examples:
return examples
if mode == "first":
return examples[:max_examples]
rng = random.Random(seed)
if mode == "random":
return [examples[i] for i in sorted(rng.sample(range(len(examples)), max_examples))]
bins = {"low": [], "mixed": [], "high": []}
for idx, ex in enumerate(examples):
score = ex["baseline_sfr_utt"]
if score is None:
bins["mixed"].append(idx)
elif score < 0.10:
bins["low"].append(idx)
elif score < 0.90:
bins["mixed"].append(idx)
else:
bins["high"].append(idx)
selected: set[int] = set()
target_per_bin = max(1, max_examples // 3)
for name in ["low", "mixed", "high"]:
candidates = bins[name][:]
rng.shuffle(candidates)
selected.update(candidates[:target_per_bin])
remaining = [idx for idx in range(len(examples)) if idx not in selected]
rng.shuffle(remaining)
for idx in remaining:
if len(selected) >= max_examples:
break
selected.add(idx)
return [examples[i] for i in sorted(selected)]
def choose_device(requested: str) -> str:
if requested != "auto":
return requested
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available():
return "mps"
return "cpu"
def load_mt_model(model_id: str, device: str):
log.info("Loading MT model: %s", model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
kwargs = {}
if device == "cuda":
kwargs["torch_dtype"] = torch.float16
model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **kwargs)
model = model.to(device).eval()
return tokenizer, model
def translation_json_path(translations_dir: Path, model_id: str, language: str, variant: str) -> Path:
return translations_dir / f"{clean_model_name(model_id)}_{language}_{variant}_translations.json"
def load_saved_translations(path: Path, expected_n: int) -> list[str] | None:
if not path.exists():
return None
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
translations = data.get("translations", [])
if len(translations) != expected_n:
log.warning("Ignoring %s because it has %d rows, expected %d", path, len(translations), expected_n)
return None
return translations
def save_translations(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False)
def translate_texts(
texts: list[str],
tokenizer,
model,
source_lang: str,
target_lang: str,
device: str,
batch_size: int,
max_input_tokens: int,
max_new_tokens: int,
desc: str,
) -> list[str]:
tokenizer.src_lang = source_lang
forced_bos = tokenizer.convert_tokens_to_ids(target_lang)
if forced_bos is None or forced_bos == tokenizer.unk_token_id:
raise ValueError(f"Tokenizer does not know target language token: {target_lang}")
outputs = [""] * len(texts)
active = [(idx, text.strip()) for idx, text in enumerate(texts) if str(text).strip()]
for start in tqdm(range(0, len(active), batch_size), desc=desc, leave=False):
batch = active[start:start + batch_size]
batch_indices = [idx for idx, _ in batch]
batch_texts = [text for _, text in batch]
inputs = tokenizer(
batch_texts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=max_input_tokens,
).to(device)
with torch.no_grad():
generated = model.generate(
**inputs,
forced_bos_token_id=forced_bos,
max_new_tokens=max_new_tokens,
num_beams=1,
)
decoded = tokenizer.batch_decode(generated, skip_special_tokens=True)
for idx, text in zip(batch_indices, decoded):
outputs[idx] = text.strip()
return outputs
def get_or_run_translations(
examples: list[dict],
variant: str,
language: str,
args: argparse.Namespace,
translations_dir: Path,
tokenizer,
model,
device: str,
) -> list[str]:
path = translation_json_path(translations_dir, args.mt_model, language, variant)
if not args.force:
saved = load_saved_translations(path, len(examples))
if saved is not None:
log.info("Reusing %s", path)
return saved
if args.summarize_only:
raise FileNotFoundError(f"Missing saved translations for summarize-only mode: {path}")
if variant == "gold":
texts = [ex["source_ref"] for ex in examples]
elif variant == "baseline":
texts = [ex["baseline_pred"] for ex in examples]
elif variant == "script_hint":
texts = [ex["script_hint_pred"] for ex in examples]
else:
raise ValueError(variant)
translations = translate_texts(
texts=texts,
tokenizer=tokenizer,
model=model,
source_lang=NLLB_LANG_CODES[language],
target_lang=TARGET_LANG,
device=device,
batch_size=args.batch_size,
max_input_tokens=args.max_input_tokens,
max_new_tokens=args.max_new_tokens,
desc=f"MT/{language}/{variant}",
)
save_translations(
path,
{
"mt_model": args.mt_model,
"source_language": language,
"source_lang_code": NLLB_LANG_CODES[language],
"target_lang_code": TARGET_LANG,
"variant": variant,
"variant_label": VARIANTS[variant],
"translations": translations,
},
)
return translations
def corpus_scores(hypotheses: list[str], references: list[str]) -> dict[str, float]:
scorer = require_sacrebleu()
return {
"chrf": round(scorer.corpus_chrf(hypotheses, [references]).score, 2),
"bleu": round(scorer.corpus_bleu(hypotheses, [references]).score, 2),
}
def sentence_chrf(hypothesis: str, reference: str) -> float:
scorer = require_sacrebleu()
return round(scorer.sentence_chrf(hypothesis, [reference]).score, 2)
def read_mitigation_summary(path: Path) -> pd.DataFrame:
if not path.exists():
raise FileNotFoundError(f"Missing mitigation summary: {path}")
df = pd.read_csv(path)
required = {
"language",
"baseline_sfr_mean",
"script_hint_sfr_mean",
"delta_sfr",
"baseline_wer_pct",
"script_hint_wer_pct",
"delta_wer",
}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Mitigation summary lacks columns: {sorted(missing)}")
return df.set_index("language")
def make_language_rows(
language: str,
examples: list[dict],
translations: dict[str, list[str]],
stats: pd.DataFrame,
args: argparse.Namespace,
) -> tuple[dict, list[dict]]:
english_refs = [ex["english_ref"] for ex in examples]
scores = {
variant: corpus_scores(translations[variant], english_refs)
for variant in VARIANTS
}
stat = stats.loc[language]
summary = {
"language": language,
"n_aligned": len(examples),
"sample_mode": args.sample_mode,
"max_examples_per_language": args.max_examples_per_language,
"mt_model": args.mt_model,
"src_lang_code": NLLB_LANG_CODES[language],
"baseline_sfr_mean": stat["baseline_sfr_mean"],
"script_hint_sfr_mean": stat["script_hint_sfr_mean"],
"delta_sfr": stat["delta_sfr"],
"baseline_wer_pct": stat["baseline_wer_pct"],
"script_hint_wer_pct": stat["script_hint_wer_pct"],
"delta_wer": stat["delta_wer"],
"gold_chrf": scores["gold"]["chrf"],
"baseline_chrf": scores["baseline"]["chrf"],
"script_hint_chrf": scores["script_hint"]["chrf"],
"baseline_chrf_drop": round(scores["gold"]["chrf"] - scores["baseline"]["chrf"], 2),
"script_hint_chrf_drop": round(scores["gold"]["chrf"] - scores["script_hint"]["chrf"], 2),
"chrf_recovery": round(scores["script_hint"]["chrf"] - scores["baseline"]["chrf"], 2),
"gold_bleu": scores["gold"]["bleu"],
"baseline_bleu": scores["baseline"]["bleu"],
"script_hint_bleu": scores["script_hint"]["bleu"],
"baseline_bleu_drop": round(scores["gold"]["bleu"] - scores["baseline"]["bleu"], 2),
"script_hint_bleu_drop": round(scores["gold"]["bleu"] - scores["script_hint"]["bleu"], 2),
"bleu_recovery": round(scores["script_hint"]["bleu"] - scores["baseline"]["bleu"], 2),
}
utterance_rows = []
for idx, ex in enumerate(examples):
gold_chrf = sentence_chrf(translations["gold"][idx], ex["english_ref"])
baseline_chrf = sentence_chrf(translations["baseline"][idx], ex["english_ref"])
hint_chrf = sentence_chrf(translations["script_hint"][idx], ex["english_ref"])
utterance_rows.append(
{
"language": language,
"example_id": ex["example_id"],
"baseline_sfr_utt": None if ex["baseline_sfr_utt"] is None else round(ex["baseline_sfr_utt"] * 100, 2),
"script_hint_sfr_utt": None if ex["script_hint_sfr_utt"] is None else round(ex["script_hint_sfr_utt"] * 100, 2),
"gold_chrf_sent": gold_chrf,
"baseline_chrf_sent": baseline_chrf,
"script_hint_chrf_sent": hint_chrf,
"baseline_chrf_drop_sent": round(gold_chrf - baseline_chrf, 2),
"script_hint_chrf_drop_sent": round(gold_chrf - hint_chrf, 2),
"chrf_recovery_sent": round(hint_chrf - baseline_chrf, 2),
"english_ref": ex["english_ref"],
"source_ref": ex["source_ref"],
"baseline_pred": ex["baseline_pred"],
"script_hint_pred": ex["script_hint_pred"],
"gold_mt": translations["gold"][idx],
"baseline_mt": translations["baseline"][idx],
"script_hint_mt": translations["script_hint"][idx],
}
)
return summary, utterance_rows
def spearman(xs: pd.Series, ys: pd.Series) -> float | None:
paired = pd.DataFrame({"x": xs, "y": ys}).dropna()
if len(paired) < 3:
return None
value = paired["x"].rank(method="average").corr(paired["y"].rank(method="average"))
return None if pd.isna(value) else round(float(value), 3)
def write_correlations(summary_df: pd.DataFrame, path: Path) -> None:
rows = [
{
"x": "baseline_sfr_mean",
"y": "baseline_chrf_drop",
"spearman_r": spearman(summary_df["baseline_sfr_mean"], summary_df["baseline_chrf_drop"]),
"n": len(summary_df),
"expected_direction": "negative",
},
{
"x": "baseline_wer_pct",
"y": "baseline_chrf_drop",
"spearman_r": spearman(summary_df["baseline_wer_pct"], summary_df["baseline_chrf_drop"]),
"n": len(summary_df),
"expected_direction": "positive",
},
{
"x": "delta_sfr",
"y": "chrf_recovery",
"spearman_r": spearman(summary_df["delta_sfr"], summary_df["chrf_recovery"]),
"n": len(summary_df),
"expected_direction": "positive",
},
{
"x": "delta_wer",
"y": "chrf_recovery",
"spearman_r": spearman(summary_df["delta_wer"], summary_df["chrf_recovery"]),
"n": len(summary_df),
"expected_direction": "negative",
},
]
path.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(rows).to_csv(path, index=False)
def main() -> None:
args = parse_args()
baseline_preds_dir = Path(args.baseline_predictions_dir)
script_hint_preds_dir = Path(args.script_hint_predictions_dir)
results_dir = Path(args.results_dir)
translations_dir = results_dir / "translations"
results_dir.mkdir(parents=True, exist_ok=True)
translations_dir.mkdir(parents=True, exist_ok=True)
fh = logging.FileHandler(results_dir / "eval_downstream_mt.log")
fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
log.addHandler(fh)
stats = read_mitigation_summary(Path(args.mitigation_summary))
missing_stats = [lang for lang in args.languages if lang not in stats.index]
if missing_stats:
raise SystemExit(f"Mitigation summary lacks languages: {', '.join(missing_stats)}")
english_by_id = load_english_reference_by_id()
device = choose_device(args.device)
log.info("Device: %s", device)
tokenizer = model = None
if not args.summarize_only and not args.validate_only:
tokenizer, model = load_mt_model(args.mt_model, device)
summary_rows = []
utterance_rows = []
validation_rows = []
for lang in args.languages:
if lang not in NLLB_LANG_CODES:
raise ValueError(f"No NLLB language code configured for {lang}")
examples = make_aligned_examples(lang, english_by_id, baseline_preds_dir, script_hint_preds_dir)
total_aligned = len(examples)
examples = select_examples(
examples,
max_examples=args.max_examples_per_language,
mode=args.sample_mode,
seed=args.seed,
)
log.info("%s: %d aligned examples selected", lang, len(examples))
validation_rows.append(
{
"language": lang,
"total_aligned": total_aligned,
"selected": len(examples),
"sample_mode": args.sample_mode,
"max_examples_per_language": args.max_examples_per_language,
"src_lang_code": NLLB_LANG_CODES[lang],
}
)
if args.validate_only:
continue
translations = {}
for variant in VARIANTS:
translations[variant] = get_or_run_translations(
examples,
variant,
lang,
args,
translations_dir,
tokenizer,
model,
device,
)
summary, rows = make_language_rows(lang, examples, translations, stats, args)
summary_rows.append(summary)
utterance_rows.extend(rows)
if args.validate_only:
alignment_csv = results_dir / "alignment_check.csv"
pd.DataFrame(validation_rows).to_csv(alignment_csv, index=False)
log.info("Wrote %s", alignment_csv)
return
summary_df = pd.DataFrame(summary_rows)
utterance_df = pd.DataFrame(utterance_rows)
Path(args.summary_csv).parent.mkdir(parents=True, exist_ok=True)
summary_df.to_csv(args.summary_csv, index=False)
utterance_df.to_csv(args.utterance_csv, index=False)
write_correlations(summary_df, Path(args.correlation_csv))
log.info("Wrote %s", args.summary_csv)
log.info("Wrote %s", args.utterance_csv)
log.info("Wrote %s", args.correlation_csv)
if __name__ == "__main__":
main()