OpenNMT-py developer on retainer: 20–30% phrase repetition rate on Spanish–English medical records — coverage penalty disabled after batch-size increase to 64 — beam search re-attends to already-decoded source segments — coverage_penalty=summary fix — 3 weeks — OpenNMT-py developer on monthly retainer
OpenNMT-py (OpenNMT/OpenNMT-py) 3.4.0 • Python 3.9; PyTorch Transformer NMT with beam search, length penalty, and optional coverage penalty • Spanish→English medical records translation service (2000 records/day, avg 650 tokens/document); BLEU target on held-out medical test set: ≥38; phrase repetition rate target: <3%; 20–30% of output documents contain repeated 3–8 word phrases (medical diagnoses, anatomical terms, procedure names repeated 2–4 times in the same output segment) — began after batch size increase from 8 to 64 to improve GPU throughput • developer investigates beam search scoring, coverage penalty configuration, attention distribution over source tokens, and translation quality on domain-specific medical terminology for 3 weeks • root cause: coverage_penalty=None (default in OpenNMT-py 3.4.0) — beam search maximizes cumulative log-probability without penalizing re-attention to already-decoded source tokens; high-confidence medical term translations (diagnoses, pharmaceutical names, anatomical terms) achieve high beam scores on re-generation; decoder can maximize score by repeating them without penalty • fix: set coverage_penalty=summary with beta=5.0 in onmt_translate beam search parameters; penalizes beam candidates whose cumulative attention on any source token exceeds saturation, suppressing re-translation of already-covered source segments • phrase repetition rate: 20–30% → under 2%; BLEU on medical test set: 34.1 → 41.8; 1.5h retainer engagement
Northfield OpenNMT Ltd. had built a Spanish→English medical records translation service for a network of regional hospital systems, processing 2000 patient encounter records per day averaging 650 tokens per document. The service used a domain-adapted OpenNMT-py 3.4.0 Transformer model fine-tuned on 2 million Spanish–English medical sentence pairs to produce clinician-readable English translations for cross-system record exchange. The pipeline ran on a 4×A100 GPU cluster and processed each daily batch in under 3 hours, meeting the overnight delivery window the hospital systems required. During the first four months of operation, translation quality was monitored by sampling 2% of output records daily for review by a bilingual medical coder, who reported repetition rates consistently below 3% across all document types. After the team doubled GPU throughput by increasing batch_size from 8 to 64, the medical coder review began flagging an increase in documents containing repeated phrases: sentences where a diagnosis or anatomical term appeared two or three times within the same passage, making the translation read as though a formatting error had duplicated content. The repetition rate climbed to 20–30% across all document types. An OpenNMT-py retainer developer was engaged to identify whether the batch size change had altered translation behavior and to restore repetition rate to below 3%.
The developer’s approach was to isolate whether the repetition was introduced by the batch size change or was latent in the model and previously undetected. The developer ran the same 500-sentence held-out test set through the pipeline at batch_size=8 and batch_size=64, confirmed the same repetition pattern at both batch sizes, and established that the batch size change had coincided with a QA process change (more records reviewed per day at higher throughput) that surfaced a pre-existing quality issue. The core diagnosis was straightforward: the production onmt_translate command had no coverage_penalty parameter, leaving it at the OpenNMT-py 3.4.0 default of None. Without coverage penalty, the beam search decoder has no cost for re-attending to source tokens it has already translated. For medical text, this matters because the NMT model assigns very high attention and translation confidence to key diagnostic terms — conditions, drugs, anatomical structures — that are central to the clinical record. The beam can re-generate these terms at any position in the output without penalty, since doing so locally maximizes the cumulative log-probability. The developer ran grid search over coverage_penalty values (None, “wu”, “summary”) and beta values (1.0, 2.0, 5.0, 10.0) on the held-out test set, finding coverage_penalty=“summary” with beta=5.0 reduced repetition rate to under 2% while improving BLEU from 34.1 to 41.8.
The diagnostic code that confirmed the coverage penalty root cause and validated the fix:
# Northfield OpenNMT Ltd. — OpenNMT-py 3.4.0 translation repetition diagnostic
# Spanish→English medical records, 2000 records/day, avg 650 tokens/document
# Problem: coverage_penalty=None → beam search re-attends to already-decoded source tokens
# Fix: coverage_penalty=summary, beta=5.0
import subprocess, re, numpy as np
from pathlib import Path
MODEL = "models/opennmt_es_en_medical_v3.pt"
SRC = "test_medical_es.txt" # 500-sentence medical test set (Spanish)
REF = "test_medical_en.txt" # reference translations (English)
def run_onmt_translate(src: str, model: str, out: str,
beam_size: int = 5, batch_size: int = 64,
length_penalty: str = "wu", alpha: float = 0.6,
coverage_penalty: str = None, beta: float = 0.0) -> None:
cmd = [
"onmt_translate",
"-model", model,
"-src", src,
"-output", out,
f"-beam_size={beam_size}",
f"-batch_size={batch_size}",
f"-length_penalty={length_penalty}",
f"-alpha={alpha}",
]
if coverage_penalty:
cmd += [f"-coverage_penalty={coverage_penalty}", f"-beta={beta}"]
subprocess.run(cmd, check=True, capture_output=True)
def repetition_rate(hyp_path: str,
min_n: int = 3, max_n: int = 8) -> float:
"""Fraction of output sentences containing a repeated n-gram (n in [min_n, max_n])."""
lines = Path(hyp_path).read_text().splitlines()
n_rep = 0
for line in lines:
toks = line.lower().split()
found = False
for n in range(min_n, max_n + 1):
ngrams = [tuple(toks[i:i+n]) for i in range(len(toks) - n + 1)]
if len(ngrams) != len(set(ngrams)):
found = True
break
if found:
n_rep += 1
return n_rep / len(lines) if lines else float("nan")
def sacrebleu(hyp_path: str, ref_path: str) -> float:
result = subprocess.run(
["sacrebleu", ref_path, "-i", hyp_path, "-m", "bleu", "-b"],
capture_output=True, text=True, check=True
)
return float(result.stdout.strip())
# --- Baseline: no coverage penalty ---
run_onmt_translate(SRC, MODEL, "out_baseline.txt",
beam_size=5, batch_size=64,
length_penalty="wu", alpha=0.6,
coverage_penalty=None)
# --- Fix: coverage_penalty=summary, beta=5.0 ---
run_onmt_translate(SRC, MODEL, "out_fixed.txt",
beam_size=5, batch_size=64,
length_penalty="wu", alpha=0.6,
coverage_penalty="summary", beta=5.0)
r_base = repetition_rate("out_baseline.txt")
r_fixed = repetition_rate("out_fixed.txt")
b_base = sacrebleu("out_baseline.txt", REF)
b_fixed = sacrebleu("out_fixed.txt", REF)
print("OpenNMT-py 3.4.0 — medical translation repetition diagnostic")
print("=" * 65)
print()
print(f" {'Configuration':<52} {'Rep.rate':<10} {'BLEU'}")
print("-" * 75)
print(f" {'No coverage_penalty (default) [regression]':<52}"
f" {r_base*100:5.1f}% {b_base:.1f}")
print(f" {'coverage_penalty=summary, beta=5.0 [fix]':<52}"
f" {r_fixed*100:5.1f}% {b_fixed:.1f}")
print()
print("Root cause: coverage_penalty=None → beam has no cost for re-attending")
print(" High-confidence medical terms produce sharply peaked attention dists.")
print(" Beam can maximize score by re-generating key terms at any position")
print(" Batch-size increase surfaced pre-existing issue via expanded QA review")
print()
print("Fix: coverage_penalty=summary, beta=5.0")
print(" Cumulative coverage(j) = Σ_t attention_weight(j, t) tracks each source token")
print(" Beam score += β * Σ_j log(coverage(j) + ε) → penalizes re-attended tokens")
print(" Repetition rate: 20–30% → under 2%; BLEU: 34.1 → 41.8")
print()
print("Retainer engagement: 1.5h total")
print(" Triage: 0.25h — repetition isolated to domain-specific medical terms")
print(" Root cause: 0.50h — coverage_penalty=None confirmed; beam re-attention analysis")
print(" Fix: 0.50h — coverage_penalty=summary, beta=5.0 grid search + apply")
print(" Validate: 0.25h — BLEU 34.1 → 41.8; repetition rate 20–30% → under 2%")
Why beam search re-attends to source tokens without coverage penalty
OpenNMT-py beam search is a greedy-approximate search over the space of all possible target sequences, maintaining a fixed-size set of the highest-scoring candidate translations at each generation step. The score of a candidate is the cumulative sum of log-token-probabilities plus a length penalty applied at the end of generation. The decoder’s attention mechanism computes a soft alignment distribution over source tokens at each step, using the query vector from the decoder’s current hidden state and the key vectors from the encoder output. This attention distribution is stateless across generation steps: the decoder computes it fresh at each step from the current decoder state, with no memory of which source tokens it has already attended to. For general-domain text, this statelessness is not problematic because the decoder learns through training to produce coherent translations that do not revisit source content — the internal language model component of the NMT decoder naturally discourages repetition because repeated phrases are rare in the training data. For domain-specific text, particularly medical records, this assumption breaks down.
Medical records contain a high density of clinically critical terms — diagnoses (hypertension, diabetes mellitus, myocardial infarction), pharmaceutical names (metformin, lisinopril, atorvastatin), anatomical terms (ventricular, pulmonary, hepatic) — that the domain-adapted NMT model has learned to translate with very high confidence. These terms produce attention distributions that are sharply peaked over a small number of source tokens, and the decoder’s log-probability for the correct target translation is very high. Without coverage penalty, the beam search algorithm has no mechanism to track that it has already generated the translation for “hipertensión arterial” and that attending to the same source tokens again would constitute re-translation. The beam can legitimately maximize its cumulative score by re-generating these high-confidence translations at later positions in the output, particularly when the decoder state at those positions is not strongly constrained by context (long output sequences, complex source structure). Coverage penalty fixes this by making the beam score sensitive to the history of attention across all generation steps. The “summary” coverage penalty in OpenNMT-py 3.4.0 adds β × Σ_j log(coverage(j) + ε) to the beam score, where coverage(j) = Σ_t a_j^t accumulates the attention weight on source token j across all generation steps t. When coverage(j) already exceeds 1.0 (the source token has been fully “used”), additional attention on that token adds a large negative contribution, sharply discouraging the beam from re-attending to already-covered source segments.
Related retainer posts
- fairseq developer on retainer — fairseq (facebookresearch/fairseq) + wav2vec 2.0 large; Python 3.9; call center ASR 8000 calls/day; non-deterministic WER 9.1% ± 2.4% on identical audio input; LayerDrop active at inference after model.eval(); fix: model.encoder.layerdrop=0.0; WER variance → ±0.1% — 3 weeks
- CTranslate2 developer on retainer — CTranslate2; Python 3.9; production NMT inference; translation latency and throughput optimization; quantization and batching configuration; beam search parameter tuning — 3 weeks
- DeepSpeed developer on retainer — DeepSpeed; Python 3.9; large-model training throughput; ZeRO optimizer stages; mixed-precision training; gradient checkpointing configuration — 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →