hotdogs commited on
Commit
862ec11
·
verified ·
1 Parent(s): 3164ccc

Add AGENT_GUIDE — reproducible MoE pipeline for agents

Browse files
Files changed (1) hide show
  1. AGENT_GUIDE.md +282 -0
AGENT_GUIDE.md ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENT_GUIDE.md — FrankenMoE Reproducible Pipeline
2
+
3
+ > **Purpose:** Step-by-step guide for building a Mixture-of-Experts (MoE) from LoRA fine-tuned dense models.
4
+ > **Target reader:** AI agents, MLOps engineers, future you.
5
+ > **Last verified:** May 2026, mergekit 0.1.4, Qwen2.5-1.5B-Instruct
6
+
7
+ ---
8
+
9
+ ## Quick Reference Card
10
+
11
+ ```
12
+ ARCH: QwenMoE (mergekit) → GGUF (llama.cpp)
13
+ BASE: Qwen2.5-1.5B-Instruct
14
+ EXPERTS: 2 (coding, math) + 1 shared
15
+ SIZE: 3.86B params, 8.2 GB safetensors, 8.2 GB GGUF F16
16
+ INFRA: RTX 4060 Ti 16GB (train) + RTX 8000 48GB (merge, convert)
17
+ ```
18
+
19
+ ---
20
+
21
+ ## Phase 1: LoRA Fine-Tuning
22
+
23
+ ```bash
24
+ # Install
25
+ pip install torch transformers peft datasets accelerate
26
+
27
+ # Train (example — use your own training script)
28
+ python train_lora.py \
29
+ --base_model unsloth/Qwen2.5-1.5B-Instruct \
30
+ --domain coding \
31
+ --lora_r 16 --lora_alpha 32 \
32
+ --target_modules q_proj,k_proj,v_proj,o_proj \
33
+ --learning_rate 2e-5 --batch_size 4 \
34
+ --epochs 3 --precision bf16
35
+ ```
36
+
37
+ ### Key config
38
+ | Param | Value | Why |
39
+ |-------|-------|-----|
40
+ | lora_r | 16 | Good balance size/quality |
41
+ | lora_alpha | 32 | Standard alpha=2*r |
42
+ | target_modules | q,k,v,o_proj | Attention only (FFN stays frozen) |
43
+ | precision | bf16 | Required for RTX 4060 Ti |
44
+
45
+ ### Output
46
+ ```
47
+ outputs/coding_lora/
48
+ ├── adapter_model.safetensors (~71 MB)
49
+ ├── adapter_config.json
50
+ └── tokenizer files...
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Phase 2: LoRA → Dense Merge
56
+
57
+ ```python
58
+ from peft import PeftModel
59
+ from transformers import AutoModelForCausalLM
60
+
61
+ base = AutoModelForCausalLM.from_pretrained(
62
+ "unsloth/Qwen2.5-1.5B-Instruct",
63
+ torch_dtype=torch.bfloat16,
64
+ device_map="auto"
65
+ )
66
+ model = PeftModel.from_pretrained(base, "outputs/coding_lora")
67
+ model = model.merge_and_unload()
68
+ model.save_pretrained("outputs/dense_coding")
69
+ ```
70
+
71
+ > ⚠️ **CRITICAL:** `merge_and_unload()` is REQUIRED. mergekit cannot use LoRA adapters directly.
72
+
73
+ ---
74
+
75
+ ## Phase 3: MoE Assembly (mergekit)
76
+
77
+ ### 3a. Install & Patch mergekit
78
+
79
+ ```bash
80
+ pip install mergekit==0.1.4
81
+ ```
82
+
83
+ ### 3b. **PATCH REQUIRED** — `router.py` line 122
84
+
85
+ mergekit 0.1.4 passes `load_in_4bit` / `load_in_8bit` directly to `from_pretrained()`.
86
+ This is BROKEN in transformers >= 4.40.
87
+
88
+ ```bash
89
+ # Find the file
90
+ ROUTER=$(python3 -c "import mergekit.moe; print(mergekit.moe.router.__file__)")
91
+
92
+ # Patch: remove load_in_4bit and load_in_8bit params
93
+ sed -i 's/load_in_4bit=load_in_4bit,//' $ROUTER
94
+ sed -i 's/load_in_8bit=load_in_8bit,//' $ROUTER
95
+ ```
96
+
97
+ ### 3c. MoE Config
98
+
99
+ ```yaml
100
+ # moe_config.yaml
101
+ base_model: unsloth/Qwen2.5-1.5B-Instruct
102
+ gate_mode: random # "hidden" also works but more complex
103
+ dtype: bfloat16
104
+ experts_per_token: 1 # top-1 routing
105
+
106
+ experts:
107
+ - source_model: outputs/dense_coding
108
+ positive_prompts:
109
+ - "Write a Python function to sort a list"
110
+ - "Debug this code snippet"
111
+ - source_model: outputs/dense_math
112
+ positive_prompts:
113
+ - "Solve x^2 + 5x + 6 = 0"
114
+ - "Find the derivative of f(x) = x^3"
115
+
116
+ shared_experts:
117
+ - source_model: unsloth/Qwen2.5-1.5B-Instruct
118
+ positive_prompts:
119
+ - "Hello, how are you?"
120
+ - "What is the capital of France?"
121
+ ```
122
+
123
+ ### 3d. Run mergekit-moe
124
+
125
+ ```bash
126
+ mergekit-moe moe_config.yaml moe_output/ --trust-remote-code
127
+ ```
128
+
129
+ ### 3e. **CRITICAL RULES**
130
+
131
+ | Rule | Wrong ❌ | Right ✅ |
132
+ |------|---------|---------|
133
+ | Shared experts | 0 | **Exactly 1** |
134
+ | Routed experts count | 3 | **2, 4, or 8** (power of 2) |
135
+ | Expert source | LoRA adapter | **Merged dense model** |
136
+ | llama.cpp compatibility | Non-power-of-2 | **2^n only** |
137
+
138
+ ---
139
+
140
+ ## Phase 4: GGUF Conversion (THE HARD PART)
141
+
142
+ ### Problem: Qwen2.5 uses Tied Embeddings
143
+
144
+ Qwen2.5 has `tie_word_embeddings: true` → no separate `lm_head.weight` tensor.
145
+ llama.cpp requires explicit `output.weight` in the GGUF.
146
+
147
+ ### Fix: Clone embed_tokens → lm_head
148
+
149
+ ```python
150
+ import torch, os, shutil, json
151
+ from safetensors.torch import save_file, load_file
152
+
153
+ SRC = "moe_output"
154
+ DST = "moe_output_fixed"
155
+ os.makedirs(DST, exist_ok=True)
156
+
157
+ # Copy config files
158
+ for f in ["config.json", "tokenizer.json", "tokenizer_config.json"]:
159
+ src_f = os.path.join(SRC, f)
160
+ if os.path.exists(src_f):
161
+ shutil.copy2(src_f, os.path.join(DST, f))
162
+
163
+ # Fix each shard
164
+ for sf in sorted(f for f in os.listdir(SRC) if f.endswith(".safetensors")):
165
+ tensors = load_file(os.path.join(SRC, sf))
166
+ if "model.embed_tokens.weight" in tensors:
167
+ tensors["lm_head.weight"] = tensors["model.embed_tokens.weight"].clone()
168
+ save_file(tensors, os.path.join(DST, sf))
169
+
170
+ # Update config
171
+ with open(os.path.join(DST, "config.json")) as f:
172
+ config = json.load(f)
173
+ config["tie_word_embeddings"] = False
174
+ with open(os.path.join(DST, "config.json"), "w") as f:
175
+ json.dump(config, f)
176
+ ```
177
+
178
+ ### Convert to GGUF
179
+
180
+ ```bash
181
+ cd llama.cpp
182
+ python3 convert_hf_to_gguf.py moe_output_fixed --outtype f16 --outfile model-F16.gguf
183
+ ```
184
+
185
+ ### Verify output.weight exists
186
+
187
+ ```bash
188
+ # GGUF binary check: output.weight should appear multiple times
189
+ strings model-F16.gguf | grep -c "output.weight"
190
+ # Expected: > 0 (found 29 in our build)
191
+ ```
192
+
193
+ ---
194
+
195
+ ## Phase 5: Test
196
+
197
+ ### transformers
198
+ ```python
199
+ from transformers import AutoModelForCausalLM
200
+ model = AutoModelForCausalLM.from_pretrained(
201
+ "moe_output_fixed", trust_remote_code=True,
202
+ torch_dtype=torch.bfloat16, device_map="auto"
203
+ )
204
+ ```
205
+
206
+ ### llama.cpp
207
+ ```bash
208
+ llama-cli -m model-F16.gguf -p "Write a Python function to sort a list"
209
+ ```
210
+
211
+ > ⚠️ **Expected:** With `gate_mode: random`, output is coherent but not domain-optimal.
212
+ > Router training is needed for production quality.
213
+
214
+ ---
215
+
216
+ ## Phase 6: Quantize (Optional)
217
+
218
+ ```bash
219
+ # F16 → Q4_K_M (~4x smaller)
220
+ llama-quantize model-F16.gguf model-Q4_K_M.gguf Q4_K_M
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Complete File Checklist
226
+
227
+ ```
228
+ ✅ moe_output_fixed/
229
+ ├── config.json (tie_word_embeddings: false)
230
+ ├── tokenizer.json
231
+ ├── model-00001-of-00002.safetensors (has lm_head.weight)
232
+ ├── model-00002-of-00002.safetensors
233
+ └── model.safetensors.index.json
234
+ ✅ model-F16.gguf (has output.weight)
235
+ ✅ model-Q4_K_M.gguf (optional, 4x smaller)
236
+ ```
237
+
238
+ ---
239
+
240
+ ## Common Pitfalls
241
+
242
+ | Error | Cause | Fix |
243
+ |-------|-------|-----|
244
+ | `missing tensor 'output.weight'` | tied embeddings, no lm_head | Clone embed→lm_head, tie=False |
245
+ | `MistralForCausalLM got load_in_4bit` | mergekit 0.1.4 bug | Patch router.py line 122 |
246
+ | `3 experts not power of two` | Wrong expert count | Use 2, 4, or 8 experts |
247
+ | `QwenMoE requires 1 shared expert` | No shared_expert in config | Add shared_experts section |
248
+ | Garbage output | LoRA not merged, or 3 experts | merge_and_unload(), use 2^n |
249
+ | OOM during GGUF convert | 16GB GPU not enough | Use CPU: `--outtype f16` (CPU-only) |
250
+
251
+ ---
252
+
253
+ ## Environment Used
254
+
255
+ ```yaml
256
+ OS: Ubuntu 22.04
257
+ GPU: Quadro RTX 8000 48GB
258
+ Python: 3.12
259
+ mergekit: 0.1.4
260
+ transformers: 4.49+
261
+ torch: 2.5+
262
+ peft: latest
263
+ safetensors: latest
264
+ llama.cpp: latest (git clone)
265
+ ```
266
+
267
+ ---
268
+
269
+ ## Scaling Up
270
+
271
+ For larger base models (Qwen2.5-7B, 14B, 32B):
272
+
273
+ 1. Same pipeline works — just more VRAM needed
274
+ 2. Training: multi-GPU or cloud GPU with >24GB
275
+ 3. MoE assembly: CPU-only works (no GPU needed for merge)
276
+ 4. GGUF F16 size ≈ params × 2 bytes (3.86B → 7.7 GB, 7B → 14 GB)
277
+ 5. Router training: use cloud GPU (48GB+) with classification loss
278
+ 6. 4 experts ideal: coding, math, chat, medical — fills all 2^n slots
279
+
280
+ ---
281
+
282
+ *Built by UKA — May 2026 — Bangkok, Thailand 🇹🇭*