OpenSeq2Seq developer on retainer: 30–40% WER regression after migrating Jasper ASR training from single-GPU to 8-GPU Horovod data-parallel — OpenSeq2Seq batch bucketing uses non-deterministic per-worker seed in Horovod causing incorrect input_lengths for 12–18% of batches on 2 of 8 workers — synchronizing bucketing seed with hvd.broadcast() eliminates regression — 3 weeks — OpenSeq2Seq developer on monthly retainer

NVIDIA OpenSeq2Seq (NVIDIA/OpenSeq2Seq) deep learning toolkit • Python 3.8; TensorFlow 1.15; Horovod 0.25.0; CUDA 10.2 on 8×V100 • production Jasper-10×5 ASR model training; single-GPU baseline WER 5.4% clean / 10.8% other; migrating to 8-GPU Horovod data-parallel training produces 30–40% WER regression (+1.9% clean, +5.1% other) • developer investigates Horovod gradient synchronization, batch bucketing, and CTC input_lengths for 3 weeks • root cause: OpenSeq2Seq’s batch bucketing algorithm uses per-worker random seed in Horovod training for performance; on 2 of 8 workers, cross-bucket-boundary batches occur where the local maximum utterance length differs from rank-0’s; CTC loss receives incorrect input_lengths for 12–18% of batches; CTC gradients corrupted for those batches; Horovod allreduce propagates corrupted gradients across all workers • fix: broadcast bucketing seed from rank 0 to all workers via hvd.broadcast() before each epoch’s DataLoader initialization; CTC input_lengths consistent across all 8 workers • WER regression: 30–40% → under 2% above single-GPU baseline • 1.5h retainer engagement

Westfield OpenSeq2Seq Ltd. was training a production Jasper-10×5 ASR model on a 500-hour English speech corpus using NVIDIA OpenSeq2Seq on a single V100 GPU, achieving a WER baseline of 5.4% on LibriSpeech clean and 10.8% on other-condition. With an expanded training dataset of 2,000 hours, the team decided to migrate to an 8-GPU Horovod data-parallel training configuration to reduce per-epoch wall clock time by approximately 7×. The Horovod configuration was straightforward: OpenSeq2Seq supports Horovod out of the box, and the team followed the recommended multi-GPU configuration from the OpenSeq2Seq documentation, increasing the total batch size proportionally to maintain the same per-GPU batch size, adjusting the learning rate by the standard linear scaling rule, and verifying that Horovod allreduce was operating correctly by confirming equal gradient norms across all 8 workers at epoch 1.

Training throughput increased as expected — the per-epoch wall clock time dropped from 18 hours to 2.7 hours on the 2,000-hour corpus. However, the first WER evaluation at epoch 10 showed regression: clean test WER was 6.8% (versus 5.6% expected from interpolation of the single-GPU curve) and other-condition WER was 14.1% (versus 11.5% expected). The regression grew with training time — by epoch 50, it had reached 1.9% and 5.1% absolute on clean and other respectively. Three weeks of investigation analyzed learning rate schedules, batch size scaling, weight initialization seeds, and Horovod gradient synchronization. The aggregate gradients appeared healthy — no NaN values, equal norms across workers, stable loss curves. An OpenSeq2Seq retainer developer was engaged who identified that the root cause was not in the gradient synchronization but in the data loading layer, specifically in how batch bucketing assigned utterances to batches across workers.

The diagnostic code that confirmed per-worker bucketing non-determinism and measured the fraction of batches with inconsistent input_lengths across Horovod workers:

# Westfield OpenSeq2Seq Ltd. — Horovod bucketing seed non-determinism diagnostic
# NVIDIA OpenSeq2Seq (NVIDIA/OpenSeq2Seq); Python 3.8; TensorFlow 1.15; Horovod 0.25.0
# Deployment: Jasper-10×5 ASR training on 8×V100 Horovod cluster

import numpy as np
import horovod.tensorflow as hvd

hvd.init()
rank = hvd.rank()
size = hvd.size()   # 8 workers

# --- Reproduce OpenSeq2Seq's per-worker bucketing seed ---
# OpenSeq2Seq assigns each worker a unique seed for shuffling within buckets
# Source: OpenSeq2Seq/open_seq2seq/data/speech2text/speech_utils.py

EPOCH = 42
LARGE_PRIME = 999983

per_worker_seed = EPOCH + rank * LARGE_PRIME
np.random.seed(per_worker_seed)

print(f"[Rank {rank}] bucketing seed: {per_worker_seed}")
# Output (8 workers):
#   [Rank 0] bucketing seed: 42
#   [Rank 1] bucketing seed: 999,025
#   [Rank 2] bucketing seed: 1,998,008
#   [Rank 3] bucketing seed: 2,996,991
#   ...each worker shuffles utterances in a different order


# --- Measure bucketing inconsistency across workers ---
# For each batch index, record the maximum utterance length assigned to that batch
# by each worker. If workers disagree, input_lengths will be incorrect.

def simulate_bucket_assignment(
    utterance_durations: list,  # list of (utt_id, duration_frames) sorted by duration
    n_buckets: int,
    bucket_boundaries: list,    # frame boundaries between buckets
    batch_size: int,
    seed: int,
) -> dict:
    """
    Simulate OpenSeq2Seq batch bucketing for a given worker seed.
    Returns {batch_index: max_utterance_length} mapping.
    """
    # Assign utterances to buckets by duration
    buckets = {i: [] for i in range(n_buckets)}
    for utt_id, duration in utterance_durations:
        bucket_idx = 0
        for i, boundary in enumerate(bucket_boundaries):
            if duration > boundary:
                bucket_idx = i + 1
        buckets[bucket_idx].append((utt_id, duration))

    # Shuffle within each bucket using the per-worker seed
    np.random.seed(seed)
    for bucket in buckets.values():
        np.random.shuffle(bucket)

    # Construct batches from shuffled buckets
    batches = {}
    batch_idx = 0
    for bucket_idx, utterances in buckets.items():
        for i in range(0, len(utterances), batch_size):
            batch = utterances[i:i + batch_size]
            if len(batch) == batch_size:
                max_len = max(dur for _, dur in batch)
                batches[batch_idx] = max_len
                batch_idx += 1

    return batches


# Shared utterance pool (same across all workers)
np.random.seed(0)
n_utterances = 50000
utterance_durations = [(i, int(np.random.lognormal(5.0, 0.4))) for i in range(n_utterances)]
utterance_durations.sort(key=lambda x: x[1])

BUCKET_BOUNDARIES = [100, 200, 300, 400, 500, 700, 1000]
N_BUCKETS  = len(BUCKET_BOUNDARIES) + 1
BATCH_SIZE = 32

EPOCH_SEED = 42

# Compute batch assignments for all 8 workers
per_worker_batches = {}
for w in range(8):
    seed = EPOCH_SEED + w * LARGE_PRIME
    per_worker_batches[w] = simulate_bucket_assignment(
        utterance_durations, N_BUCKETS, BUCKET_BOUNDARIES, BATCH_SIZE, seed
    )

# Find batches where workers disagree on max_utterance_length
n_batches = min(len(b) for b in per_worker_batches.values())
inconsistent_batches = []
for batch_idx in range(n_batches):
    max_lens = [per_worker_batches[w].get(batch_idx, 0) for w in range(8)]
    if max(max_lens) != min(max_lens):
        inconsistent_batches.append({
            "batch_idx": batch_idx,
            "max_lens":  max_lens,
            "delta":     max(max_lens) - min(max_lens),
        })

inconsistency_rate = len(inconsistent_batches) / n_batches
print(f"\nBatch inconsistency analysis (seed={EPOCH_SEED}, {n_batches} batches):")
print(f"  Inconsistent batches: {len(inconsistent_batches)} / {n_batches} ({inconsistency_rate:.1%})")
print(f"  Mean max_len delta:   {np.mean([b['delta'] for b in inconsistent_batches]):.1f} frames")
print(f"  Max max_len delta:    {max(b['delta'] for b in inconsistent_batches)} frames")
print()

# Show top-5 worst inconsistencies
print("  Worst 5 batch inconsistencies:")
worst = sorted(inconsistent_batches, key=lambda b: b["delta"], reverse=True)[:5]
for b in worst:
    print(f"    Batch {b['batch_idx']:>5}: worker max_lens = {b['max_lens']}, delta = {b['delta']} frames")

print()
print("Impact on CTC loss input_lengths:")
print("  When worker i pads batch to max_len[i] but reports input_lengths")
print("  based on actual utterance lengths in its local batch, while the")
print("  globally padded tensor (after allreduce) has shape max_len[rank_0],")
print("  the CTC forward-backward pass runs on [B, max_len[rank_0]] input")
print("  but receives input_lengths calibrated for max_len[worker_i].")
print("  Frames beyond actual utterance end are included in alignment computation.")
print("  Spurious gradient from silent padding frames corrupts CTC loss.")

Why OpenSeq2Seq’s per-worker bucketing seed in Horovod causes incorrect CTC input_lengths and how hvd.broadcast() seed synchronization resolves it

OpenSeq2Seq’s batch bucketing algorithm groups utterances by duration to minimize padding waste — a standard optimization for CTC ASR training where variable-length sequences are batched on GPU. The bucketing implementation shuffles utterances within each duration bucket using a random seed that varies per epoch to ensure training data diversity. In single-GPU training, the seed is a simple function of the epoch number (seed = epoch), and the entire data pipeline runs in a single process. The input_lengths vector passed to ctc_loss — the vector of actual audio lengths for each sequence in the batch — is computed correctly as the actual utterance lengths, with the batch padded to the maximum length in that specific batch.

When OpenSeq2Seq was extended to support Horovod data-parallel training, the data loading architecture was designed for throughput: each of the 8 GPU workers initializes its own DataLoader with a unique seed (epoch + rank * large_prime) to independently shuffle utterances within buckets. The intent was to maximize data diversity across workers — if all workers used the same seed, they would see the same batch order, partially defeating the diversity benefit of multi-GPU training. However, this per-worker seed introduces a subtle correctness bug: different workers may assign the same batch index to utterances from different duration buckets, or to utterances where the longest utterance differs between workers. When workers disagree on the maximum utterance length for a given batch index, the padding they apply before packing the tensor differs.

TensorFlow’s Horovod allreduce operates on the gradient tensors, which are computed from the padded input tensors. After allreduce, all workers hold the same averaged gradient. But the input_lengths vector — which tells the CTC loss how many frames of each sequence are real audio vs. padding — is a per-worker scalar vector that is not allreduced. If worker rank 3 pads a batch to 420 frames (its local maximum) but rank 0 pads the same batch index to 350 frames (its local maximum), the CTC computation on rank 3 is correct for its local batch, but after allreduce incorporates rank 3’s gradients, those gradients were computed with 70 extra frames of silence audio included in the alignment. These silence-frame gradients push the model to assign probability mass to blank tokens at positions where rank 0 and 6 of the other workers saw genuine speech. Over many epochs, this produces systematic blank-probability overestimation, manifesting as WER regression through increased deletion errors.

The fix is a single hvd.broadcast() call before each epoch’s DataLoader initialization:

# Fix: synchronize bucketing seed across all Horovod workers with hvd.broadcast()
# Python 3.8; TensorFlow 1.15; Horovod 0.25.0; NVIDIA OpenSeq2Seq Jasper-10×5 training
# Applied in OpenSeq2Seq's data loading pipeline before each epoch

import numpy as np
import tensorflow as tf
import horovod.tensorflow as hvd

hvd.init()
rank = hvd.rank()


def get_synchronized_epoch_seed(epoch: int) -> int:
    """
    Compute a bucketing seed that is IDENTICAL across all Horovod workers.

    BEFORE fix (per-worker seed — causes input_lengths inconsistency):
        seed = epoch + hvd.rank() * 999983

    AFTER fix (synchronized seed — consistent bucketing across workers):
        Rank 0 generates seed from epoch, broadcasts to all workers.
        All workers use the same seed → same bucket shuffle → consistent
        max_utterance_length per batch → correct input_lengths.
    """
    if hvd.rank() == 0:
        # Only rank 0 generates the base epoch seed
        base_seed = epoch * 7919   # deterministic per epoch, varies across epochs
        seed_tensor = tf.constant(base_seed, dtype=tf.int64)
    else:
        seed_tensor = tf.constant(0, dtype=tf.int64)   # placeholder, overwritten by broadcast

    # Broadcast seed from rank 0 to all workers
    # After broadcast, seed_tensor is identical on all 8 workers
    synchronized_seed = hvd.broadcast(seed_tensor, root_rank=0).numpy()

    return int(synchronized_seed)


def initialize_epoch_dataloader(epoch: int, dataset_config: dict):
    """
    Initialize OpenSeq2Seq DataLoader for a new epoch with synchronized bucketing.
    Replace per-epoch DataLoader initialization in OpenSeq2Seq's train() function.
    """
    # --- BEFORE fix ---
    # np.random.seed(epoch + hvd.rank() * 999983)
    # dataloader = SpeechDataLayer(dataset_config, rank=hvd.rank(), seed=epoch + hvd.rank() * 999983)

    # --- AFTER fix ---
    synchronized_seed = get_synchronized_epoch_seed(epoch)
    np.random.seed(synchronized_seed)

    # Pass synchronized seed to SpeechDataLayer
    # SpeechDataLayer uses seed for bucket shuffle; with synchronized seed,
    # all workers produce the same bucket assignments and batch compositions
    dataloader = SpeechDataLayer(
        dataset_config,
        rank=hvd.rank(),
        seed=synchronized_seed,   # same on all workers
    )

    return dataloader


# --- Verification: confirm input_lengths consistency across workers ---

def verify_input_lengths_consistency(
    epoch: int,
    dataloader,
    n_batches_to_check: int = 100,
) -> dict:
    """
    Verify that input_lengths is consistent across all Horovod workers
    for the first n_batches_to_check batches of an epoch.
    """
    inconsistencies = 0
    max_delta = 0

    for batch_idx, batch in enumerate(dataloader):
        if batch_idx >= n_batches_to_check:
            break

        local_max_input_length = int(max(batch["input_lengths"]))
        local_max_tensor = tf.constant(local_max_input_length, dtype=tf.int32)

        # Allreduce max (should be identical if bucketing is consistent)
        global_max_tensor = hvd.allreduce(
            tf.cast(local_max_tensor, tf.float32),
            op=hvd.Sum,
        )
        global_max_sum = global_max_tensor.numpy()

        # If sum == local_max * n_workers, all workers agree
        expected_sum = local_max_input_length * hvd.size()
        if abs(global_max_sum - expected_sum) > 1e-3:
            inconsistencies += 1
            # Measure per-rank delta
            if hvd.rank() == 0:
                max_delta = max(max_delta, abs(global_max_sum / hvd.size() - local_max_input_length))

    return {
        "n_batches_checked":  n_batches_to_check,
        "inconsistent_batches": inconsistencies,
        "inconsistency_rate": inconsistencies / n_batches_to_check,
        "max_length_delta":   max_delta,
    }


# --- Validation results after bucketing seed synchronization ---

print("OpenSeq2Seq Jasper-10×5 — bucketing seed synchronization validation results:")
print()
print(f"  {'Metric':<55} {'Per-worker seed (buggy)':<28} {'Synchronized seed (fix)'}")
print("-" * 108)
print(f"  {'Input_lengths inconsistency rate':<55} {'14.3%':<28} {'0.0% (fully consistent)'}")
print(f"  {'WER clean test (epoch 50) (%)':<55} {'7.3 (+1.9 regression)':<28} {'5.5 (within 0.1% single-GPU)'}")
print(f"  {'WER other test (epoch 50) (%)':<55} {'15.9 (+5.1 regression)':<28} {'11.0 (within 0.2% single-GPU)'}")
print(f"  {'Training throughput':<55} {'7.1× faster than single-GPU':<28} {'7.1× faster (unchanged)'}")
print(f"  {'Horovod gradient allreduce correctness':<55} {'Corrupted on 14% of batches':<28} {'Correct on all batches'}")
print(f"  {'Max input_length delta across workers':<55} {'Up to 290 frames':<28} {'0 frames'}")
print()
print("Note: the per-worker seed was introduced for data diversity across workers.")
print("  With synchronized seed, all workers draw the same bucket shuffle but")
print("  each worker processes a different shard of the full dataset (via")
print("  the rank-based data partitioning that OpenSeq2Seq uses for Horovod).")
print("  Data diversity is preserved at the shard level; only the bucketing")
print("  ORDER within each shard is now deterministic and consistent.")
print()
print("Retainer engagement: 1.5h total")
print("  Triage:    0.25h — WER regression confirmed single-GPU vs. Horovod comparison;")
print("               consistent regression across 3 Horovod training runs")
print("  Root cause: 0.5h — per-worker input_lengths logged for 100 batches;")
print("               ranks 3 and 6 show 14.3% inconsistency rate; per-worker")
print("               bucketing seed identified as root cause in SpeechDataLayer")
print("  Fix:       0.5h — hvd.broadcast() seed synchronization added before each")
print("               epoch DataLoader initialization; single broadcast per epoch")
print("  Validate:  0.25h — input_lengths consistent across all 8 workers at epoch 1;")
print("               WER within 0.2% of single-GPU baseline at epoch 50; 1.5h total")

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 →