patch_qsa_sm121.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. """Patch SGLang's Qwen sparse-attention (QSA) varlen-decode path for SM121
  3. (DGX Spark / GB10).
  4. The stock `lmsysorg/sglang:qwen38flashnext` resolves QSA's packed varlen decode
  5. to flash-attn-4's CuTe-DSL kernels, which fail MLIR compilation on SM121
  6. (layout-congruence error). This injects an early-return that routes non-SM100
  7. devices to the Triton FlashDecoding-style fallback in `qsa_fa_fallback.py`
  8. (CUDA-graph-safe: cu_seqlens are read on-device, so graph replay works).
  9. Anchor-based, refuses on drift, idempotent (--check passes on pristine and on
  10. already-patched source). See the vllm-mod-patches skill.
  11. """
  12. import os
  13. import sys
  14. import sglang
  15. FILE = os.path.join(
  16. sglang.__path__[0], "srt/layers/attention/qwen_sparse_attn_backend.py"
  17. )
  18. # The dense-varlen resolver's first try block (FA2 preferred). Insert the
  19. # SM121 early-return directly before it.
  20. OLDER = " try:\n from flash_attn import flash_attn_varlen_func"
  21. NEWER = (
  22. " from sglang.srt.utils import is_sm100_supported\n"
  23. " if not is_sm100_supported():\n"
  24. " from sglang.srt.layers.attention.qsa_fa_fallback import triton_varlen_attn_func\n"
  25. " return triton_varlen_attn_func\n"
  26. + OLDER
  27. )
  28. def _consistent(src: str, old: str, new: str) -> bool:
  29. co, cn = src.count(old), src.count(new)
  30. if cn >= 1: # patched: new once, and any old sits only inside new
  31. return cn == 1 and co <= new.count(old)
  32. return co == 1 # pristine: old once
  33. def main() -> None:
  34. check = "--check" in sys.argv
  35. src = open(FILE).read()
  36. if check:
  37. if not _consistent(src, OLDER, NEWER):
  38. raise SystemExit(f"CHECK FAIL: {FILE} is neither pristine nor patched")
  39. print(f"check OK: {FILE} state is consistent")
  40. return
  41. if src.count(OLDER) != 1:
  42. raise SystemExit(
  43. f"refusing: {FILE} anchor matched {src.count(OLDER)}x; re-sync patch"
  44. )
  45. out = src.replace(OLDER, NEWER)
  46. assert out.count(NEWER) == 1
  47. open(FILE, "w").write(out)
  48. print(f"patched {FILE} for SM121")
  49. if __name__ == "__main__":
  50. main()