Katana-1B / integrations /LLAMACPP_INTEGRATION.md
OpenBlade's picture
Upload 9 files
bd8d73c verified
|
Raw History Blame Contribute Delete
7.65 kB
# Katana-1.1B (`fuser` / VortexV4) — Integration & Porting Guide
This guide documents how to convert, run, and maintain **Katana-1.1B** inside our patched **llama.cpp** fork or port the architecture to another local inference runtime (Apple Metal / iRun Studio, Vulkan, Candle, MLX, WebGPU, etc.).
For the exact file-by-file, line-by-line C++/CUDA diff inventory against upstream `llama.cpp` (commit `d7bd3bf`, build `b10423`), see [`Integrationpatchspots.txt`](Integrationpatchspots.txt).
---
## 1. Model Specification & Tensor Schema (`model.safetensors`)
`model.safetensors` (`2.28 GiB`, **473 finite tensors**) stores the Katana-1.1B (`VortexV4` / `fuser`) checkpoint at cumulative step `701,000` (`700k` pretraining + `1,000` 4096-context extension steps, `12.02B` tokens seen).
| Parameter | Value | Notes |
| :--- | :--- | :--- |
| Architecture Name | `fuser` (`VortexV4`) | Registered as `LLM_ARCH_FUSER` in `llama.cpp` |
| Parameters | `1,122,571,848` | BF16 weights + FP32 `GaussianMod` parameters |
| Layers (`n_layer`) | `36` | Dense decoder-only blocks |
| Hidden Dim (`d_model`) | `1,536` | Pre-LayerNorm (`eps = 1e-5`, **with bias**) |
| Attention Heads | `24` (`head_dim = 64`) | MHA (`n_head_kv = 24`), fused `qkv` weight `(4608, 1536)` |
| FFN / MLP | `SwiGLU` (`ff = 4,096`) | No bias; `w2(silu(w1(x)) * w3(x))` |
| Context Length | `4,096` | Extended from `1,024` via NTK-aware RoPE |
| Vocabulary | `65,535` | Custom byte-level BPE (`uint16`-safe IDs `0..65534`), tied `lm_head` |
| RoPE Base | `theta = 1,000,000` (`1e12` in GGML) | **CRITICAL:** See Section 3 on `theta^2` parity |
### Safetensors → GGUF Tensor Mapping (`5 + 13 × 36 = 473` tensors)
| Source Key (`model.safetensors`) | GGUF Tensor Name | Shape | Recommended GGUF Dtype |
| :--- | :--- | :--- | :--- |
| `tok_emb.weight` | `token_embd.weight` | `[65535, 1536]` | `F16` |
| `ctx_gate.weight` | `ctx_gate.weight` | `[1536, 1536]` | `F16` |
| `ln_f.weight` / `ln_f.bias` | `output_norm.weight` / `.bias` | `[1536]` | `F32` |
| `lm_head.weight` | `output.weight` | `[65535, 1536]` | Tied / `F16` |
| `blocks.{i}.ln1.{weight,bias}` | `blk.{i}.attn_norm.{weight,bias}` | `[1536]` | `F32` |
| `blocks.{i}.attn.qkv.weight` | `blk.{i}.attn_qkv.weight` | `[4608, 1536]` | `F16` |
| `blocks.{i}.attn.proj.weight` | `blk.{i}.attn_output.weight` | `[1536, 1536]` | `F16` |
| `blocks.{i}.gmod.mu` | `blk.{i}.gaussian_mod.mu` | `[1536]` | **`F32`** (keep FP32) |
| `blocks.{i}.gmod.log_sigma` | `blk.{i}.gaussian_mod.log_sigma` | `[1536]` | **`F32`** (keep FP32) |
| `blocks.{i}.gmod.alpha` / `.beta` | `blk.{i}.gaussian_mod.{alpha,beta}` | `[1]` | **`F32`** (keep FP32) |
| `blocks.{i}.ln2.{weight,bias}` | `blk.{i}.ffn_norm.{weight,bias}` | `[1536]` | `F32` |
| `blocks.{i}.mlp.w1.weight` | `blk.{i}.ffn_gate.weight` | `[4096, 1536]` | `F16` |
| `blocks.{i}.mlp.w3.weight` | `blk.{i}.ffn_up.weight` | `[4096, 1536]` | `F16` |
| `blocks.{i}.mlp.w2.weight` | `blk.{i}.ffn_down.weight` | `[1536, 4096]` | `F16` |
---
## 2. Custom Architectural Mechanisms (Implementation Details)
Every transformer block executes:
```text
h = LayerNorm_1(x)
Q, K, V = split(W_qkv @ h)
Q, K = RoPE_NEOX(Q, K) [+ KaprekarPhase(h_embed)]
a = W_proj @ CausalAttention(Q, K, V)
a = a * GaussianMod(h) <-- gated BEFORE residual add, conditioned on h = ln1(x)
x = x + a
x = x + W_w2(silu(W_w1(LayerNorm_2(x))) * W_w3(LayerNorm_2(x)))
```
### A. Embedding Context Gate (`ctx_gate`)
Applied once right after token embedding lookup:
```python
e = tok_emb(token_ids)
x = e * sigmoid(e @ ctx_gate_weight.T)
```
### B. Gaussian Activation Modulation (`GaussianMod`)
Applied per block inside the attention residual branch, reading `h = ln1(x)` (all `gmod` math runs in FP32):
```python
sigma = exp(log_sigma).clamp_min(1e-3)
z = (h - mu) / sigma
r2 = mean_over_d(z ** 2) # shape: [B, T, 1]
g = exp(-0.5 * r2) # radial Gaussian score in (0, 1]
a = a * (beta + alpha * g)
```
### C. Kaprekar RoPE Phase Rotation (`fuser.kaprekar.mode`)
Our custom `llama.cpp` integration supports three GGUF metadata modes via `fuser.kaprekar.mode`:
- **`"none"` (Recommended / Exact):** Skips the `GGML_OP_FUSER_PHASE_ROT` op. Because training computes a single constant per-(layer, head) phase shift applied identically to both `Q` and `K` across a sequence, it mathematically cancels inside $QK^T$ (`cos((p_q*w + phi) - (p_k*w + phi)) = cos((p_q - p_k)*w)`). Setting `"none"` gives exact training parity, zero host-weight duplication, and requires no custom CUDA/Metal kernel when porting to new backends.
- **`"frozen"`:** Runs the 4-quarter embedding ratio -> Kaprekar 6174 trajectory calculation once at `pos == 0` and holds that `[n_layer, n_head]` phase tensor fixed across subsequent KV-cached decode steps via `ggml_fuser_phase_rot` (`LLAMA_ROPE_TYPE_NEOX` pair convention).
- **`"running"`:** Recomputes phases on every micro-batch (legacy debug mode only — do not use for KV-cache generation, as shifting $Q$'s phase relative to cached $K$ breaks attention alignment).
---
## 3. Crucial Porting Pitfalls (Must-Read for New Backends)
1. **RoPE Frequency Base (`freq_base = theta^2 = 1e12`):**
- Katana's PyTorch RoPE exponent uses `half_dim = head_dim // 2 = 32` (`theta ** (2 * i / 32) = theta ** (i / 16)`), whereas GGML/HuggingFace uses `head_dim = 64` (`theta ** (2 * i / 64) = theta ** (i / 32)`).
- Therefore, set **`fuser.rope.freq_base = 1e12`** (`(1,000,000)^2`) when exporting GGUF or initializing standard HF/GGML RoPE tables. Setting `1e6` instead of `1e12` causes positional decay mismatch at long context.
2. **Standard LayerNorm with Bias (`LLM_NORM`):**
- Katana uses full `LayerNorm` (mean-centered, variance-normalized, with affine `weight` and `bias`), **not** RMSNorm.
3. **GPT-2 Byte-Level BPE Prefix Space (`add_space_prefix`):**
- Set `tokenizer.ggml.model = "gpt2"`, `tokenizer.ggml.pre = "gpt-2"`, `tokenizer.ggml.add_space_prefix = true`, `add_bos_token = false`, `add_eos_token = false`, `bos_token_id = 0`, `eos_token_id = 1`.
- `src/llama-vocab.cpp` is patched to prepend a leading space `' '` when `add_space_prefix` is true and input doesn't start with `' '`, matching `tokenizer.json` parity bit-for-bit.
---
## 4. Building & Running with Custom `llama.cpp`
### Build Custom `llama.cpp` (CUDA)
```bash
cd llamacpp
cmake -B build -DGGML_CUDA=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release -j $(nproc)
```
### Export to GGUF (`fuser` arch)
When converting `model.safetensors` + `tokenizer.json` to `.gguf`, write the following required GGUF metadata keys:
- `general.architecture = "fuser"`
- `fuser.context_length = 4096`, `fuser.embedding_length = 1536`, `fuser.block_count = 36`, `fuser.feed_forward_length = 4096`
- `fuser.attention.head_count = 24`, `fuser.attention.head_count_kv = 24`, `fuser.attention.key_length = 64`, `fuser.attention.value_length = 64`, `fuser.attention.layer_norm_epsilon = 1e-5`
- `fuser.rope.dimension_count = 64`, `fuser.rope.freq_base = 1e12`, `fuser.rope.scaling.type = "none"`
- `fuser.vocab_size = 65535`, `fuser.kaprekar.mode = "none"`
- `tokenizer.ggml.model = "gpt2"`, `tokenizer.ggml.pre = "gpt-2"`, `tokenizer.ggml.add_space_prefix = true`, `bos_token_id = 0`, `eos_token_id = 1`
### Run Inference
```bash
# CLI completion (4096 context, full GPU offload)
./llamacpp/build/bin/llama-cli \
-m katana-1b.gguf \
-c 4096 -ngl 99 \
-p "def binary_search(arr, target):" \
-n 256 --temp 0.6 --top-k 40
# OpenAI-compatible local server
./llamacpp/build/bin/llama-server \
-m katana-1b.gguf \
-c 4096 -ngl 99 --host 127.0.0.1 --port 8080
```