본문으로 건너뛰기

[llm-compressor] RAZOR: '지웠을 때의 피해'로 MoE Expert를 고르는 pruning이 llm-compressor에 들어오다

PR 링크: vllm-project/llm-compressor#3437 상태: Merged | 변경: +1769 / -26

들어가며

MoE 모델의 VRAM을 줄이는 방법 중 하나는 expert 자체를 구조적으로 제거하는 것입니다. llm-compressor에는 이미 REAP과 HOPE가 있습니다. REAP은 각 expert를 독립적으로 평가합니다. 기준은 router-weighted 평균 출력 norm입니다.

여기에는 맹점이 있습니다. 출력 norm이 큰 expert라도 다른 expert가 같은 일을 하고 있다면, 지워도 레이어 출력은 거의 변하지 않습니다. 반대로 norm이 작아도 대체 불가능한 expert가 있을 수 있습니다. 실제로 expert를 지우면 두 가지 일이 일어납니다.

  1. 남은 expert들의 weight가 renormalize되고
  2. router가 빈 슬롯을 다음 순위 expert로 refill합니다.

이 PR은 RAZOR: Pruning Replaceable Experts in LLMs를 RazorPruningModifier로 구현합니다. 핵심 질문을 "이 expert가 얼마나 큰 값을 내는가"에서 "이 expert를 지우면 출력이 얼마나 망가지는가"로 바꾼 것입니다.

코드 분석

1. 알고리즘 정의 (examples/razor_expert_pruning/README.md)

토큰의 routed mixture를 consensus로 정의합니다.

c(x) = sum_{i in S(x)} w_i(x) * f_i(x)

expert i의 consensus residual은 r_i(x) = f_i(x) - c(x)입니다. expert i를 지우고 최상위 미선택 expert r이 pseudo-weight w_r(x) = s_r(x) / sum_{j in S(x)} s_j(x)로 승격된다고 가정합니다. 이 경우 출력 변화량은 다음과 같은 closed form으로 정확히 계산됩니다.

delta_i(x) = ||w_i(x) * r_i(x) - w_r(x) * r_r(x)||_2 / (1 - w_i(x) + w_r(x))

이 값을 토큰 단위로 모아 conditional RMS로 집계합니다.

S_j = sqrt(sum_t delta_j(t)^2 / max(n_j, 1))

이 설계에서 좋은 점은 세 가지입니다.

  • forward-only: gradient, subset search, recovery training이 모두 필요 없습니다. 실제로 expert를 하나씩 지워 보는 counterfactual 실험을 수식 하나로 대체합니다.
  • 조건부 RMS: 분모가 전체 토큰 수가 아니라 expert j로 routing된 토큰 수 n_j입니다. 그래서 드물게 선택되지만 선택될 때 결정적인 expert가 평균에 희석되지 않습니다.
  • max(n_j, 1): 한 번도 선택되지 않은 expert의 0 나눗셈을 막습니다. 리뷰에서 HDCharles가 "0을 명시적으로 처리하는 게 안전하다"고 제안했습니다. kylesayrs는 "implicit 처리가 유지보수와 성능 면에서 낫다"고 답했습니다.

criterion 인자로 세 가지 damage 정의를 고를 수 있습니다. "refill"(기본값), "rcs_loo"(refill 없는 leave-one-out), "rcs"(routing-weighted residual)입니다. router가 모든 expert를 선택하는 경우에는 승격할 expert가 없으므로, refill이 LOO로 수렴함을 테스트로 검증합니다.

2. Router score 재계산과 score function 추론

refill expert를 고르려면 선택되지 않은 expert의 score도 알아야 합니다. 그래서 매 batch마다 router linear projection으로 score를 다시 계산합니다. 변환 함수(softmax / sigmoid / sqrtsoftplus)는 config의 scoring_func 등에서 추론합니다.

리뷰에서 soyr-redhat이 중요한 지적을 했습니다. GLM-5.3-Flash는 sigmoid router를 쓰는데, 기본값에 의존하면 불안정할 수 있다는 것입니다. 이에 대한 대응으로 기본값을 softmax로 두되 warning을 출력하고, score_function으로 명시할 수 있게 바뀌었습니다.

e_score_correction_bias(DeepSeek-V3 스타일)는 router의 선택 규칙과 맞추기 위해 refill 후보를 고를 때만 반영됩니다. mixture weight에는 더하지 않습니다.

Nemotron처럼 experts 앞에 projection이 있는 구조에서는 크래시가 날 수 있다는 지적도 있었습니다. 이 부분은 follow-up 과제로 남았습니다.

3. 실행 경로: top-(k+1) 재작성

리뷰에서 가장 실질적인 논의는 비용 문제였습니다. HDCharles는 이렇게 지적했습니다.

don't you just need 1 refill expert per token? thats k+1 ... for 128 experts, keeping top 8, this means its a 128/9x=14x memory reduction

최종 README에는 이 방향이 반영되어 있습니다.

Calibration runs with `moe_calibrate_all_experts=False` (the modifier rewrites
the block's routing to top-(k+1), so the block's forward evaluates exactly the
k routed experts plus the one promoted expert per token that the refill
criterion needs — the promoted expert runs with zero mixture weight, leaving
the block's output unchanged)

refill expert를 mixture weight 0으로 같은 sparse forward에 끼워 넣는 방식입니다. 블록 출력은 바뀌지 않고, dense 실행 없이 필요한 출력만 얻습니다. moe_calibrate_all_experts=True일 때는 dense 출력에서 바로 읽으며, 두 경로의 saliency가 같다는 점을 테스트로 검증합니다.

4. 문서와 예제 (docs/steps/choosing-algo.md)

Before

| REAP | Reducing the memory footprint of MoE models | ... |
| HOPE | Expert pruning at aggressive sparsities | ... |

After

| RAZOR | Pruning MoE models while better preserving model behavior | Uses calibration data to score experts by the damage their deletion would do to the routed mixture output ... |

사용법은 REAP과 동일한 인터페이스를 따릅니다.

oneshot(
    model=model,
    dataset="perfectblend",
    recipe=RazorPruningModifier(sparsity=0.25),
    num_calibration_samples=512,
    max_seq_length=2048,
    moe_calibrate_all_experts=False,
)

GLM-5.3-Flash 예제는 두 단계 워크플로를 보여줍니다. 먼저 sparsity=0.0의 report-only 모드로 분산 calibration을 돌립니다. 그다음 ExpertPruner가 checkpoint 공간에서 직접 가지치기를 합니다.

pruner = ExpertPruner.from_pretrained(
    MODEL_ID,
    sparsity=SPARSITY,
    metric="saliency",
    uniform=True,
    saliency_report_path=REPORT_PATH,
    ...
    aux_pattern=(... r"\.mlp\.gate\.e_score_correction_bias"),
)

aux_pattern으로 routing bias도 router weight 행과 같은 축으로 잘라냅니다. 이 처리를 빠뜨리면 pruning 후 bias 차원이 맞지 않게 됩니다.

왜 이게 좋은가

  • 품질: 논문 기준으로 GLM-4.7-Flash와 Qwen3.6-35B-A3B에서 25%/50% expert를 제거한 네 가지 설정 모두에서 REAP 대비 9-task macro average가 2.12~5.59점 높았습니다. reverse KL도 네 설정 모두에서 더 낮았습니다.
  • 비용: per-layer 통계는 O(num_experts)입니다(squared-damage 합과 count). DDP에서는 rank별로 합을 먼저 reduce한 뒤 나누기 때문에, 데이터가 불균등하게 분산돼도 conditional RMS가 정확히 pooling됩니다. 평균끼리 평균을 내면 생기는 편향을 피하는 정석적인 설계입니다.
  • 호환성: report 포맷이 REAP과 공유되므로 ExpertPruner, tools/plot_reap_report.py를 그대로 쓸 수 있습니다.

일반적 교훈

  1. 중요도는 고립된 크기가 아니라 '제거했을 때의 변화량'으로 재야 합니다. redundancy를 고려하지 않는 saliency는 대체 가능한 컴포넌트를 과대평가합니다.
  2. counterfactual을 closed form으로 유도하면 실제로 N번 지워 보는 비용을 forward 한 번으로 줄일 수 있습니다.
  3. 보조 연산을 weight 0으로 기존 경로에 끼워 넣으면 출력을 바꾸지 않으면서 필요한 activation만 얻을 수 있습니다. top-(k+1) 트릭이 그 예입니다.
  4. 분산 통계는 sufficient statistic(합, count)으로 reduce하세요.

참고 자료

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

댓글

관련 포스트

PR Analysis 의 다른글