Text Generation
Transformers
Safetensors
lfm2
kv-cache-quantization
2-bit
bq2_0
quantization-aware-training
distillation
llama-cpp
on-device
kleinml
kv1
conversational
custom_code
Eval Results
Instructions to use klein-ml/KV1-1.2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use klein-ml/KV1-1.2B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="klein-ml/KV1-1.2B", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("klein-ml/KV1-1.2B", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("klein-ml/KV1-1.2B", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use klein-ml/KV1-1.2B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "klein-ml/KV1-1.2B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "klein-ml/KV1-1.2B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/klein-ml/KV1-1.2B
- SGLang
How to use klein-ml/KV1-1.2B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "klein-ml/KV1-1.2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "klein-ml/KV1-1.2B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "klein-ml/KV1-1.2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "klein-ml/KV1-1.2B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use klein-ml/KV1-1.2B with Docker Model Runner:
docker model run hf.co/klein-ml/KV1-1.2B
Download kv_ternary.py from klein-ml/KV1-1.2B: direct link, hf CLI and curl.
- Browser
- Download file 8.15 kB
-
https://huggingface.co/klein-ml/KV1-1.2B/resolve/main/kv_ternary.py
- Command line
-
hf download hf://klein-ml/KV1-1.2B/kv_ternary.py
-
curl -L -o kv_ternary.py https://huggingface.co/klein-ml/KV1-1.2B/resolve/main/kv_ternary.py
8.15 kB
| """ | |
| Ternary (3-level, ~1.58-bit) KV-cache quantization-aware training for Hugging Face | |
| transformers attention, in the style of BananaMind KV1. | |
| * Quantizes post-RoPE K and V per token, per KV head, over head_dim (same as KV1). | |
| * mode="affine": levels {min, min+s, min+2s}; fp16 min + fp16 scale per vector (KV1 with qmax=2). | |
| * mode="symmetric": levels {-s, 0, +s}; fp16 absmean scale per vector. | |
| * hadamard=True: orthonormal Hadamard rotation of head_dim before quantizing. Q and K are | |
| rotated together (dot products unchanged); V is quantized in the rotated basis and rotated | |
| back. In full precision this is mathematically identical to the unrotated model. | |
| * Straight-through estimator: forward sees dequantized K/V, backward is identity. | |
| * Codes pack 5 trits per byte (3^5 = 243 <= 256) -> 1.6 bits/value before metadata. | |
| Usage: | |
| import kv_ternary as kvt | |
| kvt.configure(levels=4, mode="affine", hadamard=True, sink=4) | |
| name = kvt.register() # registers a "kv_ternary" attention implementation wrapping sdpa | |
| model = AutoModelForCausalLM.from_pretrained(repo, attn_implementation=name) | |
| Because quantization is per token and independent of history, a forward pass with this | |
| attention gives exactly the outputs of decoding from a packed ternary cache (see pack_kv/unpack_kv). | |
| """ | |
| import math | |
| import torch | |
| import torch.nn.functional as F | |
| STATE = {"enabled": True, "alpha": 1.0, "levels": 4, "mode": "affine", "hadamard": False, "eps": 1e-6, | |
| "sink": 0, "calls": 0} | |
| def configure(**kw): | |
| for k, v in kw.items(): | |
| if k not in STATE: | |
| raise KeyError(f"unknown kv_ternary option {k!r}") | |
| STATE[k] = v | |
| if STATE["mode"] not in ("affine", "symmetric"): | |
| raise ValueError("mode must be 'affine' or 'symmetric'") | |
| if STATE["levels"] not in (3, 4): | |
| raise ValueError("levels must be 4 (2-bit, KV1-8M style) or 3 (ternary)") | |
| if STATE["mode"] == "symmetric" and STATE["levels"] != 3: | |
| raise ValueError("symmetric mode is only defined for levels=3 ({-s, 0, +s})") | |
| # ---------------------------------------------------------------- Hadamard | |
| _H_CACHE = {} | |
| def hadamard_matrix(n, device, dtype): | |
| if n <= 0 or n & (n - 1): | |
| raise ValueError(f"Hadamard rotation needs a power-of-two head_dim, got {n}") | |
| key = (n, str(device), dtype) | |
| H = _H_CACHE.get(key) | |
| if H is None: | |
| H = torch.ones(1, 1, dtype=torch.float64) | |
| while H.size(0) < n: | |
| H = torch.cat([torch.cat([H, H], 1), torch.cat([H, -H], 1)], 0) | |
| H = (H / math.sqrt(n)).to(device=device, dtype=dtype) # symmetric, H @ H = I | |
| _H_CACHE[key] = H | |
| return H | |
| # ---------------------------------------------------------------- quantizer | |
| def quantize_ternary(x, mode="affine", eps=1e-6, levels=None): | |
| """Returns (codes uint8 in {0..levels-1}, min fp16 or None, scale fp16), reducing over the last dim. | |
| levels=4: KV1-8M 2-bit affine (scale = (max-min)/3). levels=3: ternary.""" | |
| levels = STATE["levels"] if levels is None else levels | |
| qmax = levels - 1 | |
| xf = x.float() | |
| if mode == "affine": | |
| mn = xf.amin(-1, keepdim=True) | |
| mx = xf.amax(-1, keepdim=True) | |
| scale16 = ((mx - mn) / qmax).clamp_min(eps).to(torch.float16) | |
| mn16 = mn.to(torch.float16) | |
| codes = ((xf - mn16.float()) / scale16.float()).round().clamp_(0, qmax) | |
| return codes.to(torch.uint8), mn16, scale16 | |
| scale16 = xf.abs().mean(-1, keepdim=True).clamp_min(eps).to(torch.float16) | |
| codes = (xf / scale16.float()).round().clamp_(-1, 1) + 1 | |
| return codes.to(torch.uint8), None, scale16 | |
| def dequantize_ternary(codes, mn16, scale16, mode, dtype): | |
| c = codes.to(dtype) | |
| if mode == "affine": | |
| return c * scale16.to(dtype) + mn16.to(dtype) | |
| return (c - 1) * scale16.to(dtype) | |
| def fake_quant_ternary_ste(x, mode="affine", eps=1e-6, alpha=1.0, levels=None): | |
| with torch.no_grad(): | |
| codes, mn, sc = quantize_ternary(x, mode, eps, levels) | |
| delta = dequantize_ternary(codes, mn, sc, mode, x.dtype) - x | |
| if alpha < 1.0: | |
| delta = delta * alpha | |
| return x + delta | |
| # ---------------------------------------------------------------- packing | |
| # levels=4: 4 x 2-bit codes per byte, byte = c0 + (c1 << 2) + (c2 << 4) + (c3 << 6) (identical to KV1-8M) | |
| # levels=3: 5 trits per byte (3^5 = 243 <= 256) | |
| def packed_dim(d, levels=None): | |
| levels = STATE["levels"] if levels is None else levels | |
| return (d + 3) // 4 if levels == 4 else (d + 4) // 5 | |
| def pack_codes(codes, levels=None): | |
| levels = STATE["levels"] if levels is None else levels | |
| n, base = (4, 4) if levels == 4 else (5, 3) | |
| d = codes.size(-1) | |
| pad = (-d) % n | |
| if pad: | |
| codes = F.pad(codes, (0, pad)) | |
| ch = codes.reshape(*codes.shape[:-1], -1, n).to(torch.int16) | |
| w = torch.tensor([base ** i for i in range(n)], dtype=torch.int16, device=codes.device) | |
| return (ch * w).sum(-1).to(torch.uint8) | |
| def unpack_codes(packed, d, levels=None): | |
| levels = STATE["levels"] if levels is None else levels | |
| n, base = (4, 4) if levels == 4 else (5, 3) | |
| p = packed.to(torch.int16) | |
| parts = [(p // (base ** i)) % base for i in range(n)] | |
| return torch.stack(parts, -1).flatten(-2)[..., :d].to(torch.uint8) | |
| pack_trits, unpack_trits = pack_codes, unpack_codes # backwards-compatible names | |
| def bits_per_value(head_dim, mode="affine", levels=None): | |
| meta_bytes = 4 if mode == "affine" else 2 | |
| return 8 * (packed_dim(head_dim, levels) + meta_bytes) / head_dim | |
| def pack_kv(x, mode=None, eps=None, hadamard=None): | |
| """Packed cache entry for post-RoPE K or V of shape (..., head_dim). Rotated basis if hadamard.""" | |
| mode = STATE["mode"] if mode is None else mode | |
| eps = STATE["eps"] if eps is None else eps | |
| hadamard = STATE["hadamard"] if hadamard is None else hadamard | |
| if hadamard: | |
| x = x @ hadamard_matrix(x.size(-1), x.device, x.dtype) | |
| codes, mn, sc = quantize_ternary(x, mode, eps) | |
| return pack_codes(codes), mn, sc | |
| def unpack_kv(packed, mn, sc, head_dim, dtype, mode=None): | |
| """Dequantized values, still in the rotated basis (rotate Q for K; rotate attn output back for V).""" | |
| mode = STATE["mode"] if mode is None else mode | |
| return dequantize_ternary(unpack_codes(packed, head_dim), mn, sc, mode, dtype) | |
| # ---------------------------------------------------------------- attention hook | |
| def _keep_sinks(xq, x, n): | |
| """Positions [0, n) along the sequence dim keep their unquantized values (attention sinks).""" | |
| if n <= 0: | |
| return xq | |
| n = min(n, x.size(-2)) | |
| return torch.cat([x[..., :n, :], xq[..., n:, :]], dim=-2) | |
| def apply_kv_quant(query, key, value): | |
| s = STATE | |
| if not s["enabled"]: | |
| return query, key, value | |
| s["calls"] += 1 | |
| kw = dict(mode=s["mode"], eps=s["eps"], alpha=s["alpha"]) | |
| if s["hadamard"]: | |
| H = hadamard_matrix(query.size(-1), query.device, query.dtype) | |
| query = query @ H | |
| kr, vr = key @ H, value @ H | |
| key = _keep_sinks(fake_quant_ternary_ste(kr, **kw), kr, s["sink"]) | |
| value = _keep_sinks(fake_quant_ternary_ste(vr, **kw), vr, s["sink"]) @ H | |
| else: | |
| key = _keep_sinks(fake_quant_ternary_ste(key, **kw), key, s["sink"]) | |
| value = _keep_sinks(fake_quant_ternary_ste(value, **kw), value, s["sink"]) | |
| return query, key, value | |
| def register(name="kv_ternary", base="sdpa"): | |
| from transformers import AttentionInterface | |
| from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS | |
| base_fn = ALL_ATTENTION_FUNCTIONS[base] | |
| def kv_ternary_attention(module, query, key, value, attention_mask, **kwargs): | |
| query, key, value = apply_kv_quant(query, key, value) | |
| return base_fn(module, query, key, value, attention_mask, **kwargs) | |
| AttentionInterface.register(name, kv_ternary_attention) | |
| try: # newer transformers build masks per attention implementation | |
| from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS, AttentionMaskInterface | |
| AttentionMaskInterface.register(name, ALL_MASK_ATTENTION_FUNCTIONS[base]) | |
| except Exception: | |
| pass | |
| return name | |