accelerate developer on retainer: gather() returns 1,024 entries for 1,003-sample dataset — 21 duplicate padding samples inflate macro-F1 0.763 to 0.771 — shipped below quality target — $75,000 — 3 months

accelerate 0.27.2; torch 2.2.0; transformers 4.38.0; Python 3.10; 4× A100 40GB; accelerator.gather(predictions) returns all 1,024 slots for 1,003-sample dataset; last batch padded with 21 duplicated front-of-dataset samples; majority-class examples correctly classified at >0.98 confidence; macro-F1 0.763 (true) reported as 0.771 (inflated); 0.771 exceeded 0.77 ship threshold; production macro-F1 measured at 0.763; fix: accelerator.gather_for_metrics(predictions) • Southfield Accelerate NLP Ltd. (3-person; 3 months; 1.5h)

Southfield Accelerate NLP Ltd. is a 3-person startup building a legal document classification API for e-discovery workflows at mid-market law firms. Their model, a fine-tuned DeBERTa-v3-base classifier, categorized documents into three privilege classes: non-responsive, responsive, and privileged. The model was fine-tuned using accelerate 0.27.2 across four A100 40GB GPUs. Evaluation used a fixed test set of 1,003 documents — a carefully curated benchmark that mapped to realistic attorney review workload. The team’s internal product ship threshold was macro-F1 ≥ 0.77, agreed with the first enterprise client as the minimum for production use.

After six weeks of fine-tuning experiments, the evaluation pipeline consistently reported macro-F1 around 0.771–0.775 — just above the threshold. The team shipped to production. Within two weeks, the enterprise client ran their own independent evaluation on a held-out 400-document set and reported macro-F1 of 0.761. The discrepancy triggered a production quality review. The team re-ran their own evaluation multiple times and kept getting 0.771. The client kept getting 0.761. Three months passed while the team investigated model quality, data distribution shift, and evaluation methodology differences. The models themselves were fine. The evaluation pipeline had a silent one-line bug.

# eval_pipeline.py — Southfield Accelerate NLP Ltd.
# accelerate 0.27.2; torch 2.2.0; transformers 4.38.0; Python 3.10

from accelerate import Accelerator
from torch.utils.data import DataLoader
from evaluate import load as load_metric

accelerator = Accelerator()
f1_metric = load_metric("f1")

def evaluate_model(model, test_dataset, batch_size=32):
    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
    model, test_loader = accelerator.prepare(model, test_loader)

    model.eval()
    all_predictions = []
    all_labels = []

    for batch in test_loader:
        with torch.no_grad():
            outputs = model(**batch)
        predictions = outputs.logits.argmax(dim=-1)
        labels = batch["labels"]

        # Bug: accelerator.gather() returns tensors for ALL process slots,
        # including duplicated padding samples used to fill the last batch.
        #
        # Dataset: 1,003 documents, 3 classes (65% / 20% / 15%)
        # GPUs: 4; batch_size=32 per GPU; effective batch=128
        # Batches: ceil(1003 / 128) = 8; total slots = 8 × 128 = 1,024
        # Padding: 1,024 − 1,003 = 21 duplicated samples
        #
        # Accelerate DistributedSampler pads by duplicating the FIRST
        # 21 samples in the dataset. The dataset is sorted by document ID;
        # the first 21 documents are all short non-responsive (class 0)
        # filings with simple keywords — easy, high-confidence examples.
        #
        # accelerator.gather() returns ALL 1,024 gathered tensors.
        # The 21 extra samples at the end are the duplicates.
        # They all have label=0 and the model predicts 0 at ≥0.98 confidence.
        # → 21 extra "correct" class-0 predictions appended.
        gathered_preds = accelerator.gather(predictions)  # Bug: 1,024 entries
        gathered_labels = accelerator.gather(labels)      # Bug: 1,024 entries

        if accelerator.is_main_process:
            all_predictions.extend(gathered_preds.cpu().numpy())
            all_labels.extend(gathered_labels.cpu().numpy())

    if accelerator.is_main_process:
        # Computes macro-F1 over 1,024 entries, not 1,003.
        # 21 extra correct class-0 predictions → class-0 precision + recall
        # slightly inflated → class-0 F1 inflated → macro average inflated.
        result = f1_metric.compute(
            predictions=all_predictions,
            references=all_labels,
            average="macro",
        )
        # Reported macro-F1: 0.771
        # True macro-F1 (1,003 samples): 0.763
        # Inflation: +0.008 (0.8pp) — just enough to cross the 0.77 threshold.
        return result["f1"]

# Metric breakdown by class (1,024 samples including 21 duplicates):
#   class-0 (non-responsive): 672 total (651 real + 21 extra)
#     F1: 0.891 (inflated; true: 0.884)
#   class-1 (responsive):     204 total (204 real, no extras)
#     F1: 0.761 (unchanged)
#   class-2 (privileged):     148 total (148 real, no extras)
#     F1: 0.661 (unchanged)
#   macro average: (0.891 + 0.761 + 0.661) / 3 = 0.771 (inflated)
#
# True metric breakdown (1,003 real samples):
#   class-0 F1: 0.884; class-1 F1: 0.761; class-2 F1: 0.661
#   macro average: 0.763  ← below the 0.77 ship threshold

The discrepancy was found by printing the length of all_predictions after gathering: 1,024 entries for a 1,003-sample test set. accelerator.gather_for_metrics() had been added to accelerate precisely to prevent this. It strips the last num_padded_samples entries before returning, where num_padded_samples = num_processes * batch_size - len(dataset). The function was available in accelerate 0.21.0, six versions before the team’s 0.27.2. The evaluation loop never needed to change except for a single word.

Fix: replace gather() with gather_for_metrics() in evaluation loops

# Fixed eval_pipeline.py — Southfield Accelerate NLP Ltd.

def evaluate_model(model, test_dataset, batch_size=32):
    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
    model, test_loader = accelerator.prepare(model, test_loader)

    model.eval()
    all_predictions = []
    all_labels = []

    for batch in test_loader:
        with torch.no_grad():
            outputs = model(**batch)
        predictions = outputs.logits.argmax(dim=-1)
        labels = batch["labels"]

        # Fix: gather_for_metrics() strips the padding before returning.
        # Added in accelerate 0.21.0 specifically for this use case.
        # Returns exactly len(test_dataset) = 1,003 entries — no duplicates.
        gathered_preds = accelerator.gather_for_metrics(predictions)  # 1,003 entries
        gathered_labels = accelerator.gather_for_metrics(labels)      # 1,003 entries

        if accelerator.is_main_process:
            all_predictions.extend(gathered_preds.cpu().numpy())
            all_labels.extend(gathered_labels.cpu().numpy())

    if accelerator.is_main_process:
        result = f1_metric.compute(
            predictions=all_predictions,
            references=all_labels,
            average="macro",
        )
        # Correct macro-F1: 0.763 (now matches client's independent evaluation)
        return result["f1"]

# Results after fix — Southfield Accelerate NLP Ltd.:
#   Reported macro-F1 (gather):              0.771  (inflated)
#   Correct macro-F1 (gather_for_metrics):   0.763  (true)
#   Client independent evaluation:           0.761  (independent holdout)
#   Ship threshold: ≥0.77 → model was below threshold, not ready
#   After 2 more weeks of targeted fine-tuning with correct metric:
#     macro-F1: 0.779  (correctly above threshold, verified by client)
#
# If you are on accelerate < 0.21.0 and cannot upgrade, manual workaround:
#   # Gather all, then slice to actual dataset size on main process
#   gathered_preds = accelerator.gather(predictions)
#   gathered_labels = accelerator.gather(labels)
#   if accelerator.is_main_process:
#       # Slice to true dataset length before metrics computation
#       true_preds = gathered_preds[:len(test_dataset)]
#       true_labels = gathered_labels[:len(test_dataset)]
#   # Note: this only works correctly when batches are processed in order
#   # and padding is at the end. gather_for_metrics() is safer.
#
# Diagnostic to detect the problem:
#   After gathering, assert:
#     assert len(all_predictions) == len(test_dataset), (
#         f"gathered {len(all_predictions)} predictions "
#         f"for {len(test_dataset)}-sample dataset — "
#         f"use gather_for_metrics() instead of gather()"
#     )
#
# gather() vs gather_for_metrics() summary:
#   gather()              — all process slots, padding included
#                           use for: distributed tensor all_gather where
#                           you need every slot (e.g., retrieval index build)
#   gather_for_metrics()  — strips padding, returns exactly dataset_size entries
#                           use for: any end-to-end metric computation
#
# 3 engineers × 3 months × $8,333/month = $75,000

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 →