본문으로 건너뛰기

[sglang] Triton 커널의 정수 특수화를 끄면 요청 경로 재컴파일이 사라진다: MiniMax-H3 VSA-H3·VAE 사례

PR 링크: sgl-project/sglang#52224 상태: Merged | 변경: +182 / -4

들어가며

Triton 커널은 처음 호출될 때 JIT 컴파일되고, 이후에는 specialization key가 같으면 캐시된 바이너리를 재사용합니다. 문제는 이 key에 tl.constexpr 인자의 값뿐 아니라, 일반 정수 인자의 16으로 나누어떨어지는지 여부(divisibility)와 포인터 인자의 16-byte alignment까지 포함된다는 점입니다. Triton은 이 정보로 vectorized load/store 같은 최적화를 하지만, 그 대가로 값의 성질이 바뀔 때마다 새 variant를 컴파일합니다.

sglang의 MiniMax-H3 diffusion 경로에서는 이 정수들이 요청의 shape(프롬프트 길이, 화면 비율, 영상 길이)를 따라 움직였습니다. 그 결과 서버 warm-up이 끝난 뒤에도, 새로운 프롬프트 길이·캔버스·duration으로 들어온 첫 요청이 서빙 도중에 커널을 컴파일하게 됩니다. 문제가 된 커널은 네 개입니다.

  • VSA-H3 _topk_lists_kernel: video/prefix tile 수, 4개의 list stride, 출력 행의 alignment
  • VSA-H3 _untile_kernel: used, N_TILES의 16 divisibility
  • VSA-H3 _pack_tiles_kernel: N_TILES의 16 divisibility
  • _fused_scaled_residual_add_exact_kernel (VAE decoder): numel이 tl.constexpr라서 tile 수마다 컴파일

이 PR은 이 네 커널이 shape에 상관없이 (거의) 하나의 variant만 쓰도록 바꿉니다.

코드 분석

1. scale_shift_triton.py: constexpr를 runtime 인자로

가장 심한 경우입니다. tl.constexpr는 값 자체가 key에 들어가므로, numel이 1 tile, 2 tiles, 3 tiles일 때 전부 다른 커널이 됩니다.

Before

    scale_ptr,
    numel: tl.constexpr,
    width: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,

After

    scale_ptr,
    # runtime, not constexpr: it follows the input shape (the H3 VAE decoder's
    # tile batch), and each new value compiled a variant on the request path.
    # A multiple of width, so it keeps width's divisibility class
    numel,
    width: tl.constexpr,

핵심은 주석의 마지막 줄입니다. numel은 항상 width(여전히 constexpr)의 배수입니다. 일반 정수 인자로 바뀌면 Triton은 divisibility만 key로 쓰는데, width가 고정이라면 numel % 16 여부도 사실상 고정되므로 하나의 variant가 모든 tile 수를 커버합니다. 즉 do_not_specialize조차 필요 없이 constexpr만 풀어도 충분했던 케이스입니다. 마스크 경계로만 쓰이는 값을 constexpr로 둘 이유가 없었던 것이죠.

2. vsa_h3_kernels.py: do_not_specialize로 divisibility 특수화 차단

_pack_tiles_kernel과 _untile_kernel은 정수 인자의 16 divisibility가 바뀔 때 재컴파일되었습니다.

Before

@triton.jit
def _pack_tiles_kernel(

After

# N_TILES follows the prompt length; specializing on its divisibility compiled
# a new variant on the request path. It only offsets the pooled rows, which are
# HEAD_DIM-aligned either way, so the vector accesses are unchanged. S_PAD is a
# whole number of tiles, so its specialization never changes.
@triton.jit(do_not_specialize=["N_TILES"])
def _pack_tiles_kernel(
@triton.jit(do_not_specialize=["used", "N_TILES"])
def _untile_kernel(

여기서 중요한 판단은 "이 특수화가 실제로 성능에 기여하는가"입니다. 이 커널들의 vector access는 HEAD_DIM 축을 따라 일어나고, N_TILES·used는 row mask의 경계나 row offset으로만 쓰입니다. row offset에 HEAD_DIM이 곱해지므로 주소는 어차피 정렬되어 있고, divisibility 힌트가 vectorization을 바꾸지 못합니다. 그래서 특수화를 꺼도 생성 코드의 연산은 동일하고, 재컴파일만 사라집니다. 또한 S_PAD처럼 항상 tile 단위인 값은 divisibility가 변하지 않으므로 그대로 둔 것도 세심한 부분입니다.

3. _topk_lists_kernel: stride와 포인터 alignment까지

Before

@triton.jit
def _topk_lists_kernel(
    mask_ptr,
    out_ptr,

After

@triton.jit(
    do_not_specialize=[
        "num_video_tiles",
        "prefix",
        "stride_mh",
        "stride_mr",
        "stride_oh",
        "stride_or",
    ],
    do_not_specialize_on_alignment=["out_ptr"],
)
def _topk_lists_kernel(

이 커널은 [H, n_tiles + 1, n_tiles] list에서 prefix 행부터 시작하는 slice를 out으로 받습니다. 따라서 prefix 값에 따라 포인터 자체의 alignment가 달라지고, stride도 n_tiles에 따라 변합니다. 정수 divisibility만 끄면 포인터 alignment 때문에 여전히 재컴파일되므로 do_not_specialize_on_alignment=["out_ptr"]가 함께 필요했습니다. 이 커널은 int32 tile index만 옮기므로 결과는 바뀌지 않습니다. 이제 variant를 고르는 것은 VIDEO_POW2(video tile 수의 다음 2의 거듭제곱) 하나뿐입니다. 이는 tl.arange 크기를 결정하는 진짜 constexpr이라 남겨두는 게 맞습니다.

4. 테스트: variant 수를 직접 센다

테스트 설계가 인상적입니다. 커널의 compile cache를 비운 뒤, 다양한 shape로 호출하고 cache 엔트리 수를 assert 합니다.

def _fresh_compile_cache(monkeypatch, kernel) -> dict:
    monkeypatch.setattr(kernel, "device_caches", defaultdict(kernel.create_binder))
    return kernel.device_caches[torch.cuda.current_device()][0]

정확성은 특수화된 원래 커널과 바이트 단위로 비교합니다. triton.jit(kernel.fn)으로 같은 함수를 기본 옵션으로 다시 감싸 "length-specialized" 기준을 만듭니다.

specialized = triton.jit(kernel.fn)
...
for jit in (kernel, specialized):
    with mock.patch.object(vsa_h3_kernels, "_untile_kernel", jit):
        vsa_h3_kernels.vsa_h3_untile(...)
...
assert _same_bytes(*results)
assert len(cache) == 2  # gate 유무 2 모드

(32, 2048), (32, 2047), (33, 2096), (33, 2100)처럼 16 divisibility 조합을 의도적으로 섞어, 특수화가 남아 있으면 실패하도록 만들었습니다.

왜 이게 좋은가

수치

단위 테스트 기준 variant 수:

test main PR
topk list (4 layouts) 3 1
untile (4조합 x 2모드) 8 2
pack tiles (2 x 2) 4 2
residual add (1,2,3,5 tiles) 4 1

실제 2x B300 서버(warm-up 후)에서 _fused_scaled_residual_add_exact_kernel은 서버별 3~5회 컴파일되던 것이 0회가 되었고, _untile_kernel/_pack_tiles_kernel도 0회가 되었습니다. VSA-H3 denoise에서 1:1 5 s 첫 요청은 2.260s → 1.861s로 줄었고, 16:9 두 번째 프롬프트 길이도 3.432s → 3.322s로 개선되었습니다. MP4 md5는 34개 요청 모두 main과 동일합니다. 작성자는 decode 쪽 개선은 run-to-run 편차 수준이라고 정직하게 밝히고 있습니다.

일반적 교훈

  1. shape를 따라 변하는 값은 tl.constexpr로 두지 마라. tl.arange/block 크기처럼 컴파일 타임에 꼭 필요한 값만 constexpr로.
  2. Triton의 암묵적 특수화(divisibility, alignment)를 의식하라. 정수와 포인터도 key에 들어갑니다. 해당 값이 마스크 경계나 offset으로만 쓰이고 vector access 축과 무관하다면 do_not_specialize는 사실상 공짜입니다.
  3. warm-up은 만능이 아니다. warm-up shape와 다른 요청이 오면 JIT 재컴파일이 tail latency로 드러납니다. 서빙 이후 cache 디렉터리에 쓰이는 파일을 기록하는 방식의 검증은 다른 프로젝트에도 그대로 적용할 만합니다.
  4. variant 수를 테스트로 고정하라. cache 크기를 assert 하면 이후 누군가 무심코 constexpr을 추가해도 회귀를 바로 잡을 수 있습니다.

참고 자료

  • triton.jit — do_not_specialize 등 JIT 옵션을 사용한 데코레이터 공식 문서
  • Triton Python API — Triton 커널 작성 API 문서
  • torch.Tensor.view — 테스트에서 바이트 비교(view(torch.uint8))에 사용
  • torch.equal — 결과 동일성 검증에 사용

⚠️ 알림: 이 분석은 AI가 실제 코드 diff를 기반으로 작성했습니다.

댓글

관련 포스트

PR Analysis 의 다른글