A compact, efficiently quantized BitNet b1.58 ternary model optimized for edge deployment. This repository provides a plug-and-play GGUF file ready for use with llama.cpp and its ecosystem (llama-cli, llama-cpp-python, text-generation-webui, and more).
⚠️ IMPORTANT — PLEASE READ: This model does NOT run with the standard llama.cpp. It requires a patched bitnet.cpp (see below). Without the patch, you will encounter missing tensor 'blk.0.attn_sub_norm.weight' or similar errors. The BitNet folder contains benchmark and automatic installation scripts & fixes for known problems during the installation of Python Torch and sentencepiece from python3.13/sitepackages.
ik_llama
This repository is a fork of llama.cpp with better CPU and hybrid GPU/CPU performance, new SOTA quantization types, // first-class Bitnet // support, better DeepSeek performance via MLA,
FlashMLA, fused MoE operations and tensor overrides for hybrid GPU/CPU inference, row-interleaved quant packing, etc.
llama.cpp built from source with BitNet support (commit 52b3df002 or later), OR
llama-cpp-python v0.3.x+
Usage with llama-cli
bash
1# Basic text generation2./llama-cli -m quantized_q4km.gguf \3 -p "Explain quantum computing in simple terms"\4 -n 256\5 -t 4\6 --temp 0.7\7 --top-p 0.989# Chat mode10./llama-cli -m quantized_q4km.gguf \11 -p "You are a helpful assistant."\12 --chat-template gemma \13 -n 512\14 -t 4
Usage with llama-cpp-python (Python)
bash
1from llama_cpp import Llama
23llm = Llama(4model_path="quantized_q4km.gguf",
5n_ctx=8192,
6n_threads=4,
7verbose=False,
8)910output = llm(11"What is the meaning of life?",
12max_tokens=256,
13temperature=0.7,
14top_p=0.9,
15echo=False,
16)1718print(output["choices"][0]["text"])
Usage with text-generation-webui
Place quantized_q4km.gguf in the models/ directory.
Launch text-generation-webui with --model quantized_q4km.gguf.
Select the model in the UI under the "Model" tab.
Usage with LangChain
bash
1from langchain_community.llms import LlamaCpp
23llm = LlamaCpp(4model_path="quantized_q4km.gguf",
5n_ctx=8192,
6n_threads=4,
7temperature=0.7,
8top_p=0.9,
9verbose=False,
10)1112response = llm.invoke("Write a short poem about AI.")13print(response)
Performance
bash
1# SLM750-Edge: A 1.58-Bit Hybrid Edge Transformer2## Architectural Mathematics & Training Protocol34### "Null-Denkzeit für Tool-Calls. >120 tok/s auf mobiler Hardware."56---
78## 1. Design Philosophy910SLM750-Edge combines three revolutionary advances:
11121. **Hybrid Gemma-2/SmolLM2 architecture** — interleaved local+global attention with Gemma-2's logit softcapping, optimized to 750M
132. **BitNet b1.58 native quantization** — all weights constrained to {−1, 0, +1} during training, eliminating FP multiplications at inference
143. **GBNF grammar ejection** — tool-calling structure is *baked into the token distribution* so no CoT or post-processing is needed
1516**Result:** A 750M model that fits in142 MB at 1.58-bit (≈ 750M × 1.58 bits ÷ 8=148 MB), runs entirely in CPU cache on modern phone SoCs, and produces guaranteed-JSON tool calls at wire speed.
1718---
1920## 2. Architecture Blueprint2122### 2.1 Macro Architecture23
**Why:** Global at even layers captures long-range tool dependencies (passing variables between steps 1→8). Sliding window at odd layers provides 1024-token burst resolution for dense JSON structures.
### 4.2 Logit Softcapping (Gemma-2 Innovation)
After attention score computation and before softmax:
$$S'_{ij} = C_{\text{attn}} \cdot \tanh\left(\frac{S_{ij}}{C_{\text{attn}}}\right) \quad \text{where} \quad C_{\text{attn}} = 50$$
After the final FFN output projection:
$$Y' = C_{\text{final}} \cdot \tanh\left(\frac{Y}{C_{\text{final}}}\right) \quad \text{where} \quad C_{\text{final}} = 30$$
**Effect:** Prevents attention from becoming too diffuse or too peaked, critical for stable ternary training.
### 4.3 RoPE with Extended Frequency Scale
Using SmolLM2's RoPE implementation with base $f = 10000$:
$$\Theta = \{\theta_i = 10000^{-2i/d}\}_{i=0}^{d/2-1}$$
Extended to 8192 via linear frequency scaling (NTK-aware):
$$\theta'_i = \theta_i \cdot s^{-\frac{2i}{d}} \quad \text{where} \quad s = \frac{8192}{2048} = 4$$
---
## 5. ReLU² Feed-Forward Network
SmolLM2-style FFN with squared ReLU activation:
$$\text{FFN}(x) = W_{\text{down}} \cdot \left(\text{ReLU}(W_{\text{up}} \cdot x)^2 \odot W_{\text{gate}} \cdot x\right)$$
Where $\odot$ is element-wise multiplication (SwiGLU-style gating but with ReLU²).
**Rationale:** ReLU² produces sparser activations than GELU/SwiGLU at the same FLOPs, which synergizes with ternary weights — more zero activations mean more zero-selects in the INT8 adder tree.
---
## 6. Knowledge Distillation Protocol
### 6.1 Teacher-Student Setup
| Role | Model | Parameters | Format |
|------|-------|------------|--------|
| **Teacher (Reasoning)** | Gemma-2-2B (Open) | 2.6B | FP16, full precision |
| **Teacher (Tool Structure)** | LFM2-1.2B-Tool | 1.2B | Q4_K_M GGUF |
| **Student** | SLM750-Edge | 749M | 1.58-bit ternary |
### 6.2 Distillation Loss
$$\mathcal{L} = \lambda_1 \cdot \mathcal{L}_{\text{CE}}(y_s, y_t) + \lambda_2 \cdot \mathcal{L}_{\text{KD}}(p_s, p_t) + \lambda_3 \cdot \mathcal{L}_{\text{struct}}(z_s, z_t)$$
Where:
- $\mathcal{L}_{\text{CE}}$ is standard cross-entropy on hard labels
- $\mathcal{L}_{\text{KD}} = T^2 \cdot \text{KL}(p_s/T \parallel p_t/T)$ is distilled soft logits (temperature $T=4$)
- $\mathcal{L}_{\text{struct}}$ is a structured output loss comparing JSON AST trees via tree-edit distance
- $\lambda_1 = 0.3, \lambda_2 = 0.5, \lambda_3 = 0.2$
### 6.3 Namespace Correction (Online Patch)
During distillation data generation, the LFM2 teacher produces actions with incorrect namespaces (e.g., `data_science_engineering.create_post` instead of `HR.Recruiting.CreateJobPosting`). We apply a **dynamic namespace projection**:
1. Parse JSON output from LFM2 teacher
2. Extract action tuples (namespace, function)
3. Project through a similarity-weighted lookup table built from the ground-truth dataset:
$$(n_s, f_s) \rightarrow \arg\max_{(n_t, f_t) \in \mathcal{G}} \text{sim}(n_s, n_t) \cdot \text{sim}(f_s, f_t)$$
4. Rewrite the JSON with corrected namespaces **in RAM** before feeding to student
This table is constructed offline from the 2000 training samples before distillation begins.
---
## 7. GBNF Grammar for Guaranteed Tool-Call JSON
The inference grammar is compiled into a DAG that the sampler follows token-by-token:
```gbnf
root ::= "{\"actions\": " actions-array ", \"dependencies\": " dep-array ", \"variable_chain\": " vc-array "}"
actions-array ::= "[" action (", " action)* "]"
action ::= "{" ws "\"step\":" ws number ws "," ws
"\"namespace\":" ws string ws "," ws
"\"function\":" ws string ws "," ws
"\"params\":" ws object ws "," ws
"\"depends_on\":" ws array ws "," ws
"\"output_refs\":" ws (object | array) ws "," ws
"\"rollback_ref\":" ws (string | "null") ws "," ws
"\"condition\":" ws string ws "}"
At inference time, this grammar is compiled by llama.cpp's GBNF engine into a deterministic pushdown automaton. The sampler never proposes a token outside the grammar, producing 100% valid JSON on the first sampled sequence.
Key insight: Because the model was trained with 1.58-bit quantization and on grammar-structured data, the ternary weights learn to assign high probability only to grammar-valid token sequences. The grammar acts as a safety net — the model rarely needs it because the distribution is already near-deterministic for tool calls.
Batch size: 32 sequences × 2048 tokens (reduced due to teacher memory)
Gradient clipping: max_norm=1.0
8.3 Phase 3: Studio-Fine (1000 steps)
Freeze all BitLinear scales ($\alpha$)
Unfreeze only the LM head and embedding layer
Fine-tune with GBNF-constrained outputs as training targets
Learning rate: 5e-5 constant
8.4 Inference Deployment
1. Export: W_q (ternary) + α (FP16 per-channel) + embeddings → GGUF
2. Integrate GBNF grammar with llama.cpp grammar engine
3. Compile with:
- ARM NEON dot-product kernel for ternary×INT8 matmul
- FlashAttention-2 for sliding window + global attention
- Prefill: >120 tok/s on Snapdragon 8 Gen 3 (4x Cortex-A720)
- Decode: >60 tok/s (single token at a time, bandwidth-bound)
10. Code Map
File
Purpose
bitnet_linear.py
BitLinear layer with STE ternary quantization
slm750_model.py
Full 750M hybrid architecture with SubLN
distill_train.py
Knowledge distillation loop with Gemma-2 teacher
namespace_fix.py
Dynamic namespace correction table builder
tool_grammar.gbnf
GBNF grammar for tool-call JSON
gather_training_data.py
Generate distilled dataset from LFM2 teacher
Key Architectural Features
bash
1Component Specification
2Weight Precision Ternary {-1, 0, +1}(training), Q4_K_M (storage)3FFN Activation ReLU² (relu(x)²)4Attention Grouped-Query Attention (GQA), 12 heads, 4 KV heads
5Positional Encoding RoPE (Rotary Position Embeddings)6Normalization RMSNorm (epsilon = 1e-6)7Logit Softcapping Attention: 50.0, Final: 30.0(tanh-based)8Context Length 8,192 tokens
9Quantization Format
10The model is quantized using Q4_K_M (4-bit K-quant, medium size):
11File type: LLAMA_FTYPE_MOSTLY_Q4_K_M (15)12BPW: 5.27 bits per weight (including overhead)13Compression ratio: ~6:1 vs. full precision
14Method: llama.cpp llama-quantize with --allow-requantize
Compatibility
bash
1Supported Runtimes
2Runtime Status Notes
3llama.cpp (mainline) ✅ Full Requires LLM_ARCH_BITNET support (commit 52b3df002+)4llama-cpp-python ✅ Full v0.3.x+ with BitNet support
5text-generation-webui ✅ Full Via llama.cpp backend
6LangChain ✅ Full Via LlamaCpp wrapper
7Ollama ⚠️ Manual Requires custom Modelfile; not officially supported
8llama-cpp.server ✅ Full OpenAI-compatible API server
Known Limitations
GPU offloading is not supported for BitNet architectures in the current llama.cpp release — all inference runs on CPU.
Flash Attention is not compatible with the BitNet attention implementation.
Batch inference (parallel decoding) is limited by the CPU-only constraint.