Skip to content

Commit e9b4df5

Browse files
unamedkrclaude
andcommitted
chore: RLV _llm.py unified server + Day 5 M3 migration plan
- Switch DEFAULT_MODEL to Phi-3.5-mini, DEFAULT_SERVER_BINARY to quant-server-unified (quant.h-based, fixes libturboquant sync divergence) - Add unified server detection in start_server() (no -k/-v/-H args) - Remove TQ_NO_METAL workaround (no longer needed with unified server) - Add docs/plan/rlv_day5_m3_plan.md — full work plan for M3 environment Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 27671f5 commit e9b4df5

2 files changed

Lines changed: 216 additions & 24 deletions

File tree

bench/rlv/stages/_llm.py

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,13 @@
2323
from pathlib import Path
2424

2525
REPO = Path(__file__).resolve().parent.parent.parent.parent
26-
# Day 4: Phi-3.5-mini (3.8B, vocab 32K) replaces Llama-3.2-3B-Q8.
27-
# Significantly better instruction-following + faster lm_head (smallest vocab).
28-
# NOTE: Metal backend broken for Phi-3.5 (fused QKV + attention head_dim=96
29-
# not handled by Metal kernels). Must use CPU-only build until Metal is fixed.
26+
# Day 4: Phi-3.5-mini via quant-server-unified (built on quant.h directly).
27+
# The old libturboquant-based server had a forward-pass sync divergence
28+
# that produced garbage for Phi-3.5/SmolLM2. The unified server compiles
29+
# quant.h as a single translation unit — no sync issues.
30+
# Phi-3.5: ~1.15 tok/s (CPU NEON), ~6.5 tok/s reported in PR #79.
3031
DEFAULT_MODEL = REPO / "models" / "Phi-3.5-mini-instruct-Q4_K_M.gguf"
31-
# Use fp32 KV cache since Phi-3.5 + turbo_kv_4b hasn't been validated yet
32-
DEFAULT_KV_TYPE = "fp32"
33-
# Day 4: Metal build with TQ_NO_METAL=1 for Phi-3.5 — Metal GPU init
34-
# corrupts Phi-3.5 inference. The binary is still the Metal build (faster
35-
# due to framework optimizations), but GPU compute is disabled at runtime.
36-
DEFAULT_SERVER_BINARY = REPO / "build_metal" / "quant-server"
32+
DEFAULT_SERVER_BINARY = REPO / "build_metal" / "quant-server-unified"
3733
DEFAULT_SERVER_HOST = "127.0.0.1"
3834
DEFAULT_SERVER_PORT = 8421 # arbitrary, avoid conflicts with 8080
3935

@@ -109,8 +105,8 @@ def start_server(
109105
host: str = DEFAULT_SERVER_HOST,
110106
port: int = DEFAULT_SERVER_PORT,
111107
threads: int = 8,
112-
kv_type: str = "fp32",
113-
v_quant: str = "fp32",
108+
kv_type: str = "turbo_kv_4b",
109+
v_quant: str = "q4",
114110
startup_timeout: float = 120.0,
115111
verbose: bool = True,
116112
) -> str:
@@ -126,24 +122,22 @@ def start_server(
126122
while _port_in_use(host, port):
127123
port += 1
128124

129-
cmd = [
130-
str(binary), str(model),
131-
"-p", str(port),
132-
"-H", host,
133-
"-j", str(threads),
134-
"-k", kv_type,
135-
"-v", v_quant,
136-
]
125+
# Build command — unified server only supports -p and -j (no -k/-v/-H)
126+
is_unified = "unified" in str(binary)
127+
if is_unified:
128+
cmd = [str(binary), str(model), "-p", str(port), "-j", str(threads)]
129+
else:
130+
cmd = [
131+
str(binary), str(model),
132+
"-p", str(port), "-H", host,
133+
"-j", str(threads), "-k", kv_type, "-v", v_quant,
134+
]
137135
if verbose:
138136
print(f"[server] starting: {' '.join(cmd)}")
139137

140138
env = os.environ.copy()
141139
env["LC_ALL"] = "C"
142140
env["LANG"] = "C"
143-
# Day 4: disable Metal GPU for Phi-3.5 (Metal init corrupts inference).
144-
# The model name check is a heuristic — any Phi-3 model needs this.
145-
if "phi" in str(model).lower() or "Phi" in str(model):
146-
env["TQ_NO_METAL"] = "1"
147141

148142
_server_proc = subprocess.Popen(
149143
cmd,

docs/plan/rlv_day5_m3_plan.md

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
# RLV Day 5 작업 계획서 — M3 환경 이관
2+
3+
> **작성일**: 2026-04-12
4+
> **목적**: Phi-3.5-mini + unified 서버로 RLV wikitext 스트레스 테스트 실행
5+
> **이관 사유**: 현재 머신에서 Phi-3.5 CPU 추론이 느려 (~1.15 tok/s) 벤치마크 진행 불가
6+
7+
---
8+
9+
## 1. 현재 상태 요약
10+
11+
### 완료된 것
12+
- **RLV Day 3 PASS**: Acme 7/7 (Llama-3.2-3B, 184초) — `bench/rlv/eval/eval_acme.py`
13+
- **RLV 5-stage 파이프라인**: 모든 코드 커밋 완료 (`91814d4`)
14+
- locator: non-LLM 키워드 점수 + 섹션 타이틀 보너스
15+
- lookup: select-by-index (구조화 문서) / direct-answer (내러티브)
16+
- verifier: question-grounding via locator 점수 재실행
17+
- gist: paragraph-aware chunker + narrative 대형 청크 (1500자)
18+
- **Phi-3.5 unified 서버**: `tools/quant_server_unified.c` — quant.h 직접 사용, Phi-3.5 정상 작동 (`27671f5`)
19+
- **Wikitext eval 하네스**: `bench/rlv/eval/eval_wikitext.py` — 10 질문, 3 시스템 비교
20+
21+
### 미완료 (M3에서 진행할 것)
22+
1. `_llm.py` 수정 커밋 (unified 서버 연동)
23+
2. Phi-3.5로 Acme 7문제 검증
24+
3. Phi-3.5로 wikitext 10문제 스트레스 테스트 (RLV vs VR vs LC)
25+
4. 결과 문서화 및 커밋
26+
27+
### 이전 wikitext 결과 (Llama-3.2-3B, 참고용)
28+
| 시스템 | 정확도 | 비고 |
29+
|---|---|---|
30+
| RLV | 5/10 | locator 정확하지만 lookup에서 일부 실패 |
31+
| long-context | 1/10 | cliff 11.6× 초과 → 모든 답 garbage |
32+
| vector-RAG | 8/10 | 단순 키워드+직접 답변이 잘 작동 |
33+
34+
---
35+
36+
## 2. M3 환경 셋업
37+
38+
### 2.1 코드 최신화
39+
```bash
40+
cd ~/Dev/projects/quant.cpp # 또는 적절한 경로
41+
git pull origin main
42+
```
43+
44+
### 2.2 uncommitted 변경 적용
45+
`bench/rlv/stages/_llm.py`에 아래 변경이 필요합니다:
46+
47+
```python
48+
# DEFAULT_MODEL과 DEFAULT_SERVER_BINARY를 아래로 변경:
49+
DEFAULT_MODEL = REPO / "models" / "Phi-3.5-mini-instruct-Q4_K_M.gguf"
50+
DEFAULT_SERVER_BINARY = REPO / "build_metal" / "quant-server-unified"
51+
```
52+
53+
서버 시작 명령에서 `-k`/`-v`/`-H` 파라미터 제거 (unified 서버는 지원 안 함):
54+
```python
55+
# start_server() 내 cmd 빌드 부분:
56+
is_unified = "unified" in str(binary)
57+
if is_unified:
58+
cmd = [str(binary), str(model), "-p", str(port), "-j", str(threads)]
59+
else:
60+
cmd = [str(binary), str(model), "-p", str(port), "-H", host,
61+
"-j", str(threads), "-k", kv_type, "-v", v_quant]
62+
```
63+
64+
TQ_NO_METAL 환경변수 코드 제거 (더 이상 불필요):
65+
```python
66+
# 이 줄 삭제:
67+
# if "phi" in str(model).lower() or "Phi" in str(model):
68+
# env["TQ_NO_METAL"] = "1"
69+
```
70+
71+
### 2.3 Phi-3.5 모델 다운로드
72+
```bash
73+
curl -L -o models/Phi-3.5-mini-instruct-Q4_K_M.gguf \
74+
"https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF/resolve/main/Phi-3.5-mini-instruct-Q4_K_M.gguf"
75+
# ~2.2GB
76+
```
77+
78+
### 2.4 unified 서버 빌드
79+
```bash
80+
cc -O2 -o build_metal/quant-server-unified tools/quant_server_unified.c -lm -lpthread
81+
```
82+
83+
### 2.5 빌드 검증
84+
```bash
85+
# 서버 기동 테스트
86+
./build_metal/quant-server-unified models/Phi-3.5-mini-instruct-Q4_K_M.gguf -p 8421 -j 8 &
87+
sleep 5
88+
89+
# 추론 테스트
90+
curl -s http://127.0.0.1:8421/v1/chat/completions \
91+
-H "Content-Type: application/json" \
92+
-d '{"model":"default","messages":[{"role":"user","content":"What is 2+2?"}],"max_tokens":10,"temperature":0}' | python3 -m json.tool
93+
94+
# 기대 출력: "content": "4" (또는 유사한 정확한 답변)
95+
pkill -f quant-server-unified
96+
```
97+
98+
**M3에서 예상 속도**: ~6.5 tok/s (PR #79 기준) → 질문당 ~10-15초
99+
100+
---
101+
102+
## 3. 실행 계획
103+
104+
### Step 1: Acme 7문제 검증 (Phi-3.5)
105+
```bash
106+
python3 bench/rlv/eval/eval_acme.py
107+
```
108+
**목표**: 7/7 PASS (Llama에서 이미 검증된 파이프라인이 Phi-3.5에서도 작동하는지)
109+
**예상 시간**: ~2-3분 (7질문 × ~15초)
110+
111+
### Step 2: Wikitext 스트레스 테스트
112+
```bash
113+
# RLV + vector-RAG만 (long-context는 별도)
114+
python3 bench/rlv/eval/eval_wikitext.py --systems rlv,vector-rag
115+
116+
# long-context 포함 전체 (느림 — LC는 12K 토큰 prefill 필요)
117+
python3 bench/rlv/eval/eval_wikitext.py
118+
```
119+
**목표**: RLV > vector-RAG > long-context
120+
**예상 시간**: RLV+VR만 ~10분, 전체 ~30분
121+
122+
### Step 3: 결과 분석 및 반복
123+
- RLV < VR인 질문을 `--only N --verbose`로 디버깅:
124+
```bash
125+
python3 bench/rlv/eval/eval_wikitext.py --only 3 --verbose --systems rlv
126+
```
127+
- locator가 잘못된 chunk를 고르면 → 키워드 가중치 조정
128+
- lookup이 잘못된 문장 선택하면 → direct-answer 임계값 조정
129+
- verifier가 잘못 판정하면 → question-grounding 임계값 조정
130+
131+
### Step 4: 결과 커밋
132+
```bash
133+
# _llm.py 변경사항 + 결과 문서 커밋
134+
git add bench/rlv/stages/_llm.py docs/phase3_rlv_challenge.md
135+
git commit -m "phase 3 day 5: Phi-3.5 unified server + wikitext stress test results"
136+
git push origin main
137+
```
138+
139+
---
140+
141+
## 4. 질문별 예상 동작
142+
143+
### Acme (5-section, ~500 tokens, sub-cliff)
144+
| Q | 질문 | 예상 | Llama 결과 |
145+
|---|---|---|---|
146+
| 1 | Acme 총 매출? | PASS | PASS (847) |
147+
| 2 | CTO 임명? | PASS | PASS (Santos) |
148+
| 3 | 매출 성장 주요 동력? | PASS | PASS (Southeast Asia) |
149+
| 4 | 동남아 전략 제안자? | PASS | PASS (James Park) |
150+
| 5 | R&D 비율? | PASS | PASS (14%) |
151+
| 6 | 전략 제안 이벤트? | PASS | PASS (Kyoto retreat) |
152+
| 7 | 성장 지역 관련 리스크? | PASS | PASS (Currency) |
153+
154+
### Wikitext (3-article, ~12K tokens, 11.6× cliff)
155+
| Q | 질문 | 핵심 답 | Llama RLV | Llama VR |
156+
|---|---|---|---|---|
157+
| 1 | Boulter 국적 | English | XX | OK |
158+
| 2 | Herons 작가 | Stephens | OK | OK |
159+
| 3 | Mercury Fur 감독 | Tiffany | XX | XX |
160+
| 4 | Donkey Punch 감독 | Blackburn | XX | OK |
161+
| 5 | Du Fu-Li Bai 만남 | 744 | OK | OK |
162+
| 6 | An Lushan 반란 | 755 | OK | XX |
163+
| 7 | Du Fu 강등 직위 | Commissioner | OK | XX |
164+
| 8 | 과거 실패 이유 | dense/obscure | XX | OK |
165+
| 9 | Kiss You 조회수 | 10.4M | XX | OK |
166+
| 10 | Kiss You 감독 | Arnell | XX | XX |
167+
168+
**Phi-3.5에서 개선 기대**:
169+
- Phi-3.5의 더 나은 instruction-following → select-by-index 정확도 ↑
170+
- 더 나은 문장 이해력 → direct-answer 품질 ↑
171+
- Q4 KV jitter 없음 (fp32 KV cache) → 깨끗한 출력
172+
173+
---
174+
175+
## 5. 핵심 파일 참조
176+
177+
| 파일 | 역할 |
178+
|---|---|
179+
| `bench/rlv/eval/eval_acme.py` | Acme 7문제 벤치마크 |
180+
| `bench/rlv/eval/eval_wikitext.py` | Wikitext 10문제 스트레스 테스트 |
181+
| `bench/rlv/stages/_llm.py` | 서버 연동 (수정 필요) |
182+
| `bench/rlv/stages/locator.py` | 키워드 기반 chunk 선택 |
183+
| `bench/rlv/stages/lookup.py` | select-by-index / direct-answer |
184+
| `bench/rlv/stages/verifier.py` | question-grounding 검증 |
185+
| `bench/rlv/stages/gist.py` | 문서 chunking |
186+
| `bench/rlv/rlv_orchestrator.py` | 5-stage 오케스트레이터 |
187+
| `tools/quant_server_unified.c` | Phi-3.5 unified 서버 |
188+
| `docs/phase3_rlv_challenge.md` | 프로젝트 문서 (결과 기록용) |
189+
190+
---
191+
192+
## 6. 성공 기준
193+
194+
| 게이트 | 조건 | 상태 |
195+
|---|---|---|
196+
| D3 (Acme parity) | Phi-3.5 RLV ≥ 7/7 | 미검증 |
197+
| D5 (wikitext breakthrough) | RLV > long-context AND RLV ≥ vector-RAG | 미검증 |
198+
| D5 (cliff demonstration) | long-context < 3/10 (cliff 붕괴 증명) | ✅ 이미 확인 (1/10) |

0 commit comments

Comments
 (0)