Skip to content

[Fix] attention: Fence SM120 attention K/V shared-memory reads before buffer reuse - #49044

Open
xupinjie wants to merge 1 commit into
sgl-project:mainfrom
xupinjie:pinjiex/cosmos3-overlap-accuracy
Open

xupinjie wants to merge 1 commit into
sgl-project:mainfrom
xupinjie:pinjiex/cosmos3-overlap-accuracy

Conversation

@xupinjie

@xupinjie xupinjie commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The SM120 CuTe attention kernel can produce nondeterministic outputs when running concurrently with Cosmos3 VAE decoding. The issue also reproduces with frozen Q/K/V tensors and an independent VAE workload, without DiT execution or KV-cache updates.

The experiments localize the issue to synchronization around K/V shared-memory buffer release and reuse. This PR adds ordering at those handoff points while preserving VAE overlap.

Modifications

  • Add cute.arch.fence_view_async_shared() and cute.arch.sync_warp() immediately before both K and V consumer_release() calls in FlashAttentionForwardSm120.compute_one_n_block.
  • Keep attention math, tile selection, pipeline stages, and dispatch unchanged.

Accuracy Tests

Concurrency diagnostics: H100 PCIe 80 GB, with the SM120 kernel explicitly selected and compiled for sm_90a. This is a diagnostic execution of the affected kernel, not H100's default FA3 path.

Frozen BF16 inputs: Q [1, 448, 32, 128], K/V [1, 2007, 8, 128]; noncausal, packed GQA, tile 64×64, one stage and one split. A separate CUDA stream runs VAE decoding.

Configuration Mismatches / 5,000 calls
Unpatched, before the ablations 43
Fence + warp sync before K release only 34
Fence + warp sync before V release only 8
This PR: fence + warp sync before both releases 0
Unpatched, restored after the ablations 34

A second delay seed produced 55/5,000 mismatches before the fix and 0/5,000 after it. Q/K/V remained bitwise unchanged. These counts describe the observed runs, not a fixed failure probability.

For Cosmos3-Nano-Sim-Bimanual, two fresh-process runs with the fix and VAE overlap produced bitwise-identical latents and decoded RGB frames across all 901 output frames. The fixed overlapped run also matched the unpatched serial run at the latent boundary; pixel equality across the two different VAE/output paths is not claimed.

Native SM120 checks: on RTX PRO 6000 Blackwell, all 30 operator cases passed bitwise comparison against the unpatched isolated result, including LSE where requested: nine BF16 cases from PR #32991's tests, 18 square-attention cases, and three Cosmos-shaped cases.

Speed Tests and Profiling

RTX PRO 6000 Blackwell Server Edition; AMD EPYC 9124, 16 allocated CPUs; PyTorch 2.13.0+cu130, CUDA 13.0, CUTLASS DSL 4.8.0.

Operator-only CUDA-event timing, with compilation and warmup excluded. Long-sequence cases use 32 calls per CUDA Graph replay and 30 interleaved measurement rounds. Both variants use the same inputs and dispatch; GPU clocks were not locked.

BF16, Q=KV=L, 32 query heads, head dimension 128. MHA uses 32 KV heads; GQA uses eight.

B L Attention Before (ms) After (ms) Latency change
1 8192 MHA, noncausal 3.689 3.698 +0.24%
1 8192 MHA, causal 1.980 1.989 +0.47%
1 8192 GQA, noncausal 3.979 3.991 +0.30%
1 8192 GQA, causal 2.005 1.996 −0.42%
4 6144 GQA, noncausal 9.350 9.376 +0.29%
4 6144 GQA, causal 4.911 4.929 +0.38%

Across all 18 square-attention cases (L=512/2048/6144/8192, plus B=4 at L=6144), measured changes ranged from −0.42% to +0.47%. Small negative values are not interpreted as speedups. The seven short PR-derived cases that execute the modified path added 0.08%–0.43%; three Cosmos cases added 0.32%–0.36%. Two HD256 test cases use a separate path and do not execute the new fences.

On the forced SM120-on-H100 diagnostic path, the three Cosmos cases added 5.9%–6.4%; these numbers do not describe the default H100 attention backend.

Nsight Systems concurrency check on H100: the unpatched run had 12 mismatches in 512 calls, with 433 calls overlapping VAE GPU kernels. The fixed run had zero mismatches, with all 512 calls overlapping VAE GPU kernels. Registers/thread (196), dynamic shared memory/CTA (50,176 bytes), and threads/CTA (160) were unchanged. The fix therefore retains actual GPU overlap. No E2E speedup is claimed.

Reproduction

The failure is timing-dependent: identical inputs do not fail on every invocation. A single isolated attention call is insufficient.

  1. Use the unpatched parent revision with PyTorch 2.13.0+cu130 and CUTLASS DSL 4.8.0. The verified concurrency reproducer used H100 with CUTE_DSL_ARCH=sm_90a set before importing CuTe, and explicitly selected the SM120 implementation using _arch=120. Running H100's default FA3 backend does not exercise this code.

  2. Load nvidia/Cosmos3-Nano-Sim-Bimanual. Use its examples/inference/sim_bimanual_unifiedv1_hf.jsonl entry agibot_mixed_028_bulk_seed2026, including the supplied prompt, initial image, and normalized action JSON. Set task_type="ti2v", action_mode="forward_dynamics", action_normalization="none", and format_prompt_as_json=False.

  3. Use seed 2026, guidance 1.0, 901 frames, 30 FPS, and four denoising steps per chunk. The tested request used width=832/height=480 and resolved to a 640×352 output. Disable component/layerwise offload, Torch compilation, and breakable CUDA graphs. Enable VAE overlap and use this pipeline configuration:

    {
      "overlap_vae_decode": true,
      "history_mode": "sliding",
      "kv_cache_inference_size": 64,
      "attention_sink_size": 8,
      "frame_sigma_schedules": [[1.0, 0.9375, 0.8333333333333334, 0.625]]
    }
  4. Run one unrelated warmup using agibot_mixed_007_bulk_seed2026 and the target prompt with its first white replaced by black; both prompts had 439 tokens in the tested tokenizer. In the inference worker, explicitly route the target noncausal attention calls through _flash_attn_fwd(..., _arch=120, num_splits=1, pack_gqa=True). Compare consecutive outputs for the same Q/K/V during overlap, and save the first mismatching call's inputs plus a reference computed after synchronization.

  5. To isolate the kernel, replay those frozen tensors with the loaded VAE using the loop below. The observed fixture had Q stride (2752512, 6144, 128, 1); preserve that stride when copying Q. Remove DiT execution and KV-cache updates from this replay. Repeat in a fresh process with this PR applied.

Frozen-input stress loop

This function runs inside the inference worker after model warmup. It requires the loaded BF16 VAE and frozen CUDA Q/K/V tensors captured in step 4; it is not a standalone model loader.

import random

import torch

from sglang.kernels.ops.attention.flash_attn.cute.interface import (
    _flash_attn_fwd,
)


@torch.no_grad()
def stress_attention(vae, q, k, v, calls=5000):
    out = torch.empty(q.shape, device=q.device, dtype=q.dtype)

    def attention():
        return _flash_attn_fwd(
            q, k, v, causal=False, num_splits=1, pack_gqa=True,
            tile_mn=(64, 64), _arch=120, out=out,
        )[0]

    torch.cuda.synchronize()
    reference = attention().clone()
    torch.cuda.synchronize()

    generator = torch.Generator(device=q.device).manual_seed(2026)
    z = torch.randn(
        (1, 48, 2, 22, 40), device=q.device,
        dtype=torch.bfloat16, generator=generator,
    )
    vae_stream = torch.cuda.Stream()
    vae_stream.wait_stream(torch.cuda.current_stream())
    vae.reset_causal_decode_state()
    jitter = random.Random(731)
    mismatches = 0

    for i in range(calls):
        if i % 16 == 0:
            with torch.cuda.stream(vae_stream):
                decoded = vae.causal_decode(z)
        torch.cuda._sleep(jitter.choice([0, 1000, 10000, 100000]))
        mismatches += not torch.equal(attention(), reference)

    torch.cuda.synchronize()
    vae.reset_causal_decode_state()
    return mismatches

Keep the background decode asynchronous: do not insert a device-wide synchronization before each attention call. Compare outputs before lossy video encoding. The validated patched runs had zero mismatches; exact unpatched counts depend on scheduling.

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #42349981568
Latest PR Test (Extra): ❌ Run #42349981555
Latest PR Test (AMD ROCm 10): ❌ Run #42349981599

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@claude claude Bot 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.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

triple-mu added a commit to triple-mu/sglang that referenced this pull request Nov 27, 2026
…is released

In the head_dim-256 QK / PV warp-group pipelines (contiguous K/V) and in the
transposed paged decode kernel, K and V stages are filled by TMA. The consumer
warps read a stage through the generic proxy, and the producer refills it
through the async proxy as soon as the stage is released. Nothing ordered those
reads before the refill, so a stage could be overwritten while a warp was still
reading it: under concurrent GPU work a small fraction of calls returned a
different output for the same inputs.

The four release sites of these two paths now run fence_view_async_shared()
and sync_warp() before consumer_release. This complements sgl-project#49044, which fences
the two sites in compute_one_n_block; neither path here runs those. The
split-PV sites are unchanged: they only run with a page table, where the
stages are loaded by cp.async and every consumer thread arrives itself.
triple-mu added a commit to triple-mu/sglang that referenced this pull request Dec 3, 2026
…is released

In the head_dim-256 QK / PV warp-group pipelines (contiguous K/V) and in the
transposed paged decode kernel, K and V stages are filled by TMA. The consumer
warps read a stage through the generic proxy, and the producer refills it
through the async proxy as soon as the stage is released. Nothing ordered those
reads before the refill, so a stage could be overwritten while a warp was still
reading it: under concurrent GPU work a small fraction of calls returned a
different output for the same inputs.

The four release sites of these two paths now run fence_view_async_shared()
and sync_warp() before consumer_release. This complements sgl-project#49044, which fences
the two sites in compute_one_n_block; neither path here runs those. The
split-PV sites are unchanged: they only run with a page table, where the
stages are loaded by cp.async and every consumer thread arrives itself.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant