feat: add attn='auto' option (FA3 on Hopper, FA4 on Blackwell) (#3076)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s

* feat: add attn='auto' option that picks FA3 on Hopper and FA4 on Blackwell

Add an 'auto' option to the model.attn config field that resolves at runtime
based on GPU architecture: Flash Attention 3 on Hopper (SM90), Flash Attention
4 on Blackwell (SM100+), falling back to FA2 on older architectures. This
becomes the new default for model.attn.

The resolution happens early in setup_model (before any attention-related setup)
and is also called explicitly in the SFT train script before CP kernel patching,
since SFT sets up context parallelism before calling setup_model.

* fix: enforce impl constraint for attn='auto' resolving to FA3/FA4

- Config validator: reject attn='auto' with impl='hf' at config time
- Runtime check in get_model: reject FA3/FA4 when impl='auto' resolves to
  'hf' (for models without a custom implementation)
This commit is contained in:
samsja
2026-07-17 15:15:27 -07:00
committed by GitHub
parent 825e6ce98f
commit 3d2dbae5f7
4 changed files with 40 additions and 7 deletions
+1 -1
View File
@@ -112,7 +112,7 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
```toml
[trainer.model]
impl = "custom"
attn = "flash_attention_2" # or fa3 / fa4
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
@@ -18,7 +18,7 @@ from prime_rl.utils.config import BaseConfig
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4"]
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
@@ -153,8 +153,8 @@ class ModelConfig(BaseModelConfig):
seq_len: int = 2048
"""Sequence length the model is trained on."""
attn: AttnImplementation = "flash_attention_3"
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
attn: AttnImplementation = "auto"
"""Attention implementation. ``auto`` selects FA3 on Hopper (SM90) and FA4 on Blackwell (SM100+). With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
@@ -237,11 +237,11 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4"]:
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if (
self.cp > 1
and self.attn in ("flash_attention_3", "flash_attention_4")
and self.attn in ("flash_attention_3", "flash_attention_4", "auto")
and self.impl not in ("custom", "auto")
):
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
@@ -275,7 +275,8 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "flash_attention_4" and self.impl not in ("custom", "auto"):
# "auto" may resolve to FA4 on Blackwell, so apply the same impl constraint.
if self.attn in ("flash_attention_4", "auto") and self.impl not in ("custom", "auto"):
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
return self
+28
View File
@@ -616,6 +616,12 @@ def get_model(
else:
impl_to_use = config.impl
if config.attn in ("flash_attention_3", "flash_attention_4") and impl_to_use == "hf":
raise ValueError(
f"{config.attn} requires model.impl='custom' or 'auto' (resolved to 'custom'), "
f"but model.impl resolved to 'hf'. Set model.impl='custom' explicitly."
)
with device:
if impl_to_use == "custom" and custom_vlm_cls is not None:
model_cls = custom_vlm_cls
@@ -1128,11 +1134,33 @@ def _validate_flash_attn_4_installed() -> None:
)
def resolve_auto_attn(config: ModelConfig) -> None:
"""Resolve ``attn='auto'`` to a concrete flash attention implementation based on GPU architecture.
FA3 on Hopper (SM90), FA4 on Blackwell (SM100+). Falls back to FA3 on older architectures
where FA3 is available, otherwise FA2.
"""
if config.attn != "auto":
return
major, _ = torch.cuda.get_device_capability()
if major >= 10:
resolved = "flash_attention_4"
elif major >= 9:
resolved = "flash_attention_3"
else:
resolved = "flash_attention_2"
logger = get_logger()
logger.info(f"Auto-resolved attn='auto' to '{resolved}' (SM{major}x)")
config.attn = resolved
def setup_model(
config: ModelConfig,
parallel_dims: ParallelDims,
loading_from_checkpoint_later: bool = False,
) -> nn.Module:
resolve_auto_attn(config)
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
raise ValueError(
"Flash attention 3 is only supported if the flash_attn_3 package is installed. Install with `uv pip install 'flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper' --no-build-isolation`"
+4
View File
@@ -29,6 +29,7 @@ from prime_rl.trainer.model import (
get_load_balance_stats,
is_tt_moe_model,
setup_tokenizer,
resolve_auto_attn,
setup_model,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
@@ -106,6 +107,9 @@ def train(config: SFTConfig):
)
grad_accum_steps = total_micro_batches // micro_batches_per_step
# Resolve attn='auto' before CP setup so ring/ulysses patches use the correct kernel
resolve_auto_attn(config.model)
if parallel_dims.cp_enabled:
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
cp_group = parallel_dims.world_mesh["cp"].get_group()