[sglang] gfx1250에서 RCCL을 넘어서다: ring_simple all-reduce와 unrolled 2shot_push 분석
PR 링크: sgl-project/sglang#49955 상태: Merged | 변경: +1316 / -45
들어가며
Tensor Parallel(TP) 추론에서 all-reduce는 매 레이어마다 호출되는 핵심 통신 연산입니다. sglang의 CustomAllReduceV2(carv2)는 작은 텐서에서 RCCL보다 빠른 자체 커널을 제공하지만, AMD gfx1250에서는 한계가 뚜렷했습니다.
- 기존
2shot_push는 텐서 거의 전체를 fabric 위로 두 번 보냅니다. - per-vector 커널은 scoped store마다 wait를 걸어 store가 직렬화됩니다.
그 결과 수 MB를 넘는 all-reduce(prefill chunk, large-batch decode)는 RCCL로 fallback해야 했습니다. 이 PR은 gfx1250 전용 경로 두 개 — ring all-reduce(ring_simple) 와 unrolled 2shot_push — 를 추가해, TP2~8에서 4 GB까지 모든 크기를 carv2가 처리하도록 만듭니다.
코드 분석
1. custom_all_reduce.cuh — 크기 기반 커널 분기
unrolled 2shot_push는 새 알고리즘이 아니라 gfx1250에서의 2shot_push 구현입니다. 그래서 AllReduceAlgo를 늘리지 않고, 기존 launch 경로 안에서 크기로 분기합니다.
Before
if (two_shot && is_gfx1250() && nbytes <= int64_t{4} << 20) block_size = 256u;
#endif
if (two_shot) {
After
#ifdef USE_ROCM
#include "two_shot_push_unrolled.cuh"
#endif
...
if (two_shot && is_gfx1250() && nbytes <= int64_t{4} << 20) block_size = 256u;
if constexpr (kWorldSize <= 8) {
if (two_shot && is_gfx1250() && nbytes >= kTwoShotPushUnrolledMinBytes<kWorldSize>) {
LaunchKernel(push.default_blocks, kTwoShotPushThreads, stream) //
.enable_pdl(kUsePDL)(all_reduce_2shot_push_unrolled_kernel<T, kWorldSize, kUsePDL, PushParams>, params);
return out;
}
}
#endif
if constexpr (kWorldSize <= 8)로 TP16 인스턴스에서는 코드 자체가 생성되지 않습니다. 임계값 kTwoShotPushUnrolledMinBytes는 TP8 1 MB, TP5-7 2 MB, TP2-4 8 MB이며, 그 아래는 per-vector 커널이 더 빠릅니다. 이 분기가 공통 launch 경로에 있으므로 hier cross stage와 forced-2shot_push 테스트도 자동으로 새 커널을 탑니다. Lamport marker, single-word push epoch, fp32 rank order는 그대로 유지되어 결과가 bit-exact합니다.
2. ring_simple.cuh — FIFO 기반 ring all-reduce
새 파일의 핵심은 채널(=블록)마다 다음 rank 메모리에 있는 2-slot FIFO와 64-bit 카운터입니다.
struct alignas(128) RingSemaphore {
uint64_t drained; // successor가 drain한 packet 수; successor만 씀
uint64_t packet; // 이 rank가 보낸 packet 수; rank-local
uint64_t ready; // predecessor가 publish한 packet 수; predecessor만 씀
};
static_assert(sizeof(RingSemaphore) == 128, ...);
주석대로 "all counts are 64-bit so no comparison ever wraps" — wrap-around 처리 로직이 필요 없습니다. 각 필드는 writer가 하나뿐이라 atomic RMW 없이 relaxed store만으로 충분하고, 128B 정렬로 false sharing도 막습니다.
흐름 제어는 wait/post 두 람다로 단순화됩니다.
const auto wait = [&](bool recv, uint64_t recv_p, bool send, uint64_t send_p) {
if (threadIdx.x == 0) {
if (recv) wait_until(ready, &sem.ready, recv_p + 1);
if (send && send_p >= ws.num_slots) wait_until(drained, &sem.drained, send_p + 1 - ws.num_slots);
}
__syncthreads();
};
const auto post = [&](bool recv, uint64_t recv_p, bool send, uint64_t send_p) {
wait_stores_sys();
__syncthreads();
if (threadIdx.x == 0) {
if (recv) ptx::store_relaxed_sys(&prev_sem.drained, recv_p + 1);
if (send) ptx::store_relaxed_sys(&next_sem.ready, send_p + 1);
}
};
폴링은 thread 0만 하고 __syncthreads()로 결과를 전파합니다. 수신자는 카운터 하나만 확인하고 payload를 한 번만 읽습니다(slice 단위 publish).
wait_stores_sys는 작은 듯 중요한 최적화입니다.
SGL_DEVICE void wait_stores_sys() {
#if defined(__gfx1250__)
asm volatile("s_wait_storecnt 0x0" ::: "memory");
#else
device::ptx::fence_release_sys();
#endif
}
FIFO store는 system-scope로 캐시를 우회하므로, 완료만 기다리면 됩니다. full release fence가 넣는 cache writeback이 불필요하고, gfx12는 store 카운터를 load와 분리해 세므로 s_wait_storecnt만으로 충분합니다.
3. load를 먼저 다 띄우고, 컴파일러를 막는다
copy_packs는 lane당 32개(unroll 32) 16B load를 동시에 띄웁니다.
for (uint32_t u = 0; u < kUnroll; ++u)
if constexpr (!kRecv || kReduce) inputs[u] = in[u * kStride];
for (uint32_t u = 0; u < kUnroll; ++u)
if constexpr (kRecv) ptx::ld_relaxed_16B(vecs[u], recv_slot, j + u * kStride);
// keep every load ahead of the first use
__builtin_amdgcn_sched_barrier(0);
sched_barrier가 없으면 스케줄러가 레지스터 절약을 위해 각 reduction을 해당 load 바로 뒤로 끌어올려 wait를 삽입하고, memory-level parallelism이 사라집니다. 또 base pointer를 미리 계산해 pack offset이 immediate로 접히게 한 점("an index recomputed per pack reuses its VGPR, and each store then waits")도 주목할 만합니다. 같은 이유로 whole hunk만 unrolled 경로를 타고, bounds check는 tail에서만 합니다.
peer store는 새 helper st_relaxed_run_16B를 씁니다.
if constexpr (kUnroll % 8 == 0) {
ptx::st_relaxed_run_16B<kStride, kUnroll>(vecs, send_at);
} else {
for (uint32_t u = 0; u < kUnroll; ++u)
ptx::st_relaxed_16B(vecs[u], send_at, u * kStride);
}
system-scope global_store_b128 8개를 연속 발행한 뒤 s_wait_xcnt 한 번만 기다립니다. builtin store는 gfx1250에서 store마다 wait를 넣어 1256 MB에서 419% 손해였습니다.
4. 채널 분할: whole hunk 단위 (sixth commit)
채널별 몫을 균등 분할하면 대부분의 chunk에 partial hunk가 생기고, 이는 one-pack 경로의 추가 pass로 실행되어 full pass와 비슷한 비용이 듭니다. TP8에서 12 MB 배수가 아닌 모든 크기가 피해를 봤습니다(40 MB 278 us vs 48 MB 185 us). 몫을 world size × 32 lanes × 32 packs의 배수로 맞추자 마지막 채널만 partial hunk를 갖게 되었고, TP8 64 MB는 362→250.7 us, 256 MB는 834→725 us로 줄었습니다.
5. 토폴로지를 아는 ring 순서
같은 accelerator의 partition을 ring에서 인접시킵니다. 떨어뜨리면 모든 hop이 accelerator 밖 링크를 타서 64 MB 이상에서 1.5~1.8배 느려졌습니다.
설계와 리뷰 포인트
ring은 hier_2shot_push처럼 공통 추상화 밖에 둡니다. RingSimpleAllReduce가 plan·버퍼·plane을 소유하고, RingPlaneObj는 별도 FFI 객체이며, AllReduceConfig.use_ring 플래그로만 선택됩니다. AllReduceAlgo, CommunicatorObj 등 공통 코드는 건드리지 않았습니다. FIFO 버퍼(채널당 4 MB)도 테이블이 ring을 선택하는 경우에만 할당합니다. 리뷰에서는 "code/comment를 SKU independent하게" 하라는 요청이 있었고, CU 수를 런타임에 감지하고 제품명을 제거하는 방향으로 반영되었습니다(TP16 push grid도 고정값 대신 전체 CU 사용).
왜 이게 좋은가
Standalone (TP8, bf16, CUDA graph, us, carv2 / RCCL)
| size | 선택 | carv2 | RCCL |
|---|---|---|---|
| 1 MB | 2shot | 17.1 | 42.5 |
| 16 MB | 2shot | 88.6 | 92.0 |
| 64 MB | ring | 250.7 | 311.4 |
| 256 MB | ring | 725.2 | 1011.9 |
측정한 모든 셀에서 RCCL보다 빠르고, DeepSeek-V4-Flash TP8 serving 처리량은 +3.17.8%, TTFT 46%, TPOT 3~7% 개선됐습니다. GSM8K 정확도도 RCCL과 동등합니다.
흥미로운 점은 두 개의 size table입니다. HIP_FORCE_DEV_KERNARG=0에서 TP8 16 MB를 2shot_push로 돌리면 뒤따르는 fp8 quant 커널이 2 ms stall(정상 2551 us)해 prefill 처리량이 반토막 났습니다. kernel argument가 host 메모리에 있을 때만 생기는 현상이라, =0에서는 그 구간을 ring에 맡기고 =1에서는 2shot_push를 back-to-back 한계까지 씁니다. microbenchmark의 승자가 serving의 승자가 아닐 수 있다는 좋은 사례입니다.
또한 NT cache hint는 측정 결과 이득이 없어(±2%) 제거했습니다. 버퍼 descriptor가 wave-uniform base를 강제하는 비용만 남기 때문입니다.
일반적 교훈
- Load를 모두 띄운 뒤 사용하라 — 컴파일러가 레지스터 절약을 위해 MLP를 깨지 않도록
sched_barrier로 강제. - Store의 wait를 batch하라 — 원격 store마다 wait하면 interconnect latency가 그대로 직렬화됨.
- 필요한 만큼만 동기화하라 — 캐시 우회 store엔 writeback fence 대신 store counter wait.
- Single-writer 64-bit 카운터 — atomic RMW와 wrap 처리를 동시에 제거.
- 작업 분할을 커널 granularity에 맞춰라 — 균등 분할보다 hunk 정렬 분할이 tail pass를 없앰.
- 토폴로지와 실제 serving에서 검증하라 — ring 순서, kernarg 위치 같은 요소가 수십 % 차이를 만듦.
참고 자료
- HIP Programming Guide — __hip_atomic_load 등 HIP 프로그래밍 공식 문서
- RCCL Documentation — 비교 기준인 RCCL 공식 문서
- AMDGPU Backend User Guide (LLVM) — memory scope, s_wait 명령, amdgpu_waves_per_eu 속성 설명
⚠️ 알림: 이 분석은 AI가 실제 코드 diff를 기반으로 작성했습니다.
관련 포스트
PR Analysis 의 다른글
- 이전글 [sglang] HMM GPU의 페이지 폴트 폭풍 피하기: prefill PLE 행을 호스트에서 모아 한 번에 전송하기
- 현재글 : [sglang] gfx1250에서 RCCL을 넘어서다: ring_simple all-reduce와 unrolled 2shot_push 분석
- 다음글 [sglang] 커널 내부를 들여다보는 법: SGLang JIT 커널에 IKET/%clock 기반 In-kernel 이벤트 트레이싱 도입
댓글