Skip to content

Commit 0c14e95

Browse files
unamedkrclaude
andcommitted
v0.8: Self-contained inference engine — no external dependencies
TurboQuant is now a COMPLETE inference engine, not just a library. Loads models, runs forward pass, generates tokens — all in pure C. New engine components (src/engine/): - tq_ops.c: matmul (NEON 4-acc unrolled), rmsnorm, rope, silu, softmax - tq_transformer.c: Full LLaMA-style forward pass with GQA + SwiGLU FFN KV cache uses TurboQuant quantization (integer attention integrated) - tq_model.c: safetensors loader (mmap, zero-copy, JSON parser) - tq_tokenizer.c: BPE tokenizer (encode/decode) - tq_generate.c: Autoregressive generation with top-p sampling + streaming - tq_run.c: CLI inference tool API (include/turboquant/tq_engine.h): tq_load_model(path) → model tq_forward(model, state, token, pos) → logits tq_generate(model, prompt, config, output, size) → tokens generated Key design: - Zero external dependencies (libc/libm only) - KV cache automatically quantized with TurboQuant during inference - Integer Q4×Q8 attention in the forward pass (2.9-4.8x faster) - NEON-optimized matmul (16 elements/iteration, 4 accumulators) - mmap model loading (zero-copy) - Streaming token output via callback Tests: 19 suites pass (33 new op tests + 18 existing) Usage: tq_run --model model.safetensors --prompt "Hello" --kv-type uniform_4b Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent c299c8f commit 0c14e95

11 files changed

Lines changed: 2784 additions & 0 deletions

File tree

CMakeLists.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ option(TQ_BUILD_METAL "Build Metal backend" OFF)
1313
file(GLOB TQ_CORE_SOURCES src/core/*.c)
1414
file(GLOB TQ_CACHE_SOURCES src/cache/*.c)
1515
file(GLOB TQ_CPU_SOURCES src/backend/cpu/*.c)
16+
file(GLOB TQ_ENGINE_SOURCES src/engine/*.c)
1617

1718
add_library(turboquant STATIC
1819
${TQ_CORE_SOURCES}
1920
${TQ_CACHE_SOURCES}
2021
${TQ_CPU_SOURCES}
22+
${TQ_ENGINE_SOURCES}
2123
)
2224
target_include_directories(turboquant PUBLIC include)
2325
target_link_libraries(turboquant PRIVATE m)
@@ -27,6 +29,7 @@ add_library(turboquant_shared SHARED
2729
${TQ_CORE_SOURCES}
2830
${TQ_CACHE_SOURCES}
2931
${TQ_CPU_SOURCES}
32+
${TQ_ENGINE_SOURCES}
3033
)
3134
target_include_directories(turboquant_shared PUBLIC include)
3235
target_link_libraries(turboquant_shared PRIVATE m)
@@ -82,6 +85,10 @@ if(TQ_BUILD_BENCH)
8285
endforeach()
8386
endif()
8487

88+
# CLI inference tool
89+
add_executable(tq_run tools/tq_run.c)
90+
target_link_libraries(tq_run turboquant)
91+
8592
# Examples (always built)
8693
file(GLOB EXAMPLE_C_SOURCES examples/*.c)
8794
file(GLOB EXAMPLE_CXX_SOURCES examples/*.cpp)

docs/plan/prd/prd_v0.8.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# TurboQuant.cpp — Product Requirements Document v0.8
2+
3+
**Version**: 0.8
4+
**Date**: 2026-03-29
5+
**Focus**: 자체 추론 엔진 — 모델 로드부터 토큰 생성까지, 외부 의존성 없이
6+
7+
---
8+
9+
## 1. Problem
10+
11+
현재 TurboQuant.cpp는 KV 캐시 압축 **라이브러리**일 뿐이다. 실제 추론은 PyTorch에 의존하며, CPU에서 0.8 tok/s로 매우 느리다.
12+
13+
refs/ 프로젝트들의 강점을 융합한 **자체 추론 엔진**이 필요하다:
14+
15+
| refs/ 프로젝트 | 가져올 강점 | 현재 구현 |
16+
|---------------|-----------|----------|
17+
| **llama.cpp** | 순수 C 추론, GGUF 로더, NEON matmul | ❌ 없음 |
18+
| **vLLM** | PagedAttention, 퓨전 커널 | ⚠️ 캐시만 |
19+
| **ONNX** | 표준 연산자, 포맷 호환 | ⚠️ 비트패킹만 |
20+
21+
## 2. Goal
22+
23+
**순수 C로 구현된 최소 추론 엔진** — Qwen3.5-0.8B를 외부 의존성 없이 CPU에서 **10+ tok/s**로 실행.
24+
25+
참조: Karpathy의 llama2.c (순수 C, ~700줄, 외부 의존성 없음)
26+
27+
## 3. Architecture
28+
29+
```
30+
┌─────────────────────────────────────────────┐
31+
│ tq_generate() — Autoregressive decode loop │
32+
├─────────────────────────────────────────────┤
33+
│ tq_forward() — Single forward pass │
34+
│ ├── RMSNorm │
35+
│ ├── QKV Projection (matmul) │
36+
│ ├── RoPE (rotary position embedding) │
37+
│ ├── KV Cache (TurboQuant quantized!) │
38+
│ ├── Attention (integer Q4×Q8!) │
39+
│ ├── Output Projection (matmul) │
40+
│ ├── FFN: gate/up → SiLU → down │
41+
│ └── Residual connections │
42+
├─────────────────────────────────────────────┤
43+
│ tq_load_model() — Weight loader │
44+
│ ├── safetensors / GGUF / custom format │
45+
│ └── Weight quantization (Q4/Q8) │
46+
├─────────────────────────────────────────────┤
47+
│ tq_tokenize() — BPE tokenizer │
48+
├─────────────────────────────────────────────┤
49+
│ tq_sample() — Top-p, temperature │
50+
└─────────────────────────────────────────────┘
51+
```
52+
53+
핵심: **KV 캐시에 TurboQuant 양자화가 내장**된 추론 엔진. 기존 라이브러리의 모든 기능(정수 attention, RHT, mixed precision, progressive compression)이 추론 파이프라인 안에서 동작.
54+
55+
## 4. Requirements
56+
57+
### FR-V8-1: 텐서 연산 (src/engine/tq_ops.c)
58+
59+
llama.cpp GGML 패턴 참조:
60+
- `tq_matmul()` — 행렬-벡터 곱 (가중치 × 활성화), NEON 최적화
61+
- `tq_rmsnorm()` — RMS normalization
62+
- `tq_rope()` — Rotary Position Embedding
63+
- `tq_silu()` — SiLU activation (x * sigmoid(x))
64+
- `tq_softmax()` — Softmax (attention scores)
65+
- `tq_add()` — 잔차 연결
66+
67+
### FR-V8-2: 모델 로더 (src/engine/tq_model.c)
68+
69+
- safetensors 포맷 읽기 (Qwen3.5-0.8B 호환)
70+
- 가중치를 FP32 또는 Q8로 로드
71+
- 모델 구조 자동 감지 (config.json 파싱)
72+
- mmap 지원 (대용량 모델 메모리 효율)
73+
74+
### FR-V8-3: Transformer 블록 (src/engine/tq_transformer.c)
75+
76+
Qwen3.5-0.8B의 Gated Attention 레이어:
77+
```
78+
input → RMSNorm → QKV_proj → RoPE → Attention → O_proj → residual
79+
→ RMSNorm → gate_proj + up_proj → SiLU → down_proj → residual
80+
```
81+
82+
KV 캐시에 TurboQuant 양자화 자동 적용:
83+
- 새 키 생성 → `tq_quantize_keys()` → 양자화 캐시에 저장
84+
- Attention 계산 → `tq_attention_int()` → 정수 도메인에서 직접 계산
85+
86+
### FR-V8-4: 토크나이저 (src/engine/tq_tokenizer.c)
87+
88+
- BPE 토크나이저 (tokenizer.json 로드)
89+
- encode: 문자열 → 토큰 ID
90+
- decode: 토큰 ID → 문자열
91+
92+
### FR-V8-5: 생성 루프 (src/engine/tq_generate.c)
93+
94+
- Autoregressive decode: 한 토큰씩 생성
95+
- Prefill: 프롬프트 전체를 한번에 처리
96+
- Sampling: temperature, top-p, top-k
97+
- 스트리밍 출력 (토큰 생성 즉시 출력)
98+
99+
### FR-V8-6: CLI (tools/tq_run)
100+
101+
```bash
102+
# 모델 실행
103+
tq_run --model qwen3.5-0.8b.safetensors --prompt "What is deep learning?"
104+
105+
# 옵션
106+
tq_run --model MODEL --prompt TEXT \
107+
--kv-type uniform_4b \ # KV 캐시 양자화 타입
108+
--max-tokens 100 \
109+
--temperature 0.7 \
110+
--threads 4
111+
```
112+
113+
## 5. Success Criteria
114+
115+
| 지표 | 목표 |
116+
|------|------|
117+
| CPU 추론 속도 | **10+ tok/s** (현재 PyTorch: 0.8 tok/s) |
118+
| MPS 추론 속도 | **30+ tok/s** |
119+
| 메모리 사용량 | **< 2 GB** (Qwen3.5-0.8B Q8 가중치 + KV 캐시) |
120+
| 외부 의존성 | **0개** (libc/libm만) |
121+
| KV 캐시 압축 | 기존 TurboQuant 전체 기능 내장 |
122+
| 정확도 | PyTorch FP32 대비 동일 텍스트 생성 |
123+
124+
## 6. Scope
125+
126+
### v0.8.0 (최소 동작)
127+
- Qwen3.5-0.8B Gated Attention 레이어만 지원
128+
- safetensors 로더
129+
- FP32 가중치 + TurboQuant KV 캐시
130+
- CPU 추론 (NEON 최적화)
131+
- 기본 BPE 토크나이저
132+
133+
### v0.8.1 (최적화)
134+
- Q8 가중치 양자화 (메모리 절반)
135+
- NEON matmul 최적화
136+
- 멀티스레드 prefill
137+
138+
### v0.9+ (확장)
139+
- DeltaNet 레이어 지원 (Qwen3.5 전체)
140+
- Metal GPU 추론
141+
- GGUF 호환
142+
- 다른 모델 아키텍처 (Llama, Phi)

docs/plan/wbs/wbs_v0.8.md

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# TurboQuant.cpp — Work Breakdown Structure v0.8
2+
3+
**Version**: 0.8
4+
**Date**: 2026-03-29
5+
**Focus**: 자체 추론 엔진 구현
6+
7+
---
8+
9+
## Phase 1: 텐서 연산 커널
10+
11+
- [ ] `src/engine/tq_ops.c` — 핵심 연산
12+
- [ ] `tq_matmul(out, x, w, n, d)` — 행렬-벡터 곱 (w[n,d] × x[d] → out[n])
13+
- [ ] `tq_matmul_neon()` — ARM NEON 최적화 (vfmaq_f32, 4-wide)
14+
- [ ] `tq_rmsnorm(out, x, weight, n, eps)` — RMS normalization
15+
- [ ] `tq_rope(q, k, pos, head_dim, freq_base)` — Rotary Position Embedding
16+
- [ ] `tq_silu(x, n)` — SiLU activation (in-place)
17+
- [ ] `tq_softmax(x, n)` — Softmax
18+
- [ ] `tq_add(out, a, b, n)` — 벡터 덧셈
19+
- [ ] `tq_mul(out, a, b, n)` — 벡터 곱셈 (element-wise)
20+
- [ ] `include/turboquant/tq_engine.h` — 추론 엔진 헤더
21+
- [ ] `tests/test_ops.cpp` — 연산 단위 테스트
22+
23+
---
24+
25+
## Phase 2: 모델 로더
26+
27+
- [ ] `src/engine/tq_model.c` — safetensors 로더
28+
- [ ] safetensors 헤더 파싱 (JSON 메타데이터)
29+
- [ ] 텐서 데이터 mmap 로드
30+
- [ ] 모델 구조 정의 (tq_model_t)
31+
```c
32+
typedef struct {
33+
int n_layers, n_heads, n_kv_heads, head_dim;
34+
int hidden_dim, intermediate_dim, vocab_size;
35+
float rope_freq_base;
36+
float* token_embedding; // [vocab_size, hidden_dim]
37+
struct { // per layer
38+
float* attn_norm, *ffn_norm;
39+
float* wq, *wk, *wv, *wo;
40+
float* w_gate, *w_up, *w_down;
41+
} layers[];
42+
} tq_model_t;
43+
```
44+
- [ ] `tq_load_model(path)``tq_model_t*`
45+
- [ ] `tq_free_model(model)`
46+
- [ ] `tests/test_model_load.cpp` — 로더 테스트
47+
48+
---
49+
50+
## Phase 3: Transformer Forward Pass
51+
52+
- [ ] `src/engine/tq_transformer.c` — forward pass
53+
- [ ] `tq_forward(model, token, pos, kv_cache)` → logits
54+
- [ ] Attention 블록:
55+
```
56+
x → RMSNorm → Q,K,V projection (matmul)
57+
Q,K → RoPE
58+
K,V → TurboQuant KV cache (quantize + store)
59+
Q × KV_cache → attention scores (integer Q4×Q8!)
60+
scores → softmax → weighted sum of V
61+
→ output projection → residual add
62+
```
63+
- [ ] FFN 블록:
64+
```
65+
x → RMSNorm → gate_proj + up_proj (matmul)
66+
gate → SiLU
67+
gate × up → down_proj (matmul) → residual add
68+
```
69+
- [ ] KV 캐시 통합: `tq_quantize_keys()` 자동 호출
70+
- [ ] `tests/test_forward.cpp` — forward pass 정확도 테스트
71+
72+
---
73+
74+
## Phase 4: 토크나이저
75+
76+
- [ ] `src/engine/tq_tokenizer.c` — BPE 토크나이저
77+
- [ ] tokenizer.json 파싱 (vocab + merges)
78+
- [ ] `tq_encode(text, tokens, max_tokens)` → token count
79+
- [ ] `tq_decode(token_id)` → string
80+
- [ ] 특수 토큰 처리 (BOS, EOS, PAD)
81+
- [ ] `tests/test_tokenizer.cpp` — 토크나이저 테스트
82+
83+
---
84+
85+
## Phase 5: 생성 루프 + CLI
86+
87+
- [ ] `src/engine/tq_generate.c` — autoregressive 생성
88+
- [ ] `tq_generate(model, prompt, config)` → generated text
89+
- [ ] Prefill: 프롬프트 전체 forward
90+
- [ ] Decode: 한 토큰씩 생성
91+
- [ ] Sampling: temperature, top-p
92+
- [ ] 스트리밍: 토큰 생성 즉시 콜백
93+
- [ ] `tools/tq_run.c` — CLI 실행 파일
94+
```bash
95+
tq_run --model model.safetensors --prompt "Hello" --kv-type uniform_4b
96+
```
97+
- [ ] 벤치마크: tok/s 측정
98+
99+
---
100+
101+
## Phase 6: 검증
102+
103+
- [ ] PyTorch 대비 출력 비교 (동일 프롬프트 → 유사 로짓)
104+
- [ ] 속도: CPU 10+ tok/s 달성 확인
105+
- [ ] 메모리: < 2 GB 확인
106+
- [ ] KV 캐시: TurboQuant 양자화 동작 확인
107+
- [ ] 정수 attention: 실제 추론에서 사용 확인
108+
109+
---
110+
111+
## 완료 기준
112+
113+
- [ ] `tq_run --model qwen3.5-0.8b --prompt "What is AI?"` 실행 → 텍스트 생성
114+
- [ ] CPU 10+ tok/s
115+
- [ ] 외부 의존성 0 (libc/libm만)
116+
- [ ] KV 캐시에 TurboQuant uniform_4b 자동 적용
117+
- [ ] 정수 Q4×Q8 attention이 실제 추론에서 동작

0 commit comments

Comments
 (0)