Skip to content

perf(megakernel): MHC 재구성 -- 배리어 0개, fn 레지스터 상주, 꼬리 큐: T=8 27.4 / T=32 42.0 µs - #224

Merged
choiceoh merged 1 commit into
mainfrom
feat/mhc-last-arriver
Sep 2, 2026
Merged

perf(megakernel): MHC 재구성 -- 배리어 0개, fn 레지스터 상주, 꼬리 큐: T=8 27.4 / T=32 42.0 µs#224
choiceoh merged 1 commit into
mainfrom
feat/mhc-last-arriver

Conversation

@choiceoh

@choiceoh choiceoh commented Sep 2, 2026

Copy link
Copy Markdown
Owner

요약

MHC 커널을 배리어 없는 구조로 재구성했습니다. T=8 30.7 → 27.4 µs, T=32 59.4 → 42.0 µs(stock 32.8 / 71.6 → −16% / −41%). 수치 1.25e-7 / 3.86e-7(게이트 1e-3), VERDICT PASS.

실험 T=8 / T=32 (µs) 배운 것
p1 의 청크별 fn 96 KB smem 상주(48 블록) 43.0 / 75.7 채움이 지연 지배, 토큰마다 smem 96 읽기, 동시성 1/3
꼬리를 토큰의 last-arriver 가 처리, 배리어 제거 34.6 / 86.0 쌍 16t+15 를 맡는 블록이 t, t+9, t+18, t+27 의 꼬리를 직렬로
꼬리 티켓 큐 34.8 / 59.4 T=32 동률, 꼬리 ~13 µs 가 T=8 에 더해짐
꼬리 분리 스탬프 + p34 선로드 32.8 / 67.6 3 블록/SM 이면 레지스터 상한 85 로 꼬리가 스필; 2 블록/SM 이면 정상
fn 을 레지스터(96개)에, 블록당 토큰 3개 30.7 / 51.2 T=8 의 p1 = 128쌍 × fn 96 KB = 12 MB 의 L2→SM 트래픽
레지스터 절약 꼬리(레인별 셔플) 34.8 / 45.1 꼬리 p2 12→8.8
mix 계수 선로드 + 8레인 그룹 축약 27.4 / 41.8 토큰당 사슬 ~3.3 µs
hc 상수 선로드·근사 내장함수·단일 레인 sinkhorn 27.4 / 42.0 프로브 창은 줄었으나 벤치 불변 — %globaltimer 프로브가 창마다 ~0.5 µs 를 더함

구조: p1 은 (청크, 토큰 그룹) 블록, fn 레지스터 상주, 다음 토큰 선로드, 전치 smem 축약, 토큰별 도착 카운터. 꼬리(p2·p3·p4)는 쌍을 끝낸 블록이 티켓으로 집어 처리(p2 한 워프: lane 24 sumsq 직접 합산, lane 0 의 4×4 sinkhorn 레지스터 수행; p3+p4 레지스터 융합). 마지막 퇴장 블록이 티켓 카운터 재무장(그래프 리플레이에 호스트 리셋 없음). 격자 배리어 0개.

  • 계약 테스트: 배리어 부재, 도착/티켓 카운터, 레지스터 fn·전치 축약, p34 선로드 분리, 단일 레인 sinkhorn.
  • -DMK_PHASE_TS 프로브 매크로(MK_MHC_PROBE)는 진단 전용, 기본 빌드에서는 비어 있습니다.

🤖 Generated with Claude Code


Note

Medium Risk
MHC is a fused GPU path on the inference hot path; wrong tail/arrival logic could affect layer inputs, while dropping prep_fused only removes an optional (default-off) optimization.

Overview
MK-MHC is restructured so mk_mhc_kernel runs only mk_mhc_p1 per block—no grid barriers. p1 maps blocks to (hidden chunk, token group), keeps each chunk’s fn slice in 96 registers, prefetches the next token, and publishes partials via per-token arrival counters. Finished blocks dequeue tail tickets to run per-token p2 (one warp, register 4×4 Sinkhorn), fused p3+p4 (register residuals, no ol_stash/sq round-trips), with the last block rearming ticket counters for graph replay. Adds optional MK_MHC_PROBE timestamps when MK_PHASE_TS is on.

Docs and MEASUREMENTS record ~T=8 27.4 µs / T=32 42.0 µs vs stock 32.8 / 71.6. tests/test_logic.py gains megakernel MHC contract checks for the new sync model.

glm53_prep_fused is removed end-to-end: Triton prep module, model install hook, overlay module, profiles/glm53.env mount, EXP-7 runbook, trace write-ups, and probes/run_prep_fused_check.sh / contract tests—decode input prep stays on the stock runner path.

Reviewed by Cursor Bugbot for commit e76452f. Bugbot is set up for automated code reviews on this repo. Configure here.

…0.7 → 27.4, T=32 59.4 → 42.0 µs

MHC 스탬프로 p1 이 T 에 비례하는 것(13.4 / 37.8)과 배리어·p2 편중(~10 µs)을
확인한 뒤 여덟 번의 실험(MEASUREMENTS.md 9차)으로 도달한 구조:
- p1: 블록 = (256차원 청크, 토큰 그룹). 청크의 fn 96개를 레지스터에 두고
  그룹의 토큰을 흘린다(예전 (토큰, 청크) 쌍 매핑은 T=8 에 12 MB 를 L2 로
  다시 읽었다). 다음 토큰의 입력·mix 계수 선로드, 25개 부분합은 전치
  smem 타일 + 8레인 그룹 축약, 청크 완료는 토큰별 도착 카운터.
- 꼬리(p2·p3·p4): 쌍을 끝낸 블록이 티켓을 받아 토큰의 16 도착을 기다리고
  카운터를 재무장한 뒤 처리. p2 는 한 워프(lane 24 가 sumsq 를 직접
  합산, lane 0 이 4x4 sinkhorn 을 레지스터에서), p3+p4 는 레지스터 융합
  (ol_stash/sq 왕복 제거). 마지막 퇴장 블록이 티켓 카운터를 재무장하므로
  그래프 리플레이에 호스트 리셋이 없다.
- 격자 배리어 3개 모두 제거.
기각(장부): fn smem 상주(43 / 76), last-arriver 꼬리(35 / 86: 한 블록에
꼬리 4개 직렬), 24값 셔플 브로드캐스트(3 블록/SM 의 레지스터 상한에서
스필). 수치 1.25e-7 / 3.86e-7 (게이트 1e-3), VERDICT PASS. README 에
구조 절, 계약 테스트 추가.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings September 2, 2026 09:55
@choiceoh
choiceoh merged commit 0995825 into main Sep 2, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 2, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-02T09:56:29.386297Z e76452f PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI 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.

🔵 Needs a closer look

It significantly alters a fused GPU inference hot path (new tail-queue synchronization and counter rearming semantics), which warrants careful human validation beyond static review.

Pull request overview

This PR refactors the GLM-5.3 megakernel MHC path to eliminate grid barriers by moving p2/p3/p4 work onto a tail ticket queue (with per-token arrival counters), and updates accompanying contract tests and documentation/measurement notes. It also removes the glm53_prep_fused experiment end-to-end (module wiring, probes, docs, and profile mounts).

Changes:

  • Restructure mk_mhc_kernel so blocks run p1 and then opportunistically dequeue tail tickets for per-token p2/p3/p4, with re-arming counters to support graph replay without host resets.
  • Add/extend logic-contract assertions for the new MHC synchronization model and update MK-megakernel documentation/measurements.
  • Remove glm53_prep_fused overlay module, probes, runbook/docs references, and profile mounts.
File summaries
File Description
tests/test_logic.py Adds MK‑MHC “no grid barrier”/tail-queue contract checks; removes glm53_prep_fused contract test and invocation.
STEP_KERNEL_MAP.md Removes the EXP‑7 prep-fused analysis section.
RUNBOOK_KERNEL_CAMPAIGN2.md Removes EXP‑7 prep-fused runbook section and list entry.
profiles/glm53.env Stops mounting glm53_prep_fused and removes the VLLM_GLM53_PREP_FUSED knob documentation.
probes/run_prep_fused_check.sh Deletes the prep-fused probe wrapper script.
probes/prep_fused_check.py Deletes the prep-fused numerics/launch-count probe.
overlay/modules/glm53_prep_fused/requires Removed with the glm53_prep_fused module teardown.
overlay/modules/glm53_prep_fused/README.md Removed with the glm53_prep_fused module teardown.
overlay/modules/glm53_prep_fused/manifest.tsv Removed with the glm53_prep_fused module teardown.
overlay/modules/glm53_prep_fused/glm53_prep_fused.py Removed with the glm53_prep_fused module teardown.
overlay/modules/glm53_model_wiring/glm5next_model.py Removes the optional install_glm53_prep_fused() hook.
overlay/modules/glm53_megakernel/README.md Documents the new MK‑MHC structure and benchmark results.
overlay/modules/glm53_megakernel/glm53_megakernel.cu Implements barrier-free MK‑MHC with per-token arrivals + tail ticket queue; adds MK_MHC_PROBE.
MEASUREMENTS.md Adds “megakernel 9차” MK‑MHC experiment log; removes prep-fused section.
build/glm53/manifest.tsv Removes the composed glm53_prep_fused.py entry.
build/glm53/glm5next_model.py Mirrors removal of the prep-fused install hook in the build output.
build/glm53/glm53_prep_fused.py Removed composed prep-fused module output.
build/glm53/glm53_megakernel.cu Mirrors MK‑MHC refactor and probe macro changes in the build output.
Review details
  • Files reviewed: 18/18 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +1126 to +1132
// trips and their two grid barriers are gone.
// p3 + p4 for ONE token, by one block: pre-mix the four residual streams
// (16 elements per thread, kept in registers), one block-wide sum of
// squares, then the normalized layer input -- the ol_stash / sq round
// trips and their two grid barriers are gone. The residual loads do not
// depend on p2, so every warp issues them BEFORE warp 0 runs p2 (load
// phase) and only the mixing runs after (compute phase).
Comment on lines +1126 to +1132
// trips and their two grid barriers are gone.
// p3 + p4 for ONE token, by one block: pre-mix the four residual streams
// (16 elements per thread, kept in registers), one block-wide sum of
// squares, then the normalized layer input -- the ol_stash / sq round
// trips and their two grid barriers are gone. The residual loads do not
// depend on p2, so every warp issues them BEFORE warp 0 runs p2 (load
// phase) and only the mixing runs after (compute phase).
Comment thread tests/test_logic.py
Comment on lines +6598 to +6602
# -- mhc: no grid barrier. The block that completes a token's 16th
# chunk runs that token's p2/p3/p4 (arrival counter, rearmed by the
# last arriver, other blocks' partials read through L2); p1 reduces
# its 25 partials through a transposed smem tile and prefetches the
# next pair's loads. Keeping fn in smem instead measured worse.

@cursor cursor 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.

Cursor Bugbot stayed pending and did not finish within the 8-minute wait, so this run is not approving. Human review is needed; one reviewer was assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: Pull Request Router and Approver

choiceoh pushed a commit that referenced this pull request Sep 2, 2026
PR #221 은 09:46Z 머지됐으나 PR #224(e76452f) 가 언급 없이 18개 파일 변경을
전부 되돌려 main 에서 사라졌다. 이 브랜치는 #221·#223 을 main 위에 다시 올리고
(cherry-pick), 10 관점 리뷰 + 검증 14건에서 확인된 결함을 고친다.

CONFIRMED 결함과 수정:
- plan 이 prefill_len.gpu / num_blocks.gpu 를 캐시: 둘은 UvaBackedTensor 라
  copy_to_uva() 마다 라운드로빈 풀의 다른 버퍼로 재바인딩된다(num_blocks 는
  매 스텝 apply_staged_writes 로 회전). 격 스텝마다 한 스텝 stale -> 새 블록으로
  넘어가는 스텝에 gather 가 한 블록 짧아 어텐션이 잘못된 블록을 읽음. 이미지
  코드로 재현. 수정: 소유 객체(BlockTables, UvaBackedTensor)를 plan 에 두고 발사
  시점에 .gpu / 포인터 텐서를 읽는다(wake-up 재생성도 자동 반영).
- 드래프터 KV 그룹(7번째)에 타깃 쪽 FlashInfer 빌더가 붙어 있어 build_plan 이
  모든 실제 부팅에서 실패 -> 모듈 inert. 수정: 드래프터 그룹을 레이어 소속
  (draft_attn_layer_names / draft_kv_cache_group_ids)으로 식별해 gather+slot 만.
- pinned 스테이징 버퍼 1개 재사용이 async scheduling 아래에서 이전 스텝 DMA 와
  경합(GB10 재현). 수정: 이미지의 UvaBufferPool(동시 배치 수 라운드로빈).
- Q 가 2의 거듭제곱이 아니면 tl.arange 컴파일 실패가 첫 적격 스텝에서 엔진을
  죽임. 수정: plan 가드, warmup 실패 DISARM, 발사 예외 시 stock 폴백.
- shadow 가 stock 배치를 반환해 armed 분기를 한 번도 실행 안 함. 수정: fused 뒤
  stock 사슬 전체(prepare_inputs·gather/slot·빌더)를 돌려 diff 하고 깨끗하면
  fused 배치를 흘린다; armed 도 64 fused 스텝마다 self-check, drift 면 DISARM.
- kpool tail 원형 버퍼 휴면을 가정만 함. 수정: plan 생성·검증마다 assert.
- 메타데이터 캐시는 dflash 가 dict 를 무시할 때만 안전. 수정: speculator 타입 게이트.
- 노브 오타가 arm 으로. 수정: 0/off/false/no, shadow, 1 만 인정, 나머지 DISARM.
- 런북·README 의 EXTRA_ENV="VLLM_GLM53_..." 는 프로필 선언 키라 런처가 ABORT
  (EXP-6 도 동일). 수정: caller env 형식 + 문서 lint 테스트.
- 프로브 래퍼가 preimage 검증 없이 전 행을 마운트(fi618 위에 v13 오버레이 5개).
  수정: 런처와 같은 base contract 검증, 프로필 이미지 기본.
- "88/64 us GPU" 는 호스트 발사 시간(실제 커널 ~23 us). 원장·README 정정, 하네스는
  CUDA 그래프 리플레이로 GPU 시간을 잰다.
- warmup 이 돌려주는 컴파일 커널로 직접 발사(Triton 디스패처 ~12 us/스텝 절감,
  검증에서 bit-exact); _load_ptr·PAD_SLOT_ID 재사용; 행 복사 2D 브로드캐스트;
  와이어링 훅은 "미마운트" 와 "모듈 내부 ImportError" 를 구분해 후자를 로그.

오프라인 게이트(srv2, glm53:v13-b12x, 31개 행 preimage 검증): 무작위 배치 60/60
bit-exact(UVA 핸들 회전 포함), C=1 스텝당 stock 2,469 us vs fused 184 us
(호스트+GPU), 실제 GPU 24.4 us(그래프 리플레이). tests/test_logic.py 통과.
서빙 미측정: EXP-7 섀도 부팅 -> 브래킷.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
choiceoh pushed a commit that referenced this pull request Sep 2, 2026
PR #221 은 09:46Z 머지됐으나 PR #224(e76452f) 가 언급 없이 18개 파일 변경을
전부 되돌려 main 에서 사라졌다. 이 브랜치는 #221·#223 을 main 위에 다시 올리고
(cherry-pick), 10 관점 리뷰 + 검증 14건에서 확인된 결함을 고친다.

CONFIRMED 결함과 수정:
- plan 이 prefill_len.gpu / num_blocks.gpu 를 캐시: 둘은 UvaBackedTensor 라
  copy_to_uva() 마다 라운드로빈 풀의 다른 버퍼로 재바인딩된다(num_blocks 는
  매 스텝 apply_staged_writes 로 회전). 격 스텝마다 한 스텝 stale -> 새 블록으로
  넘어가는 스텝에 gather 가 한 블록 짧아 어텐션이 잘못된 블록을 읽음. 이미지
  코드로 재현. 수정: 소유 객체(BlockTables, UvaBackedTensor)를 plan 에 두고 발사
  시점에 .gpu / 포인터 텐서를 읽는다(wake-up 재생성도 자동 반영).
- 드래프터 KV 그룹(7번째)에 타깃 쪽 FlashInfer 빌더가 붙어 있어 build_plan 이
  모든 실제 부팅에서 실패 -> 모듈 inert. 수정: 드래프터 그룹을 레이어 소속
  (draft_attn_layer_names / draft_kv_cache_group_ids)으로 식별해 gather+slot 만.
- pinned 스테이징 버퍼 1개 재사용이 async scheduling 아래에서 이전 스텝 DMA 와
  경합(GB10 재현). 수정: 이미지의 UvaBufferPool(동시 배치 수 라운드로빈).
- Q 가 2의 거듭제곱이 아니면 tl.arange 컴파일 실패가 첫 적격 스텝에서 엔진을
  죽임. 수정: plan 가드, warmup 실패 DISARM, 발사 예외 시 stock 폴백.
- shadow 가 stock 배치를 반환해 armed 분기를 한 번도 실행 안 함. 수정: fused 뒤
  stock 사슬 전체(prepare_inputs·gather/slot·빌더)를 돌려 diff 하고 깨끗하면
  fused 배치를 흘린다; armed 도 64 fused 스텝마다 self-check, drift 면 DISARM.
- kpool tail 원형 버퍼 휴면을 가정만 함. 수정: plan 생성·검증마다 assert.
- 메타데이터 캐시는 dflash 가 dict 를 무시할 때만 안전. 수정: speculator 타입 게이트.
- 노브 오타가 arm 으로. 수정: 0/off/false/no, shadow, 1 만 인정, 나머지 DISARM.
- 런북·README 의 EXTRA_ENV="VLLM_GLM53_..." 는 프로필 선언 키라 런처가 ABORT
  (EXP-6 도 동일). 수정: caller env 형식 + 문서 lint 테스트.
- 프로브 래퍼가 preimage 검증 없이 전 행을 마운트(fi618 위에 v13 오버레이 5개).
  수정: 런처와 같은 base contract 검증, 프로필 이미지 기본.
- "88/64 us GPU" 는 호스트 발사 시간(실제 커널 ~23 us). 원장·README 정정, 하네스는
  CUDA 그래프 리플레이로 GPU 시간을 잰다.
- warmup 이 돌려주는 컴파일 커널로 직접 발사(Triton 디스패처 ~12 us/스텝 절감,
  검증에서 bit-exact); _load_ptr·PAD_SLOT_ID 재사용; 행 복사 2D 브로드캐스트;
  와이어링 훅은 "미마운트" 와 "모듈 내부 ImportError" 를 구분해 후자를 로그.

오프라인 게이트(srv2, glm53:v13-b12x, 31개 행 preimage 검증): 무작위 배치 60/60
bit-exact(UVA 핸들 회전 포함), C=1 스텝당 stock 2,469 us vs fused 184 us
(호스트+GPU), 실제 GPU 24.4 us(그래프 리플레이). tests/test_logic.py 통과.
서빙 미측정: EXP-7 섀도 부팅 -> 브래킷.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
choiceoh added a commit that referenced this pull request Sep 2, 2026
fix(prep-fused): 리뷰 결함 12건 수정 + PR #224 가 되돌린 EXP-7 복원 (v2, 기본 off)
choiceoh pushed a commit that referenced this pull request Sep 2, 2026
…라운드는 유지

#230 의 커밋(7a287e0)은 0bd06b7 에서 갈라졌으면서 glm53_prep_fused·glm53_async_dflash·
glm53_indexer_gate_splitk 모듈, probes/tools 5개, glm5next_model.py 의 prep-fused 훅,
프로필 MODULES/노브, 테스트 419줄, 원장·RUNBOOK·커널맵 항목을 삭제했다(#224 와 같은
패턴: 오래된 작업 트리로 add -A). 유지한 것 = #230 이 실제로 작성한 것: 메가커널
.cu/README(KDA 2라운드), 테스트의 KDA 계약 2 hunk, 원장 10차 항목. 나머지는 이 브랜치
(0bd06b7 + 리뷰 처리분) 그대로. 41,247 checks OK.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants