4. Native MoE Expert LoRA (Mixtral)
개요
native_moe_expert_lora는 이미 MoE 구조를 가진 모델(Mixtral 등)의 기존 전문가 내부에 LoRA를 주입하는 전략입니다. MoE 구조를 새로 만들지 않고, 모델이 이미 가진 라우터와 전문가를 그대로 활용합니다.
- 적합한 용도: Mixtral 등 네이티브 MoE 모델 파인튜닝
- 호환 모델: Mixtral만 (네이티브 MoE 구조 필수)
- 참조 프리셋:
configs/presets/mixtral_native_expert_lora_sft.yml - moe_expert_lora와의 핵심 차이: "MoE를 새로 만드는 것" vs "기존 MoE에 LoRA만 추가"
사전 요구 사항
1. Where: 어디에 주입되는가?
다른 전략들이 find_ffn_module()로 FFN을 찾는 반면, 이 전략은 find_native_expert_groups()로 기존 MoE 전문가 그룹을 탐색합니다.
탐색 과정
MixtralAdapter.find_transformer_layers(model)— 트랜스포머 블록 탐색MixtralAdapter.find_native_expert_groups(block)— 기존 MoE 전문가 그룹 탐색 -block_sparse_moe(또는 유사 이름) 내부의expertsModuleList를 찾음 - 기존router/gate모듈도 탐색하지만 수정하지 않음NativeMoEExpertLoRAInjection클래스가 각 전문가에 LoRA 주입- (선택) 어텐션 프로젝션에도 LoRA 적용
Mixtral 모델 구조
MixtralDecoderLayer (block)
├── self_attn # 어텐션
│ ├── q_proj: Linear
│ ├── k_proj: Linear
│ ├── v_proj: Linear
│ └── o_proj: Linear
└── block_sparse_moe # 네이티브 MoE (FFN)
├── gate: Linear (라우터) ← 수정하지 않음
└── experts: ModuleList
├── expert[0]
│ ├── w1: Linear
│ ├── w2: Linear
│ └── w3: Linear
├── expert[1]: ...
└── ...
타겟 모듈
| 영역 | 탐색 방법 | 타겟 키워드 |
|---|---|---|
| MoE 전문가 FFN | find_native_expert_groups() |
w1, w2, w3 |
| Attention | find_attention_leaf_modules() |
q_proj, v_proj |
주의: Mixtral의 전문가 Linear 이름은
w1,w2,w3입니다. Qwen/LLaMA의gate_proj,up_proj,down_proj와 다릅니다.
관련 설정
backbone: mixtral # MixtralAdapter 사용
injection:
strategy: native_moe_expert_lora
target_keywords: [w1, w2, w3] # Mixtral 전문가 Linear 이름
start_layer: 0
num_layers: 0
attn_lora:
enabled: true
keywords: [q_proj, v_proj]
2. What: 무엇이 주입되는가?
기존 전문가의 각 Linear를 LoRALinear로 래핑합니다. MoE 구조 자체는 전혀 변경하지 않습니다.
변환 과정
변환 전: 변환 후:
[block_sparse_moe] [block_sparse_moe]
├── gate (그대로) ├── gate (그대로, 수정 안 함)
├── expert[0] ├── expert[0]
│ ├── w1: Linear │ ├── w1: LoRALinear (base + lora_A/B)
│ ├── w2: Linear │ ├── w2: LoRALinear
│ └── w3: Linear │ └── w3: LoRALinear
├── expert[1] ├── expert[1]
│ ├── w1: Linear │ ├── w1: LoRALinear
│ └── ... │ └── ...
└── ... └── ...
- 라우터(
gate)는 이미 사전 학습되어 있으므로 수정하지 않습니다. - 각 전문가의
w1,w2,w3만LoRALinear로 래핑됩니다. - Forward 동작은 기존 MoE 라우팅을 그대로 사용합니다.
관련 설정
injection:
strategy: native_moe_expert_lora
lora_r: 16 # LoRA 랭크 (전문가 수가 많으므로 작게)
lora_alpha: 32 # 스케일링 팩터 (32/16 = 2.0)
lora_dropout: 0.05 # LoRA 드롭아웃
파라미터 가이드:
- lora_r이 다른 전략(48)보다 작습니다(16). Mixtral은 전문가가 많아(보통 8개) 전체 LoRA 파라미터 수가 이미 크기 때문입니다.
- 전문가 수 × 레이어 수 × Linear 수 × 2(A,B) 개의 LoRA 텐서가 생성됩니다.
3. When: 언제 어떤 파라미터를 훈련하는가?
native_moe_expert_lora는 단일 페이즈 스케줄을 사용합니다. dense_lora와 유사하게 단순합니다.
페이즈 구성
training:
phases:
- step: 0
trainable: ["lora", "attn_lora"]
타임라인
Step 0 ──────────────────────────────────────> Step 5000
│
└── [lora + attn_lora 훈련]
기존 라우터(gate): frozen (이미 사전 학습됨)
기존 전문가 base 가중치: frozen
LoRA 파라미터 (lora_A, lora_B): trainable
왜 라우터 훈련이 불필요한가?
- Mixtral의 라우터는 사전 학습 과정에서 이미 안정적인 전문가 할당 패턴을 학습했습니다.
- 이 라우터를 다시 훈련하면 기존 전문가 전문성이 깨질 수 있습니다.
- LoRA만 학습하여 각 전문가의 출력을 미세 조정하는 것이 안전합니다.
4. MoE 안정성 설정
native_moe_expert_lora에는 moe 섹션이 불필요합니다.
- 모델이 이미 자체 라우팅 메커니즘을 갖고 있습니다.
- EulerForge가 새로운 라우터를 추가하지 않으므로, z-loss나 부하 분산이 필요 없습니다.
moe섹션을 포함하면 validator가 "moe section unnecessary" 경고를 발생시킵니다.
5. 전체 설정 파일 해설
configs/presets/mixtral_native_expert_lora_sft.yml 전문:
# ── 모델 정보 ──
device: cuda:0 # GPU 디바이스
backbone: mixtral # [Where] MixtralAdapter (네이티브 MoE 탐색)
model_name: yujiepan/mixtral-8xtiny-random # HuggingFace 모델 ID (테스트용 소형 모델)
# ── 인젝션 설정 ──
injection:
strategy: native_moe_expert_lora # [What] 기존 MoE 전문가에 LoRA 주입
lora_r: 16 # [What] LoRA 랭크 (전문가 다수이므로 작게)
lora_alpha: 32 # [What] 스케일링 (32/16 = 2.0)
lora_dropout: 0.05 # [What] LoRA 드롭아웃
target_keywords: [w1, w2, w3] # [Where] Mixtral 전문가 Linear 이름
start_layer: 0 # [Where] 시작 레이어
num_layers: 0 # [Where] 0 = 전체
attn_lora: # [Where] 어텐션 LoRA
enabled: true
keywords: [q_proj, v_proj]
# (moe 섹션 없음 - 네이티브 MoE는 불필요)
# ── 훈련 설정 ──
training:
type: sft # SFT 훈련
phases: # [When] 단일 페이즈
- step: 0
trainable: ["lora", "attn_lora"] # LoRA만 훈련
lr: 1.0e-5
weight_decay: 0.01
warmup_steps: 200
max_train_steps: 5000
batch_size: 4
grad_accum_steps: 4
max_grad_norm: 1.0
log_steps: 50
save_steps: 1000
val_steps: 500
참고: 프리셋의
model_name: yujiepan/mixtral-8xtiny-random은 테스트용 소형 모델입니다. 실제 사용 시mistralai/Mixtral-8x7B-v0.1등 실제 Mixtral 모델로 교체하세요.
6. 실행하기
기본 실행
eulerforge train --preset configs/presets/mixtral_native_expert_lora_sft.yml \
--set data.format=raw \
--set data.task=sft \
--set data.path=data/sft_10k_raw.jsonl \
--set data.max_length=512
실제 Mixtral 모델로 실행
eulerforge train --preset configs/presets/mixtral_native_expert_lora_sft.yml \
--set model_name=mistralai/Mixtral-8x7B-v0.1 \
--set data.format=raw \
--set data.task=sft \
--set data.path=data/sft_10k_raw.jsonl \
--set data.max_length=512 \
--set model.load_precision.mode=int4
프리플라이트 검사
eulerforge train --preset configs/presets/mixtral_native_expert_lora_sft.yml \
--preflight
7. 디버깅 및 트러블슈팅
| 증상 | 원인 | 해결 |
|---|---|---|
| "requires 'target_keywords' list" | target_keywords 미지정 |
target_keywords: [w1, w2, w3] 추가 |
| 전문가를 찾을 수 없음 | Dense 모델에 이 전략 적용 | Mixtral/MoE 모델에서만 사용. Dense 모델은 moe_expert_lora 사용 |
| "moe section unnecessary" 경고 | moe 섹션 포함 |
moe 섹션 제거 |
| OOM | 전체 Mixtral 모델이 큼 | model.load_precision.mode: int4, lora_r 감소, batch_size 감소 |
| 타겟 키워드 불일치 | Qwen/LLaMA 키워드(gate_proj 등) 사용 | Mixtral은 w1, w2, w3 사용 |
다음 단계
- Dense 모델을 MoE로 변환하려면 → FFN MoE Expert LoRA 튜토리얼
- 가장 기본적인 LoRA 파인튜닝 → Plain LoRA 튜토리얼
- DPO 훈련을 원한다면 → DPO 훈련 가이드