Katana-1B / integrations /Integrationpatchspots.txt
OpenBlade's picture
Upload 9 files
bd8d73c verified
Raw History Blame Contribute Delete
11.7 kB
===============================================================================
KATANA-1.1B ("fuser" / VortexV4) — INTEGRATION & PATCH SPOTS LEDGER
Baseline upstream reference: llama.cpp commit d7bd3bf (build b10423 / v0.22.0)
===============================================================================
Use this checklist whenever rebasing onto a newer upstream llama.cpp release or
porting Katana-1.1B ("fuser") to another inference engine (Metal / iRun Studio,
Vulkan, WebGPU, Candle, MLX, vLLM, ONNX Runtime, etc.).
Total diff footprint in custom llamacpp:
- 1 new model file (src/models/fuser.cpp, 290 lines)
- 18 modified files (475 insertions, 6 deletions across ggml + llama + model)
-------------------------------------------------------------------------------
SECTION A — GGML CORE & CUSTOM OP REGISTRATION (Kaprekar Phase Rotation)
-------------------------------------------------------------------------------
NOTE: Only needed if you support `fuser.kaprekar.mode = "frozen" | "running"`.
When `fuser.kaprekar.mode = "none"`, training-identical attention holds because
the per-sequence constant phase added equally to Q and K cancels out in Q @ K^T.
1. ggml/include/ggml.h
- enum ggml_op (around line 592, right before GGML_OP_COUNT):
Add: `GGML_OP_FUSER_PHASE_ROT,`
- Public C API declaration (around line 1916, near ggml_rope_multi_inplace):
Add: `GGML_API struct ggml_tensor * ggml_fuser_phase_rot(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * phase);`
2. ggml/include/ggml-rpc.h
- Line 10: Bump `RPC_PROTO_PATCH_VERSION` (0 -> 1)
- Line 14: Update `static_assert(GGML_OP_COUNT == 102, ...)` (previous count + 1)
3. ggml/src/ggml.c
- `GGML_OP_NAME[]` table (~line 1101): add `"FUSER_PHASE_ROT",` and bump static_assert `GGML_OP_COUNT == 102`
- `GGML_OP_SYMBOL[]` table (~line 1217): add `"fuser_phase_rot(x, phase)",` and bump static_assert `GGML_OP_COUNT == 102`
- Tensor constructor (~line 4368): implement `ggml_fuser_phase_rot(ctx, a, phase)`
Asserts: `a->type == F32 || F16`, `phase->type == F32`, `phase->ne[0] == a->ne[1]`, `a->ne[0] % 2 == 0`
Sets: `result->op = GGML_OP_FUSER_PHASE_ROT; result->src[0] = a; result->src[1] = phase;`
- `ggml_compute_backward` (~line 7146): add `case GGML_OP_FUSER_PHASE_ROT:` (unimplemented assert)
- `ggml_build_backward_expand` (~line 7323): mark `ignore_src[1] = true;` under `case GGML_OP_FUSER_PHASE_ROT:`
4. ggml/src/ggml-backend-meta.cpp
- `ggml_backend_meta_get_split_state` (~line 973):
Add `case GGML_OP_FUSER_PHASE_ROT: split_state = handle_generic(src_ss, /*scalar_only =*/ false); break;`
-------------------------------------------------------------------------------
SECTION B — BACKEND KERNELS (CPU + CUDA)
-------------------------------------------------------------------------------
5. ggml/src/ggml-cpu/ops.h
- Near line 66 (below `ggml_compute_forward_rope_back`):
Declare: `void ggml_compute_forward_fuser_phase_rot(const struct ggml_compute_params * params, struct ggml_tensor * dst);`
6. ggml/src/ggml-cpu/ops.cpp
- Around line 6153: implement `ggml_compute_forward_fuser_phase_rot<T>` (F16 and F32)
For each (batch i3, seq i2, head i1, half-dim i0 in 0..ne0/2):
phi = phase[i1 % src1->ne[0]]
dst[i0] = x0 * cos(phi) - x1 * sin(phi)
dst[i0 + ne0/2] = x0 * sin(phi) + x1 * cos(phi)
(NEOX half-split pair layout!)
7. ggml/src/ggml-cpu/ggml-cpu.c
- `ggml_compute_forward` switch (~line 1904): dispatch `case GGML_OP_FUSER_PHASE_ROT: ggml_compute_forward_fuser_phase_rot(params, tensor); break;`
- `ggml_get_n_tasks` switch (~line 2364): add `case GGML_OP_FUSER_PHASE_ROT:` so it uses `n_threads`
8. ggml/src/ggml-cuda/rope.cuh
- Line 9: Declare `void ggml_cuda_op_fuser_phase_rot(ggml_backend_cuda_context & ctx, ggml_tensor * dst);`
9. ggml/src/ggml-cuda/rope.cu
- Lines 708-790: Implement CUDA kernel `fuser_phase_rot<T, D>` + host launcher `ggml_cuda_op_fuser_phase_rot`
Supports `GGML_TYPE_F32` and `GGML_TYPE_F16`; rotates NEOX pairs `(ipair, ipair + hd)` by `phases[i1]`.
10. ggml/src/ggml-cuda/ggml-cuda.cu
- `ggml_cuda_compute_forward` switch (~line 2303):
Add `case GGML_OP_FUSER_PHASE_ROT: GGML_ASSERT(ggml_nrows(dst) > 0); ggml_cuda_op_fuser_phase_rot(ctx, dst); break;`
(If porting to Metal / Vulkan / other GPU backends: add the matching 20-line NEOX
pair-rotation shader implementing `out[i] = x[i]*cos(phase[h]) - x[i+hd]*sin(phase[h])`
and `out[i+hd] = x[i]*sin(phase[h]) + x[i+hd]*cos(phase[h])` if using frozen/running Kaprekar.)
-------------------------------------------------------------------------------
SECTION C — LLAMA ARCHITECTURE, TENSORS & GRAPH WIRING
-------------------------------------------------------------------------------
11. src/llama-arch.h
- `enum llm_arch` (~line 162, right before `LLM_ARCH_UNKNOWN`):
Add: `LLM_ARCH_FUSER,`
- `enum llm_tensor` (~line 704):
Add:
`LLM_TENSOR_CTX_GATE,`
`LLM_TENSOR_GAUSSIAN_MOD,`
`LLM_TENSOR_KAPREKAR_PHASE,`
12. src/llama-arch.cpp
- `LLM_ARCH_NAMES` (~line 157): `{ LLM_ARCH_FUSER, "fuser" },`
- `LLM_TENSOR_NAMES` (~line 697):
`{ LLM_TENSOR_CTX_GATE, "ctx_gate" },`
`{ LLM_TENSOR_GAUSSIAN_MOD, "blk.%d.gaussian_mod" },`
`{ LLM_TENSOR_KAPREKAR_PHASE, "kaprekar_phase" },`
- `LLM_TENSOR_INFOS` (~line 989):
`{ LLM_TENSOR_CTX_GATE, { LLM_TENSOR_LAYER_INPUT, GGML_OP_MUL_MAT } },`
`{ LLM_TENSOR_GAUSSIAN_MOD, { LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL } },`
`{ LLM_TENSOR_KAPREKAR_PHASE, { LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL } },`
CRITICAL: Without non-NONE GGML_OP entries in LLM_TENSOR_INFOS, llama-model-loader
drops the tensors with "unused tensor -- ignoring".
13. src/llama-model.h
- `struct llama_layer` (~line 306):
`struct ggml_tensor * gaussian_mu = nullptr;`
`struct ggml_tensor * gaussian_log_sigma = nullptr;`
`struct ggml_tensor * gaussian_alpha = nullptr;`
`struct ggml_tensor * gaussian_beta = nullptr;`
- `struct llama_model` (~line 638):
`struct ggml_tensor * ctx_gate = nullptr;`
`struct ggml_tensor * kaprekar_phase = nullptr;`
14. src/llama-model.cpp
- `llama_model_mapping` factory switch (~line 339):
`case LLM_ARCH_FUSER: return new llama_model_fuser(params);`
- `llama_model_rope_type` switch (~line 2938):
`case LLM_ARCH_FUSER: return LLAMA_ROPE_TYPE_NEOX;`
15. src/models/models.h
- Line 9: `#include <vector>`
- Around line 489: declare `struct llama_model_fuser : public llama_model_base`
with `tok_embd_host`, `ctx_gate_host`, `kap_S[4]`, `kap_M[4]`, `kap_N`, `kap_mode`,
`kap_phase`, `kap_phase_valid`, and `struct graph : public llm_graph_context`.
16. src/models/fuser.cpp [NEW FILE — 290 lines]
- `fuser_load_host(...)`: host FP32 dequantizer for F32/F16/BF16/Q8_0 (when `kap_mode != 0`)
- `llama_model_fuser::load_arch_hparams`: reads `LLM_KV_ATTENTION_LAYERNORM_EPS` and `fuser.kaprekar.mode`
- `llama_model_fuser::load_arch_tensors`: loads `token_embd`, `ctx_gate`, `output_norm`+bias,
tied `output`, per-layer `attn_norm`+bias, fused `attn_qkv`, `attn_output`, `ffn_norm`+bias,
`ffn_gate`/`ffn_down`/`ffn_up`, and `gaussian_mod.{mu,log_sigma,alpha,beta}`
- `llama_model_fuser::graph::graph`:
* `inpL = build_inp_embd(model.tok_embd)`
* `ctx_gate`: `inpL = inpL * sigmoid(ctx_gate @ inpL)`
* Layer loop (il = 0..35):
- `cur = build_norm(..., LLM_NORM, il)` -> LayerNorm WITH bias (`attn_norm_out = cur`)
- `Qcur, Kcur, Vcur = build_qkv(...)`
- `Qcur/Kcur = ggml_rope_ext(..., LLAMA_ROPE_TYPE_NEOX, ...)`
- if `kap != nullptr`: `ggml_fuser_phase_rot(Qcur/Kcur, kap->phase[il])`
- `cur = build_attn(...)`
- `GaussianMod` BEFORE residual add (receives `attn_norm_out`):
`sigma = clamp(exp(log_sigma), 1e-3, FLT_MAX)`
`r2 = mean_d(((attn_norm_out - mu) / sigma)^2)`
`cur = cur * (beta + alpha * exp(-0.5 * r2))`
- `ffn_inp = cur + inpSA`
- `cur = build_ffn(build_norm(ffn_inp, ..., LLM_NORM, il), ..., LLM_FFN_SILU, LLM_FFN_PAR, il)`
- `inpL = cur + ffn_inp`
* Final `build_norm(inpL, LLM_NORM)` -> tied `build_lora_mm(model.output, cur)`
17. src/llama-graph.h
- Lines 164-201: Declare `class llm_graph_input_fuser_kaprekar : public llm_graph_input_i`
implementing `set_input(const llama_ubatch *)` and `can_reuse(...)`.
18. src/llama-graph.cpp
- Lines 129-277: Implement `llm_graph_input_fuser_kaprekar::set_input`
- Computes `ctx_gate @ tok_emb` -> `e * sigmoid(g)` -> 4 quarter `mean(|e|)/max(|e|)` ->
repdigit bump -> 4-digit Kaprekar trajectory (`6174` fixed point <=7 steps) ->
per-(layer, head) phases in `[n_layer * n_head]`.
- Supports `mode == 1` (`frozen`, compute once at `pos == 0`) and `mode == 2` (`running`).
-------------------------------------------------------------------------------
SECTION D — TOKENIZER & BPE PATCHES
-------------------------------------------------------------------------------
19. src/llama-vocab.cpp
- `llm_tokenizer_bpe_session::tokenize` (~lines 605-616):
When `vocab.get_add_space_prefix()` is true (GPT-2 ByteLevel style) and input
`text` is non-empty and does not start with `' '`, prepend `' '` before `unicode_regex_split`.
- `llama_vocab::impl::load` (~line 2878):
Recognize `t.first == "<|eos|>"` as an EOG token automatically.
-------------------------------------------------------------------------------
SECTION E — GGUF / THIRD-PARTY PORTING INVARIANTS (CRITICAL PITFALLS)
-------------------------------------------------------------------------------
1. RoPE frequency base mismatch (`freq_base = theta^2`):
- Katana's PyTorch reference defines `inv_freq = 1 / theta^(2*i / half_dim)` where `half_dim = head_dim / 2 = 32`, i.e., exponent is `i / 16` (`2*i / 32`).
- Standard GGML / HuggingFace RoPE defines `theta^(-2*i / head_dim)` where exponent is `i / 32` (`2*i / 64`).
- Therefore, any standard GGUF / HF / Metal runtime MUST set `rope.freq_base = raw_theta^2 = (1e6)^2 = 1e12` (unless you override `inv_freq` calculation to match `theta^(i/16)` directly). Missing this breaks multi-token coherence and long-context retrieval!
2. GaussianMod placement & precision:
- Inputs come from `ln1(x)` (NOT residual `x`), and the scalar `(beta + alpha * exp(-0.5 * r2))` scales attention output `a` BEFORE adding the residual `x + a`.
- Keep `gaussian_mod.{mu, log_sigma, alpha, beta}` and `exp/div` math in **FP32**; clamping `exp(log_sigma) >= 1e-3f` prevents division-by-zero in half precision.
3. LayerNorm WITH bias:
- Katana uses `nn.LayerNorm` (mean subtraction + variance norm + weight + bias), i.e., `LLM_NORM` — NOT RMSNorm (`LLM_NORM_RMS`).
4. SwiGLU projection order (`w1`, `w3`, `w2`):
- In PyTorch (`model.safetensors`): `w2(silu(w1(x)) * w3(x))`.
- Map `w1 -> ffn_gate`, `w3 -> ffn_up`, `w2 -> ffn_down`.
5. Tokenizer edge cases:
- `vocab_size = 65535` (max token id `65534` for uint16 efficiency).
- Special tokens: `<|bos|> = 0`, `<|eos|> = 1` (control token type `3`). Guard duplicate special strings at slots `256`/`257` when converting `tokenizer.json` to GGUF (`<|unused_256|>`, `<|unused_257|>`).
- `add_space_prefix = true`, `add_bos_token = false`, `add_eos_token = false`.
===============================================================================