flash-attn developer on retainer: padding_side=“right” with FlashAttention-2 — shorter sequences in batch attend to padding-token KV entries — quality score 2.8/5 vs 4.4/5 — $70,000 — 2 months
flash-attn 2.5.6; transformers 4.38.2; torch 2.2.0; Python 3.11; CUDA 12.2; A100 40GB; tokenizer.padding_side = “right” (default) + attn_implementation=“flash_attention_2” + model.generate() with batch_size=4; FlashAttention-2 requires left-padding for batched generation; shorter sequences in right-padded batch attend to padding-token KV cache entries during generation step; outputs garbled for all but the longest sequence; quality score 2.8/5 batched vs 4.4/5 single-sample; 3 weeks before discovery; fix: tokenizer.padding_side = “left” • Westfield FlashAttn Inference Ltd. (3-person; 2 months; 1.5h)
Westfield FlashAttn Inference Ltd. is a 3-person LLM inference API startup that fine-tuned Llama-2-7b-chat on 50,000 customer support dialogues across three training epochs. The model was deployed with attn_implementation=“flash_attention_2” to cut inference latency on their A100 40GB GPU — a standard choice that reduced first-token latency from 180ms to 110ms per request at sequence length 512. To improve throughput, the team batched 4 requests together using the HuggingFace generate() pipeline. Quality scores from human reviewers immediately showed something was wrong: batched inference scored 2.8 out of 5 while single-sample inference of the same prompts scored 4.4. Shorter prompts in the batch consistently produced garbled outputs — responses that repeated phrases, changed topic mid-sentence, or ignored the question entirely. The longest prompt in each batch was always answered correctly.
The team spent three weeks attributing the problem to their fine-tuning. They ran four additional fine-tuning experiments on different hyperparameter settings, all of which measured the same 2.8/5 quality in batched mode. Automated benchmarks using model(**inputs) to compute token-level perplexity showed no anomaly — perplexity was a consistent 11.2 across all fine-tuned checkpoints. The critical omission was that their automated benchmarks evaluated the model in forward-pass mode only, not in generation mode. The bug only manifests during model.generate(). The transformers documentation for flash_attention_2 includes a note that is easy to miss: “Flash Attention 2 currently supports batched generation with the left padding. This is important for the generation use case.” The team’s LlamaTokenizer defaults to padding_side=“right”.
# inference.py — Westfield FlashAttn Inference Ltd.
# flash-attn 2.5.6; transformers 4.38.2; torch 2.2.0; Python 3.11
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_id = "westfield/llama-2-7b-chat-support-v3"
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Bug: LlamaTokenizer default: tokenizer.padding_side == "right"
# This is correct for training (labels must align left) but
# WRONG for batched generation with flash_attention_2.
# print(tokenizer.padding_side) → "right"
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float16,
device_map="cuda",
attn_implementation="flash_attention_2", # requires left-padding for generate()
)
def run_batch(prompts: list[str]) -> list[str]:
inputs = tokenizer(
prompts,
return_tensors="pt",
padding=True, # pads shorter sequences to max length
truncation=True,
max_length=512,
).to("cuda")
# With right-padding, inputs["input_ids"] looks like:
# prompt_0 (len 480): [tok0, tok1, ..., tok479, PAD, PAD, ..., PAD] (32 PADs)
# prompt_1 (len 200): [tok0, tok1, ..., tok199, PAD, PAD, ..., PAD] (312 PADs)
# prompt_2 (len 350): [tok0, tok1, ..., tok349, PAD, PAD, ..., PAD] (162 PADs)
# prompt_3 (len 512): [tok0, tok1, ..., tok511] (longest — no PAD)
#
# flash_attention_2 path in transformers:
# - Builds cu_seqlens from attention_mask.sum(-1): [480, 200, 350, 512]
# - position_ids computed from attention_mask.long().cumsum(-1) - 1
# - For prompt_1 (len 200, right-padded): position IDs for real tokens = [0,1,...,199];
# position IDs for PAD tokens = [199,199,...,199] (clamped at real sequence end)
# - During generate(), the NEW generated token is placed at position max_seq_len=512
# - The KV cache for prompt_1 was written at positions [0,...,199]
# - The new token at position 512 attends to ALL KV cache positions [0,...,511]
# - Positions [200,...,511] contain KV entries from PAD token embeddings
# (zero-initialized or sinusoidal at those positions)
# - The new token for prompt_1 receives majority attention weight over 312 PAD-token
# KV entries — its next-token distribution is corrupted by padding representations
# - prompt_3 (len 512): no padding → KV cache positions [0,...,511] all real → correct
output_ids = model.generate(
**inputs,
max_new_tokens=256,
do_sample=False,
temperature=1.0,
)
# Decode only the generated tokens (after the input)
generated = output_ids[:, inputs["input_ids"].shape[1]:]
return tokenizer.batch_decode(generated, skip_special_tokens=True)
# Results — Westfield FlashAttn Inference Ltd. (batch_size=4, 500 queries/hour):
# prompt_3 (longest in batch, 512 tokens): quality 4.4/5 ✓
# prompt_0 (480 tokens, 32 PADs): quality 3.8/5 (minor degradation)
# prompt_2 (350 tokens, 162 PADs): quality 2.9/5 (significant degradation)
# prompt_1 (200 tokens, 312 PADs): quality 1.6/5 (severe — garbled output)
#
# Human reviewer notes on prompt_1 output:
# "The response starts addressing the question, then repeats 'I understand your concern'
# three times, then answers a completely different question about shipping policy.
# The user asked about a software integration issue."
#
# No exception raised. No warning in logs. Output has correct token count.
# batch_size=1 inference: all prompts score 4.4/5 — the problem is batch-only.
During the retainer triage, testing batch_size=2 with two prompts of identical length produced correct outputs (4.4/5), while batch_size=2 with prompts of different lengths reproduced the degradation. This isolated padding as the variable. The transformers documentation note was found in the FlashAttention-2 integration guide, confirming that padding_side=“left” is required specifically for batched generation. Automated perplexity benchmarks never triggered the issue because model(**inputs) in forward-pass mode does not use the KV generation cache — padding token positions do not affect the prompt encoding, only the generation step.
Fix: set tokenizer.padding_side = “left” for batched generation
# Fixed inference.py — Westfield FlashAttn Inference Ltd.
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_id = "westfield/llama-2-7b-chat-support-v3"
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Fix: set left-padding BEFORE batching for generation.
# Left-padding places PAD tokens BEFORE real tokens:
# prompt_1 (len 200): [PAD, PAD, ..., PAD, tok0, tok1, ..., tok199]
# Position IDs for real tokens: [312, 313, ..., 511]
# New generated token at position 512 attends to KV positions [312,...,511]
# All attended KV entries correspond to real tokens — correct.
tokenizer.padding_side = "left"
# Guard: fail fast if flash_attention_2 is used with wrong padding
assert tokenizer.padding_side == "left", (
"flash_attention_2 requires padding_side='left' for batched generation. "
"Single-sample inference (batch_size=1) is unaffected."
)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float16,
device_map="cuda",
attn_implementation="flash_attention_2",
)
def run_batch(prompts: list[str]) -> list[str]:
inputs = tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=512,
).to("cuda")
output_ids = model.generate(
**inputs,
max_new_tokens=256,
do_sample=False,
)
generated = output_ids[:, inputs["input_ids"].shape[1]:]
return tokenizer.batch_decode(generated, skip_special_tokens=True)
# Results after fix — Westfield FlashAttn Inference Ltd.:
# prompt_1 (200 tokens): quality 4.4/5 ✓ (was 1.6/5)
# prompt_2 (350 tokens): quality 4.4/5 ✓ (was 2.9/5)
# prompt_0 (480 tokens): quality 4.4/5 ✓ (was 3.8/5)
# prompt_3 (512 tokens): quality 4.4/5 ✓ (unchanged — no padding)
#
# Throughput: unchanged (batch_size=4 maintained)
# Latency: unchanged (left-padding adds no overhead)
# Quality: 2.8/5 → 4.4/5 for batched generation
# Note: padding_side does NOT need to be 'left' for:
# - Training (use 'right' so labels align correctly)
# - Forward-pass evaluation (model(**inputs) for perplexity)
# - Single-sample inference (batch_size=1, no padding applied)
#
# Only batched generation (model.generate() with batch_size > 1
# and variable-length inputs) requires left-padding with flash_attention_2.
#
# If using transformers pipeline():
# pipe = pipeline("text-generation", model=model, tokenizer=tokenizer,
# device_map="cuda")
# pipe.tokenizer.padding_side = "left" # set on the pipeline's tokenizer
#
# 3 engineers × 2 months × $11,667/month = $70,000
Related retainer posts
- accelerate developer on retainer — accelerate 0.27.2;
gather()returns 1,024 for 1,003-sample dataset; 21 duplicated padding samples; macro-F1 inflated 0.763→0.771; shipped below target; fix:gather_for_metrics(); 1.5h - pytorch-lightning developer on retainer — pytorch-lightning 2.1.3;
sync_dist=Falseonval_lossin DDP; rank-0 shard metric logged to ModelCheckpoint; test sensitivity 71.4% vs 76.8%; fix:sync_dist=True; 1.5h - bitsandbytes developer on retainer — bitsandbytes 0.42.0; NF4 model loaded with
device_map='cpu';model.to('cuda')re-quantizes already-quantized weights; doubly-quantized garbage; inference nonsense; 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 →