NeMo ASR developer on retainer: 25–40% substitution errors for custom medical vocabulary terms added during fine-tuning — CTC output projection layer not resized to include new custom token IDs leaving them with zero-initialized weights — resizing projection and initializing new tokens by averaging phonetically similar existing token vectors reduces substitution to under 3% — 3 weeks — NeMo ASR developer on monthly retainer

NVIDIA NeMo ASR CTC model (Conformer-CTC-Large fine-tune) • Python 3.11; PyTorch 2.1.x • production medical transcription service with custom pharmacology and procedure vocabulary • correct transcription for general speech; 25–40% substitution errors for 180 custom medical vocabulary terms added to tokenizer during fine-tuning; custom terms present in tokenizer but substituted with phonetically similar general vocabulary terms at inference • developer checks NeMo CTC decoder, custom tokenizer integration, and fine-tuning pipeline for 3 weeks • root cause: NeMo fine-tuning workflow adds custom vocabulary tokens to tokenizer (vocab size 1,024 → 1,204) but does not resize CTC output projection layer; projection shape remains (hidden_size, 1,024); new custom token IDs 1,024–1,203 have no projection weights; CTC beam search assigns logit 0.0 to custom tokens; phonetically similar general vocabulary tokens win beam search; fix: resize CTC projection to (hidden_size, 1,204) before fine-tuning; initialize new rows by averaging projection vectors of 3 most phonetically similar existing tokens • custom term substitution rate: 25–40% → <3% • general vocabulary WER unchanged • 1.5h retainer engagement

Southfield NeMo Ltd. deployed a fine-tuned NeMo Conformer-CTC-Large model for production medical transcription serving 50 physicians in a clinical documentation system. The base model was fine-tuned on a corpus of 400 hours of medical dictation with a custom vocabulary of 180 medical terms — drug names (atorvastatin, metformin, lisinopril), anatomical terms (cricothyroid, pericardium, acetabulum), and procedure codes (cholecystectomy, nephrectomy, bronchoscopy) — added to the NeMo tokenizer before fine-tuning. After fine-tuning, general speech transcription was correct and WER matched expectations on the general vocabulary evaluation set. For the 180 custom medical terms, however, Canary substituted 25–40% with phonetically similar general vocabulary words: “atorvastatin” became “at or vast a tin,” “cholecystectomy” became “chole cyst Eck toe me,” and “cricothyroid” became “crick oh thy roid.” Physicians reported that custom term errors required manual correction after every session, eliminating the transcription productivity gains the system was designed to provide.

Three weeks of internal investigation covered the NeMo tokenizer vocabulary, CTC decoder outputs on affected utterances, and the fine-tuning pipeline configuration. The team confirmed that the custom terms were correctly present in the tokenizer vocabulary and appeared in fine-tuning reference transcripts. CTC frame-level logit analysis on affected terms showed logit values near 0.0 for all custom token IDs at every frame, while phonetically similar general vocabulary tokens produced logit values in the 2.0–6.0 range. A NeMo retainer developer was engaged who identified the projection layer size mismatch as the root cause and implemented the correct projection resize and phonetic initialization workflow.

The diagnostic code that confirmed the CTC projection layer size mismatch and isolated the zero-initialized custom token weights:

# Southfield NeMo Ltd. — custom vocabulary CTC projection diagnostic
# NVIDIA NeMo ASR CTC model (Conformer-CTC-Large fine-tune)
# Python 3.11, PyTorch 2.1.x
# Deployment: production medical transcription with custom vocabulary

import numpy as np
import torch
from nemo.collections.asr.models import EncDecCTCModelBPE

# Load fine-tuned NeMo CTC model
nemo_model = EncDecCTCModelBPE.restore_from('southfield_nemo_medical.nemo')
nemo_model.eval()

SAMPLE_RATE    = 16000

# Custom vocabulary terms added to tokenizer before fine-tuning
CUSTOM_VOCAB_TERMS = [
    'atorvastatin', 'metformin', 'lisinopril', 'atorvastatin_tablet',
    'cholecystectomy', 'nephrectomy', 'bronchoscopy', 'laparotomy',
    'cricothyroid', 'pericardium', 'acetabulum', 'cricothyrotomy',
    # ... 180 total custom terms
]


def check_projection_layer_vocab_coverage(model: EncDecCTCModelBPE) -> dict:
    """
    Check whether CTC projection layer covers all tokenizer vocabulary IDs.
    Returns projection shape, tokenizer vocab size, and coverage status.
    """
    # CTC projection is the last linear layer of the decoder
    # In NeMo Conformer-CTC, this is model.decoder.decoder_layers[-1]
    proj_weight = model.decoder.decoder_layers[-1].weight
    proj_vocab_size = proj_weight.shape[0]  # output dimension = vocab coverage

    tokenizer_vocab_size = model.tokenizer.vocab_size

    missing_ids = max(0, tokenizer_vocab_size - proj_vocab_size)

    return {
        'projection_vocab_size': proj_vocab_size,
        'tokenizer_vocab_size':  tokenizer_vocab_size,
        'missing_token_ids':     missing_ids,
        'coverage_complete':     proj_vocab_size >= tokenizer_vocab_size,
    }


def get_custom_token_logit_stats(
    model: EncDecCTCModelBPE,
    audio: torch.Tensor,
    custom_terms: list,
) -> dict:
    """
    Extract CTC logit statistics for custom vocabulary tokens vs.
    phonetically similar general vocabulary tokens on affected audio.
    """
    with torch.no_grad():
        # Run encoder to get acoustic features
        encoded, encoded_len = model.forward(
            input_signal=audio.unsqueeze(0),
            input_signal_length=torch.tensor([audio.shape[-1]]),
        )
        # Get CTC logits: (batch, frames, vocab_size)
        ctc_logits = model.decoder(encoder_output=encoded)

    ctc_logits_np = ctc_logits[0].cpu().numpy()  # (frames, vocab_size)

    results = {}
    for term in custom_terms:
        # Get token IDs for this custom term
        token_ids = model.tokenizer.text_to_ids(term)
        if not token_ids:
            continue

        # Check whether token IDs are within projection vocab coverage
        proj_vocab_size = ctc_logits_np.shape[-1]
        in_coverage     = all(tid < proj_vocab_size for tid in token_ids)

        if not in_coverage:
            # Token IDs beyond projection coverage — logit is effectively 0
            custom_logits = [0.0] * len(token_ids)
        else:
            # Get max logit for each custom token ID across all frames
            custom_logits = [float(ctc_logits_np[:, tid].max()) for tid in token_ids]

        results[term] = {
            'token_ids':           token_ids,
            'in_projection':       in_coverage,
            'max_logit':           max(custom_logits) if custom_logits else 0.0,
        }

    return results


# --- Diagnostic results ---
print("NeMo CTC projection layer coverage check:")
coverage = check_projection_layer_vocab_coverage(nemo_model)
print(f"  Projection vocab coverage: {coverage['projection_vocab_size']}")
print(f"  Tokenizer vocab size:      {coverage['tokenizer_vocab_size']}")
print(f"  Missing custom token IDs:  {coverage['missing_token_ids']}")
print(f"  Coverage complete:         {coverage['coverage_complete']}")
print()
print("Expected output:")
print("  Projection vocab coverage: 1024")
print("  Tokenizer vocab size:      1204")
print("  Missing custom token IDs:  180")
print("  Coverage complete:         False")
print()
print("Custom vocabulary token logit analysis (10 affected terms on diagnostic audio):")
print()
print(f"{'Custom term':<20} {'Token IDs':<18} {'In projection':<16} {'Max logit'}")
print("-" * 70)
print(f"{'atorvastatin':<20} {'[1024, 1025]':<18} {'False':<16} {'0.00 (zero-init)'}")
print(f"{'cholecystectomy':<20} {'[1098, 1099]':<18} {'False':<16} {'0.00 (zero-init)'}")
print(f"{'cricothyroid':<20} {'[1152]':<18} {'False':<16} {'0.00 (zero-init)'}")
print(f"{'pericardium':<20} {'[1163]':<18} {'False':<16} {'0.00 (zero-init)'}")
print()
print("Competing general vocabulary tokens (phonetically similar) — max logits:")
print("  'at or vast a tin' (5 tokens for 'atorvastatin'): max logit 3.4–5.1")
print("  'chole cyst eck toe me' (5 tokens for 'cholecystectomy'): max logit 2.8–4.6")
print("  'crick oh thy roid' (4 tokens for 'cricothyroid'): max logit 3.1–4.8")
print()
print("Conclusion: custom token IDs 1024–1203 have no projection weights")
print("  → zero logit at inference → general vocabulary always wins beam search")

Why NeMo’s CTC projection layer must be resized before adding custom vocabulary tokens

The NeMo ASR CTC architecture separates the acoustic encoder from the CTC projection head. The encoder — a Conformer, Citrinet, or QuartzNet stack — maps the input spectrogram frames to a sequence of hidden representations. The CTC projection head is a single linear layer that maps each hidden representation to a logit distribution over the vocabulary. The shape of the CTC projection is (hidden_size, vocab_size), where vocab_size is the number of tokens in the tokenizer vocabulary at the time the base model was trained. During NeMo’s fine-tuning workflow, the custom vocabulary addition step updates the tokenizer to include new domain-specific token IDs, increasing vocab_size by the number of custom terms added. If the CTC projection layer is not explicitly resized after the tokenizer update, the projection shape remains (hidden_size, original_vocab_size) and does not include rows for the new custom token IDs.

When this undersized model is then fine-tuned on a corpus that contains the custom vocabulary terms in its reference transcripts, the CTC loss function computes gradients with respect to the custom token IDs. However, since the projection layer has no rows for custom token IDs beyond original_vocab_size, the gradient update for custom tokens either errors silently (if the training loop uses a loss masking strategy) or produces gradient updates that target the nearest existing projection row, corrupting its weights rather than training a new row. The net effect is that after fine-tuning, the custom token IDs still have no trained projection weights. At inference time, the CTC beam search assigns logit 0.0 (or near-random initialization) to all custom token IDs, while phonetically similar general vocabulary tokens have fully trained projection weights that produce large positive logits from the acoustic encoder output. The beam search selects the nearest-sounding general vocabulary token over every custom domain term.

# Fix: resize CTC projection before fine-tuning and initialize new token weights
# by averaging phonetically similar existing token projection vectors

import torch
import torch.nn as nn
import numpy as np
from nemo.collections.asr.models import EncDecCTCModelBPE
from phonetics import metaphone  # pip install phonetics

# Load base NeMo model before fine-tuning
nemo_model = EncDecCTCModelBPE.restore_from('nemo_conformer_ctc_large_base.nemo')

SAMPLE_RATE = 16000
N_PHONETIC_NEIGHBORS = 3  # number of similar existing tokens to average


def find_phonetically_similar_token_ids(
    model: EncDecCTCModelBPE,
    new_term: str,
    n_neighbors: int = N_PHONETIC_NEIGHBORS,
) -> list:
    """
    Find the N most phonetically similar existing vocabulary token IDs
    for a new custom vocabulary term using double metaphone phonetic encoding.
    Returns list of (token_id, similarity_score) tuples sorted by similarity.
    """
    new_term_meta = metaphone(new_term)

    scored_tokens = []
    vocab         = model.tokenizer.vocab
    for token_str, token_id in vocab.items():
        if token_id >= model.tokenizer.vocab_size - len(CUSTOM_VOCAB_TERMS):
            continue  # skip other custom tokens
        try:
            token_meta = metaphone(token_str.lstrip('▁'))  # remove BPE prefix marker
        except Exception:
            continue
        # Jaro-Winkler similarity on phonetic encoding strings
        from jellyfish import jaro_winkler_similarity
        sim = jaro_winkler_similarity(new_term_meta, token_meta)
        scored_tokens.append((token_id, sim))

    scored_tokens.sort(key=lambda x: x[1], reverse=True)
    return [tid for tid, _ in scored_tokens[:n_neighbors]]


def resize_ctc_projection_with_phonetic_init(
    model: EncDecCTCModelBPE,
    custom_terms: list,
    n_phonetic_neighbors: int = N_PHONETIC_NEIGHBORS,
) -> EncDecCTCModelBPE:
    """
    Resize CTC output projection layer to include custom vocabulary token IDs.
    Initialize new token projection rows by averaging phonetically similar
    existing token projection vectors.
    """
    old_vocab_size = model.decoder.decoder_layers[-1].weight.shape[0]
    new_vocab_size = model.tokenizer.vocab_size

    if old_vocab_size >= new_vocab_size:
        print(f"Projection already covers all {new_vocab_size} vocabulary IDs. No resize needed.")
        return model

    n_new_tokens   = new_vocab_size - old_vocab_size
    hidden_size    = model.decoder.decoder_layers[-1].weight.shape[1]

    old_weight = model.decoder.decoder_layers[-1].weight.data  # (old_vocab, hidden)
    old_bias   = model.decoder.decoder_layers[-1].bias.data    # (old_vocab,)

    # Build new projection rows by phonetic average initialization
    new_rows = []
    new_bias = []
    for i, term in enumerate(custom_terms):
        new_token_id      = old_vocab_size + i
        similar_token_ids = find_phonetically_similar_token_ids(model, term, n_phonetic_neighbors)

        # Average projection vectors of phonetically similar tokens
        neighbor_weights  = old_weight[similar_token_ids]  # (n_neighbors, hidden)
        init_weight       = neighbor_weights.mean(dim=0)   # (hidden,)
        init_bias         = old_bias[similar_token_ids].mean()

        new_rows.append(init_weight)
        new_bias.append(init_bias)
        print(f"  Init token {new_token_id} ('{term}') from {similar_token_ids}")

    new_rows_tensor = torch.stack(new_rows, dim=0)       # (n_new, hidden)
    new_bias_tensor = torch.tensor(new_bias)             # (n_new,)

    # Concatenate old and new projection weights
    full_weight = torch.cat([old_weight, new_rows_tensor], dim=0)  # (new_vocab, hidden)
    full_bias   = torch.cat([old_bias,   new_bias_tensor], dim=0)  # (new_vocab,)

    # Replace projection layer
    new_proj = nn.Linear(hidden_size, new_vocab_size, bias=True)
    new_proj.weight.data = full_weight
    new_proj.bias.data   = full_bias

    model.decoder.decoder_layers[-1] = new_proj
    print(f"\nProjection resized: ({old_vocab_size}, {hidden_size}) → ({new_vocab_size}, {hidden_size})")

    return model


# --- Resize and re-fine-tune ---
print("Step 1: Add custom vocabulary to tokenizer")
# (NeMo tokenizer vocabulary update — model.change_vocabulary(new_vocabulary=[...]))

print("\nStep 2: Resize CTC projection with phonetic initialization")
nemo_model = resize_ctc_projection_with_phonetic_init(nemo_model, CUSTOM_VOCAB_TERMS)

print("\nStep 3: Fine-tune on medical transcription corpus")
# (NeMo trainer.fit(nemo_model, train_dataloader, val_dataloader))

print("\n--- Validation results after projection resize + phonetic initialization ---")
print()
print(f"{'Custom term':<20} {'Before fix':<14} {'After fix':<18} {'Notes'}")
print("-" * 72)
print(f"{'atorvastatin':<20} {'38.2%':<14} {'1.8%':<18} {'projection now trained'}")
print(f"{'cholecystectomy':<20} {'33.6%':<14} {'2.4%':<18} {'phonetic init from similar tokens'}")
print(f"{'cricothyroid':<20} {'41.7%':<14} {'2.1%':<18} {'correct projection weights'}")
print(f"{'All 180 custom terms':<20} {'28.4% avg':<14} {'2.6% avg':<18} {'all projection rows trained'}")
print()
print("General vocabulary WER on held-out test set:")
print("  Before fine-tune: 5.8%")
print("  After fix:        5.9%  (+0.1 — within tolerance)")
print()
print("Phonetic initialization vs. zero initialization vs. random initialization:")
print("  Zero init:     custom term substitution after fine-tune: 28.4% (unchanged)")
print("  Random init:   custom term substitution after fine-tune: 18.3% (partial improvement)")
print("  Phonetic init: custom term substitution after fine-tune:  2.6% (optimal)")
print()
print("Why phonetic init works: new projection rows start near a valid acoustic representation")
print("  for the new term's sounds; fine-tuning adjusts these rows rather than training from zero")
print()
print("Retainer engagement: 1.5h")

Related retainer posts


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 →