What this thread does
Do first: Upgrade Transformers to v5.0.0, whose release includes the common-dtype Flash Attention correction.
Symptom
RuntimeError: query and key must have the same dtype appears during generation with Flash Attention after training. antonioalegria reported it with Transformers 4.38.2. Other affected reporters in the same thread include imirzadeh, ylacombe and edchengg; their examples also discuss cache values becoming fp32.
Cause
Maintainer gante explains that fp16=True enables autocast during training without permanently changing model weights to fp16; inference can therefore see fp32. zucchini-nlp separately identified Trainer/Accelerate casting cached outputs to fp32. The closing maintainer comment points to the shared target-dtype path from merged PR #41605, which brings query/key/value to a common dtype.
Fix
1. Upgrade to v5.0.0, whose release notes include PR #41605 (release). 2. For the original fp32-loaded-model case, the maintainer's example explicitly passes attn_implementation="flash_attention_2" and torch_dtype=torch.float16 to AutoModelForCausalLM.from_pretrained() (comment).
Fixed in
The correction is included in v5.0.0 (released 2026-01-26). PR #41605 merged 2025-10-16. If you cannot upgrade: gante states that the fp32-trained model can be manually cast to FP16 or reloaded in FP16; this addresses the original model-loading case, rather than every cache-related variant.
If it still fails
- Earlier comments distinguish the fp32-loaded-model case from Trainer cache upcasting; a load-time dtype choice is not presented as a universal cache fix.
- PR #41605 says the kosmos2 test still has other failure causes.
- The closing comment requests a new reproducer for a recurrence on v5.
Not for: the vLLM or llama.cpp runtimes, or general Transformers v4-to-v5 loading and tokenizer migration; see transformers-v4-to-v5-migrate-loading-and-tokenizers.
Sources
- Model trained with Flash Attention 2.0 raises "RuntimeError: query and key must have the same dtype" when generating, antonioalegria, opened 2024-04-03; closed as completed on 2026-10-20: "It should generate without any problems."
- Fix fp32_ln for various models, remi-or, merged 2025-10-16 (closed).
- v5.0.0, published 2026-01-26.
Checked
2026-11-24; read the issue and comments API records, PR API record and release API record, release list and release comparison API records; no command was run.
Started from a post by @antonioalegria, packaged by the editor. Original post