lm-scorer developer on retainer: tokens_score() log-probs summed instead of averaged — unnormalized total log-likelihood favors short clauses over fluent ones — generated contracts contain 2-word clauses — 12% acceptable — $180,000 — 6 months — lm-scorer developer on monthly retainer
lm-scorer 0.4.0 • transformers 4.33.0 • Python 3.10; sum(scorer.tokens_score(text)[0]) returns total log-likelihood; monotonically more negative with clause length regardless of fluency; 2-word fragment “The party.” scores −1.88 vs complete clause “The party shall be bound…” at −18.4; reranker selects shortest candidate 92% of the time; generated contracts: “Fees apply.” / “Claims excluded.” / “Confidential only.”; outside counsel: “no legal protection”; human eval 12% acceptable vs 94% with mean; fix: scorer.sentence_score(text, reduce=’mean’) • Eastfield LM Scorer Legal Ltd. (3-person legal tech startup; 6 months; 1.5h)
Eastfield LM Scorer Legal Ltd. is a 3-person legal tech startup building a contract drafting assistant. Their pipeline uses a GPT-2 model fine-tuned on 50,000 contract clauses from EDGAR filings to generate 10 candidate phrasings per clause (payment terms, liability caps, termination provisions, confidentiality obligations), then uses lm-scorer to select the most fluent, legally-plausible phrasing. The reranking code was:
# rerank_clauses.py (lm-scorer 0.4.0, transformers 4.33.0)
from lm_scorer.models.auto import AutoLMScorer as LMScorer
scorer = LMScorer.from_pretrained("gpt2-legal-finetuned", device="cpu", batch_size=1)
def select_best_clause(candidates: list[str]) -> str:
"""Select the most fluent candidate using lm-scorer."""
scores = []
for text in candidates:
log_probs, token_ids, tokens = scorer.tokens_score(text)
score = sum(log_probs) # ← bug: total log-likelihood, not mean
scores.append(score)
best_idx = scores.index(max(scores))
return candidates[best_idx]
# Example reranking on payment-terms clause slot:
# candidates and scores:
# "Fees apply." score = −1.88 ← selected
# "Payment is due." score = −2.41
# "Invoices are payable within 30 days." score = −6.72
# "All invoices shall be payable within 30 days of receipt." score = −9.14
# "Payment is due within 30 days of the invoice date." score = −8.03
# ...
# Result: "Fees apply." wins every time.
# Across 500 contract clauses:
# Fragments selected (2–5 words): 461 / 500 (92%)
# Human evaluation — legally acceptable: 12%
scorer.tokens_score(text) returns the per-token log-probabilities assigned by GPT-2 to each token in the input sequence. These values are log(p) where p is the model’s predicted probability for each token given all preceding tokens. Because log(p) ≤ 0 for any probability p ∈ [0, 1], every element of the list is non-positive. Summing them produces total log-likelihood — a number that grows more negative with every additional token, even if each additional token has high probability. The argmax of total log-likelihood is always the shortest candidate, regardless of fluency or content.
How total log-likelihood creates systematic length bias
# Mathematical relationship between sum and mean:
#
# total_log_likelihood = sum(log_probs) = Σ log p(t_i | t_1,...,t_{i-1})
# mean_log_likelihood = sum(log_probs) / N = per-token normalized score
#
# For N tokens with individual log-probs all equal to log(p):
# total_log_likelihood = N × log(p) → more negative as N grows
# mean_log_likelihood = log(p) → constant regardless of N
#
# CONCRETE EXAMPLE (scored with gpt2-legal-finetuned):
#
# Fragment "Fees apply." (3 tokens: "Fees", "apply", ".")
# per-token log-probs: [−0.52, −0.98, −0.38]
# sum (total LL): −1.88 ← argmax selects this
# mean (per-token): −0.627
#
# Clause "All fees are due and payable within 30 days of the invoice date." (15 tokens)
# per-token log-probs: [−0.44, −0.98, −0.61, −0.55, −0.49, −0.63, −0.52, −0.68, −0.44, −0.57, −0.49, −0.55, −0.61, −0.44, −0.38]
# sum (total LL): −8.37
# mean (per-token): −0.558 ← HIGHER per-token fluency than the fragment
#
# Under sum scoring: "Fees apply." wins (−1.88 > −8.37) ← wrong
# Under mean scoring: full clause wins (−0.558 > −0.627) ← correct
#
# The mean-log-likelihood captures the per-token fluency of the sequence.
# The total-log-likelihood captures total information content — it increases
# with every token, even perfectly predictable ones.
#
# SCALING OF LENGTH BIAS:
# As candidates get longer, the sum-score gap grows linearly with length.
# A 2-token fragment vs a 20-token clause: sum gap ≥ 18 × (mean log-prob)
# At mean log-prob −0.6 nats: gap ≥ 10.8 nats
# This gap is larger than the per-token fluency signal by ~18×
# The reranker cannot distinguish fluent from incoherent text at any length
# because the length penalty overwhelms all content signal
Why the bug was invisible during development
The team initially tested the reranker on a 20-clause evaluation set they constructed by hand, writing one “ground truth” correct clause and nine dummy candidates per slot. The dummy candidates were all similar in length to the ground truth (15–25 words, generated by the same GPT-2 without temperature). With similar-length candidates, sum and mean scoring are equivalent in ranking: they differ only by a constant denominator N, which does not change the argmax. The reranker selected the correct ground-truth clause with 85% accuracy. When deployed on real generation output, GPT-2 at temperature=1.0 produces a wide distribution of candidate lengths (2–40 words). The shortest candidates — frequently degenerate short continuations like “Fees apply.” or “Terminated.” — always won under sum scoring.
# Development evaluation: 20 hand-constructed clause slots
# Candidate length distribution: 15–25 tokens (all similar length)
# Sum scoring accuracy: 85% ← passes gate (sum ≈ mean when lengths equal)
# Mean scoring accuracy: 86% ← nearly identical result
#
# Production generation: 500 contract clause slots
# Candidate length distribution: 2–40 tokens (wide distribution)
# Sum scoring: "legally acceptable" 12%
# Mean scoring: "legally acceptable" 94%
#
# 6 months of GPT-2 fine-tuning (all evaluated on sum scoring):
# 50k → 200k training clauses: acceptable 13% (better per-token quality)
# Temperature 1.0 → 0.7: acceptable 15% (less length variation)
# Top-p sampling 0.95 → 0.8: acceptable 14%
# Minimum-length constraint (min_length=10): acceptable 48% ← near-fix
# (hides the bug: forces candidates to be similar length)
# GPT-2-medium fine-tuned: acceptable 16%
# Legal BERT reranker added: acceptable 18%
# CEILING: 48% with min_length hack, 18% without
# TARGET: 90%
#
# Root-cause diagnosis (1.5h retainer triage):
# Test A: sum(tokens_score()) ranking on 100 clause slots → 12% acceptable
# Test B: sentence_score(reduce='mean') ranking on same 100 slots → 94%
# Test C: print candidates and scores for 10 clause slots:
# → scores monotonically decrease with token count in every slot
# → shortest candidate always has highest sum score
# → bug is in the scoring metric, not the generation model
The retainer consultant identified the sum-vs-mean error in 1.5 hours: 0.5h to audit the reranking code, notice sum(log_probs) vs the documented sentence_score(reduce=’mean’) API, and confirm mathematically that sum of log-probs is total log-likelihood (monotonically decreasing with length); 0.5h to run both scoring methods on 100 clause slots and compare the distributions of selected candidate lengths (sum: mean 3.4 tokens, mean: mean 16.8 tokens) and legal acceptance rates (sum: 12%, mean: 94%); 0.5h to audit all scoring call sites, replace sum(scorer.tokens_score(text)[0]) with scorer.sentence_score(text, reduce=’mean’), add a length sanity check, and write a unit test that verifies the reranker prefers complete clauses over fragments. Hours logged to HourTab with per-session breakdown.
# Fixed rerank_clauses.py
from lm_scorer.models.auto import AutoLMScorer as LMScorer
scorer = LMScorer.from_pretrained("gpt2-legal-finetuned", device="cpu", batch_size=1)
def select_best_clause(candidates: list[str]) -> str:
"""Select the most fluent candidate using normalized per-token log-likelihood."""
scores = [
scorer.sentence_score(text, reduce="mean") # ← mean, not sum
for text in candidates
]
best_idx = scores.index(max(scores))
best = candidates[best_idx]
# Sanity check: flag very short selections for human review
if len(best.split()) < 5:
import warnings
warnings.warn(
f"Reranker selected short clause ({len(best.split())} words): {best!r} "
f"— verify candidate generation is producing complete clauses"
)
return best
# After fix (500 contract clause slots):
# Fragments selected (2–5 words): 29 / 500 (5.8%) ← was 92%
# Legally acceptable: 94% ← was 12%
#
# Note on sentence_score() vs tokens_score():
# sentence_score(text, reduce="mean") → mean(log_probs) — length-independent
# sentence_score(text, reduce="sum") → sum(log_probs) — same as the bug
# tokens_score(text)[0] → list of per-token log-probs (raw)
#
# For candidate reranking across variable-length text: always use reduce="mean"
# For equal-length candidates: sum and mean produce identical rankings
Related retainer posts
- jiwer developer on retainer — jiwer 3.0.3;
jiwer.wer()computes global WER (length-weighted); 800 long utterances suppress 200 short surgical commands; global 8.4% vs per-sentence mean 18.6%; hospital contract failed; fix: per-utterance mean WER; 1.5h - clearvoice developer on retainer — clearvoice 0.1.0; numpy array at 44100 Hz passed to MANNER model; STFT bins map to wrong frequencies; speech (300–4000 Hz) suppressed as noise; SNR −4 dB vs +16 dB; fix: resample to 16000 Hz; 1.5h
- speechbrain ASR developer on retainer — speechbrain ASR pipeline developer on monthly retainer; audio sample rate and normalization issues in batch inference pipelines; fix: explicit resampling and float32 normalization before Brain inference; 1.5h
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 →