Skip to content

[core] support sage attention + FA2 through kernels - #12439

Merged
sayakpaul merged 19 commits into
mainfrom
sage-kernels
Nov 24, 2025
Merged

[core] support sage attention + FA2 through kernels#12439
sayakpaul merged 19 commits into
mainfrom
sage-kernels

Conversation

@sayakpaul

@sayakpaulsayakpaul commented Oct 6, 2025

Copy link
Copy Markdown
Member

What does this PR do?

Code to test (SAGE):

fromdiffusersimportDiffusionPipelineimporttorchrepo_id="black-forest-labs/FLUX.1-dev"pipe=DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to("cuda")
pipe.transformer.set_attention_backend("sage_hub")
image=pipe(
prompt="a dog sitting by the sea, waiting for its companion to come",
guidance_scale=3.5,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.manual_seed(0)
).images[0]
image.save("sage_flux.png")

Result:
image

FA2:

importtorchfromdiffusersimportFluxPipelinemodel_id="black-forest-labs/FLUX.1-dev"pipe=FluxPipeline.from_pretrained(
model_id, torch_dtype=torch.bfloat16
).to("cuda")
pipe.transformer.set_attention_backend("flash_hub")
pipe.transformer.compile(fullgraph=True)
prompt="A cat holding a sign that says 'hello world'"withtorch._dynamo.config.patch(error_on_recompile=True):
image=pipe(
prompt, num_inference_steps=28, guidance_scale=4.0, generator=torch.manual_seed(0)
).images[0]
image.save("output.png")

Notes

  1. It would be nice to get torch.compile support when using sage attention like we have for flash and flash 3. Currently, this fails.
Code to test
fromdiffusersimportDiffusionPipelineimporttorchrepo_id="black-forest-labs/FLUX.1-dev"pipe=DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to("cuda")
pipe.transformer.set_attention_backend("sage_hub")
pipe.transformer.compile_repeated_blocks(fullgraph=True)
with (
torch._inductor.utils.fresh_inductor_cache(),
torch._dynamo.config.patch(error_on_recompile=True),
):
image=pipe(
prompt="a dog sitting by the sea, waiting for its companion to come",
guidance_scale=3.5,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.manual_seed(0)
).images[0]
image.save("sage_flux.png")

Error: https://pastebin.com/3HS6HNzR

  1. We have other sageattn variants (see here), which would be cool to expose from the Hub kernel.

Cc: @MekkCyber

@sayakpaulsayakpaul added the performance Anything related to performance improvements, profiling and benchmarking label Oct 6, 2025
@sayakpaul
sayakpaul requested a review from DN6October 6, 2025 05:48
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@MekkCyberMekkCyber left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool ! I will try to look into the torch compile compatibility, but for the other variants, they are the same as sageattn, what i mean is sageattn is just a wrapper that dispatches to the correct kernel depending on the hardware used : https://github.com/thu-ml/SageAttention/blob/main/sageattention/core.py#L140

@sayakpaul

Copy link
Copy Markdown
MemberAuthor

they are the same as sageattn, what i mean is sageattn is just a wrapper that dispatches to the correct kernel depending on the hardware used :

So, you mean we shouldn't have to have different dispatched functions like this?

_SAGE_QK_INT8_PV_FP8_CUDA="_sage_qk_int8_pv_fp8_cuda"

@MekkCyber

Copy link
Copy Markdown

Yes I think we don't need that because it depends on the hardware. For example if a user chooses : _sage_qk_int8_pv_fp8_cuda on A100 (8.0) it will fail, because this function is only supported and compiled for 8.9 gpus

@sayakpaul
sayakpaul marked this pull request as draft October 7, 2025 13:38
Comment on lines -165 to -167
_SAGE_ATTENTION_PV_ACCUM_DTYPE = Literal["fp32", "fp32+fp32"]
_SAGE_ATTENTION_QK_QUANT_GRAN = Literal["per_thread", "per_warp"]
_SAGE_ATTENTION_QUANTIZATION_BACKEND = Literal["cuda", "triton"]

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see their usage, hence removed.

@woct0rdho

woct0rdho commented Oct 10, 2025

Copy link
Copy Markdown

FYI, I've ported SageAttention to Python stable ABI (ABI3) and libtorch stable ABI, which should simplify building for HF Kernels:
woct0rdho/SageAttention@main...abi3_stable

There are also some refactors in my main branch to simplify building. If someone can maintain the build system, then I no longer need to maintain my repo :)

@sayakpaul
sayakpaul marked this pull request as ready for review October 13, 2025 10:27
@sayakpaul

Copy link
Copy Markdown
MemberAuthor

This PR is ready to be reviewed now. As discussed with @MekkCyber over DMs, we're disabling torch.compile support now as the compile branch leads to garbage outputs.

In order for us to support it with torch.compile, some kind of lightweight dispatcher might be needed. d344134 added support for that but I have removed it for now for the above-mentioned purpos. Those changes are still safe in sage-kernels-dispatch branch.

I think we should be good with the PR.

Cc: @MekkCyber@DN6

Comment threadsrc/diffusers/models/attention_dispatch.py Outdated
@sayakpaulsayakpaul mentioned this pull request Oct 27, 2025
6 tasks
@sayakpaulsayakpaul changed the title [core] support sage attention through kernels[core] support sage attention + FA2 through kernelsNov 20, 2025
@sayakpaul
sayakpaul requested a review from DN6November 20, 2025 06:54
@sayakpaul

Copy link
Copy Markdown
MemberAuthor

@DN6 it should be up for another review. I have updated the test suite and ensured that they pass successfully as well. PTAL.

@sayakpaulsayakpaul mentioned this pull request Nov 22, 2025
4 tasks
DN6
DN6 approved these changes Nov 24, 2025

@DN6DN6 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to merge. But we need to remove the parallel config check and use supports_context_parallel=False

return_lse: bool = False,
_parallel_config: Optional["ParallelConfig"] = None,
) -> torch.Tensor:
if _parallel_config:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use:

@_AttentionBackendRegistry.register(AttentionBackendName.FLASH_HUB,constraints=[_check_device, _check_qkv_dtype_bf16_or_fp16, _check_shape],supports_context_parallel=False,)

supports_context_parallel=True,

It will raise an error when trying to enable parallelism with this backend. This check isn't needed.

@sayakpaul
sayakpaul merged commit d176f61 into mainNov 24, 2025
15 checks passed
@sayakpaul
sayakpaul deleted the sage-kernels branch November 24, 2025 11:30
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performanceAnything related to performance improvements, profiling and benchmarking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants

@sayakpaul@HuggingFaceDocBuilderDev@MekkCyber@woct0rdho@DN6