Text Generation
Transformers
English
multilingual
inkling2_loop
image-text-to-text
prime-quant
2-bit
4-bit precision
Mixture of Experts
inkling-2
inkling-2-mini
looped-transformer
triton
rocm
cuda
quantization
coding
openai-compatible
conversational
Instructions to use batteryphil/Inkling-2-Mini-PRIME-Quant with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="batteryphil/Inkling-2-Mini-PRIME-Quant") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("batteryphil/Inkling-2-Mini-PRIME-Quant") model = AutoModelForMultimodalLM.from_pretrained("batteryphil/Inkling-2-Mini-PRIME-Quant", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.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(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "batteryphil/Inkling-2-Mini-PRIME-Quant" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "batteryphil/Inkling-2-Mini-PRIME-Quant", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/batteryphil/Inkling-2-Mini-PRIME-Quant
- SGLang
How to use batteryphil/Inkling-2-Mini-PRIME-Quant 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 "batteryphil/Inkling-2-Mini-PRIME-Quant" \ --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": "batteryphil/Inkling-2-Mini-PRIME-Quant", "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 "batteryphil/Inkling-2-Mini-PRIME-Quant" \ --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": "batteryphil/Inkling-2-Mini-PRIME-Quant", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with Docker Model Runner:
docker model run hf.co/batteryphil/Inkling-2-Mini-PRIME-Quant
Add model card, Bartsch LICENSE, Apache-2.0 NOTICE, tokenizer, standalone read-only Triton runtime & verified benchmarks
Browse files- .gitattributes +1 -0
- LICENSE +108 -0
- NOTICE +17 -0
- README.md +161 -0
- benchmarks/formula_parser_looptop8.py +230 -0
- benchmarks/formula_parser_v2_16k.py +335 -0
- benchmarks/inkling2_looptop8_report.json +193 -0
- benchmarks/kld_looptop8.json +53 -0
- benchmarks/kld_p2_gptq.json +53 -0
- benchmarks/kld_p2_maxcomp.json +53 -0
- benchmarks/spreadsheet_engine_looptop8.py +230 -0
- benchmarks/test_spreadsheet_engine.py +276 -0
- benchmarks/verified_results.json +120 -0
- chat_template.jinja +137 -0
- config.json +118 -0
- generation_config.json +6 -0
- inkling2_kernels.py +715 -0
- prime_infer_runtime.py +1265 -0
- processor_config.json +25 -0
- requirements.txt +4 -0
- run_inkling2_prime.py +859 -0
- special_tokens_map.json +21 -0
- tiktoken/tokenizer.model +3 -0
- tokenizer.json +3 -0
- tokenizer_config.json +548 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BARTSCH PERSONAL-FREE & 5% COMMERCIAL PROFIT-SHARE LICENSE
|
| 2 |
+
Version 1.0 — November 2026
|
| 3 |
+
SPDX-License-Identifier: LicenseRef-Bartsch-Personal-Free-5Pct-Commercial
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2026 Philip Bartsch (@batteryphil, https://github.com/batteryphil).
|
| 6 |
+
All rights reserved except as expressly granted below.
|
| 7 |
+
|
| 8 |
+
This License governs all original source code, Triton/GPU inference kernels,
|
| 9 |
+
PyTorch runtime modules, Prime-Harmonic quantization codecs (PRIME-Quant
|
| 10 |
+
P2_G32 / Q2_G32 / P4_G32 / P4_G64), SafeTensors v2 quantized checkpoint layouts,
|
| 11 |
+
and original weight quantization representations authored by Philip Bartsch
|
| 12 |
+
(collectively, the "Covered Work"). Third-party upstream base model weights remain subject to their
|
| 13 |
+
respective upstream licenses as documented in the accompanying NOTICE file.
|
| 14 |
+
|
| 15 |
+
================================================================================
|
| 16 |
+
1. DEFINITIONS
|
| 17 |
+
================================================================================
|
| 18 |
+
|
| 19 |
+
1.1 "Licensor" means Philip Bartsch (@batteryphil).
|
| 20 |
+
|
| 21 |
+
1.2 "Individual Non-Commercial User" means:
|
| 22 |
+
(a) a natural person using the Covered Work solely for personal, hobbyist,
|
| 23 |
+
private study, academic research, or non-monetized open-science
|
| 24 |
+
purposes; or
|
| 25 |
+
(b) an accredited educational institution or registered non-profit
|
| 26 |
+
charitable/research organization (such as a U.S. 501(c)(3) or
|
| 27 |
+
international equivalent) using the Covered Work solely for non-profit
|
| 28 |
+
research or educational instruction, without commercial monetization.
|
| 29 |
+
|
| 30 |
+
1.3 "Commercial Entity" means any corporation, limited liability company,
|
| 31 |
+
partnership, sole proprietorship, startup, enterprise, or other for-profit
|
| 32 |
+
organization, OR any individual who uses, hosts, embeds, distributes, or
|
| 33 |
+
deploys the Covered Work (or any derivative thereof) in connection with a
|
| 34 |
+
revenue-generating product, paid API, SaaS platform, commercial hardware or
|
| 35 |
+
edge device, paid client engagement, or internal for-profit business
|
| 36 |
+
operations.
|
| 37 |
+
|
| 38 |
+
1.4 "Attributable Net Profit" means all gross commercial revenue, subscription
|
| 39 |
+
fees, API usage fees, licensing fees, hardware/device margins, or direct
|
| 40 |
+
monetization proceeds received by a Commercial Entity from products,
|
| 41 |
+
services, or deployments that incorporate, execute, or are trained/modified
|
| 42 |
+
using the Covered Work, minus documented direct third-party compute,
|
| 43 |
+
hosting, or manufacturing cost of goods sold (COGS) directly incurred to
|
| 44 |
+
deliver that specific product or service.
|
| 45 |
+
|
| 46 |
+
================================================================================
|
| 47 |
+
2. FREE LICENSE FOR INDIVIDUALS & NON-COMMERCIAL USE (0% ROYALTY)
|
| 48 |
+
================================================================================
|
| 49 |
+
|
| 50 |
+
Licensor hereby grants to every Individual Non-Commercial User a perpetual,
|
| 51 |
+
worldwide, royalty-free, no-charge, non-exclusive license to use, run, study,
|
| 52 |
+
modify, benchmark, and redistribute the Covered Work (with or without
|
| 53 |
+
modifications) for non-commercial purposes, provided that:
|
| 54 |
+
|
| 55 |
+
(a) This LICENSE file and the accompanying NOTICE file are retained intact in
|
| 56 |
+
all copies, forks, and redistributions of the Covered Work; and
|
| 57 |
+
(b) Clear attribution to Philip Bartsch (@batteryphil) and a link to the
|
| 58 |
+
canonical repository are included in any public release, paper, or
|
| 59 |
+
documentation utilizing the Covered Work.
|
| 60 |
+
|
| 61 |
+
================================================================================
|
| 62 |
+
3. COMMERCIAL & CORPORATE LICENSE (5% PROFIT SHARE)
|
| 63 |
+
================================================================================
|
| 64 |
+
|
| 65 |
+
Licensor hereby grants to any Commercial Entity a worldwide, non-exclusive
|
| 66 |
+
license to use, modify, embed, host (including closed-source products, SaaS,
|
| 67 |
+
APIs, and embedded/edge hardware), and commercially distribute the Covered Work,
|
| 68 |
+
strictly conditioned upon full compliance with ALL of the following terms:
|
| 69 |
+
|
| 70 |
+
(a) Five Percent (5%) Profit Share: The Commercial Entity shall pay to
|
| 71 |
+
Licensor five percent (5%) of all Attributable Net Profit generated from
|
| 72 |
+
any commercial product, hosted service, API, hardware device, or
|
| 73 |
+
for-profit deployment utilizing the Covered Work (or models trained,
|
| 74 |
+
quantized, compressed, or modified using the Covered Work).
|
| 75 |
+
|
| 76 |
+
(b) Notification & Quarterly Accounting: Within thirty (30) days of first
|
| 77 |
+
commercial deployment or first commercial revenue (whichever occurs
|
| 78 |
+
earlier), the Commercial Entity must notify Licensor via GitHub
|
| 79 |
+
(https://github.com/batteryphil) by opening a "[Commercial 5% License
|
| 80 |
+
Registration]" notice or executing a direct payment schedule with
|
| 81 |
+
Licensor. Profit-share statements and payments shall be remitted within
|
| 82 |
+
thirty (30) days following the close of each calendar quarter in which
|
| 83 |
+
Attributable Net Profit exceeds USD $1,000.
|
| 84 |
+
|
| 85 |
+
(c) Internal Non-Revenue R&D Evaluation Grace Period: A Commercial Entity may
|
| 86 |
+
internally evaluate and benchmark the Covered Work for up to sixty (60)
|
| 87 |
+
days prior to production or commercial deployment without fee.
|
| 88 |
+
|
| 89 |
+
(d) Optional Flat-Fee Enterprise Buyout: Commercial Entities preferring a
|
| 90 |
+
fixed annual or perpetual flat-fee buyout in lieu of the 5% profit share
|
| 91 |
+
may negotiate a separate written Enterprise License Agreement directly
|
| 92 |
+
with Philip Bartsch (@batteryphil).
|
| 93 |
+
|
| 94 |
+
(e) Automatic Termination on Breach: Any commercial use by a Commercial Entity
|
| 95 |
+
that fails to honor Section 3(a)-(b) automatically terminates all rights
|
| 96 |
+
granted under this Section 3 until cured in writing with Licensor.
|
| 97 |
+
|
| 98 |
+
================================================================================
|
| 99 |
+
4. NO WARRANTY & LIMITATION OF LIABILITY
|
| 100 |
+
================================================================================
|
| 101 |
+
|
| 102 |
+
THE COVERED WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 103 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
| 104 |
+
FOR A PARTICULAR PURPOSE, ACCURACY, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 105 |
+
AUTHOR OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY,
|
| 106 |
+
WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR
|
| 107 |
+
IN CONNECTION WITH THE COVERED WORK OR THE USE OR OTHER DEALINGS IN THE COVERED
|
| 108 |
+
WORK.
|
NOTICE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-Party Upstream Model & Attribution Notices
|
| 2 |
+
|
| 3 |
+
This repository contains **original PRIME-Quant inference software, fused Triton GPU kernels, Prime-Harmonic `P2_G32` / `P4_G32` quantization representations, and compressed SafeTensors v2 checkpoints** Copyright (c) 2026 Philip Bartsch (`@batteryphil`), licensed under the **[Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0](LICENSE)**.
|
| 4 |
+
|
| 5 |
+
The quantized weights are derived from the following third-party upstream pre-trained model, whose upstream license and attribution notice apply independently to the underlying upstream model weights and tokenizer/configuration assets:
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## `thinkingmachines/Inkling-2-Mini`
|
| 10 |
+
- **Upstream Source:** [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
|
| 11 |
+
- **Model Provider:** Thinking Machines Lab, Inc. (released November 20, 2026)
|
| 12 |
+
- **Upstream License:** **Apache License 2.0** (`https://www.apache.org/licenses/LICENSE-2.0`)
|
| 13 |
+
- **Upstream Acceptable Use Policy:** [Thinking Machines Model Acceptable Use Policy](https://thinkingmachines.ai/model-acceptable-use-policy/)
|
| 14 |
+
- **Modifications Made:**
|
| 15 |
+
- Weights quantized from Thinking Machines' `20.16 GB` NVFP4/MXFP8 (`52.8 GB` BF16-dequantized) checkpoint into `PRIME-Quant` signed-scale Prime-Harmonic 2-bit (`P2_G32`) and 4-bit (`P4_G32`) SafeTensors v2 checkpoints (`inkling2_mini_p2_looptop8.safetensors` at `10.87 GB`, and `inkling2_mini_p2_maxcomp.safetensors` at `8.83 GB`).
|
| 16 |
+
- Removed the upstream `quantization_config` (`modelopt`/`NVFP4`) stanza from `config.json` to prevent spurious loader warnings when hydrating `PRIME-Quant` checkpoints into `Inkling2LoopForConditionalGeneration`.
|
| 17 |
+
- Bundled standalone read-only Triton/PyTorch inference runtime (`prime_infer_runtime.py`, `inkling2_kernels.py`, `run_inkling2_prime.py`).
|
README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: bartsch-personal-free-5pct-commercial
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
base_model: thinkingmachines/Inkling-2-Mini
|
| 6 |
+
base_model_relation: quantized
|
| 7 |
+
library_name: transformers
|
| 8 |
+
pipeline_tag: text-generation
|
| 9 |
+
language:
|
| 10 |
+
- en
|
| 11 |
+
- multilingual
|
| 12 |
+
tags:
|
| 13 |
+
- prime-quant
|
| 14 |
+
- 2-bit
|
| 15 |
+
- 4-bit
|
| 16 |
+
- moe
|
| 17 |
+
- inkling-2
|
| 18 |
+
- inkling-2-mini
|
| 19 |
+
- looped-transformer
|
| 20 |
+
- triton
|
| 21 |
+
- rocm
|
| 22 |
+
- cuda
|
| 23 |
+
- quantization
|
| 24 |
+
- coding
|
| 25 |
+
---
|
| 26 |
+
|
| 27 |
+
# Inkling-2-Mini — PRIME-Quant (`8.83 GB` All-2-Bit MoE & `10.87 GB` `loop_top8` P2/P4 Hybrid)
|
| 28 |
+
|
| 29 |
+
**Run Thinking Machines' `26.4B` 3-Pass Looped MoE (`Inkling-2-Mini`) 100% resident on a single 12 GB or 16 GB consumer GPU at `52–56 tok/s` — zero CPU offload, up to `16K` context on 16 GB VRAM.**
|
| 30 |
+
|
| 31 |
+
Upstream [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini) ships as a `20.16 GB` NVFP4+MXFP8 checkpoint (`52.8 GB` BF16-dequantized) with **32 GB+ VRAM recommended**. **PRIME-Quant** compresses **`99.85%`** (`26.35B / 26.39B`) of its parameters using signed-scale Prime-Harmonic 2-bit (`P2_G32`, `2.50 bpw`) and 4-bit (`P4_G32`, `4.50 bpw`) codebooks paired with a pure-Triton fused decode runtime and single HIP/CUDA-graph execution engine.
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
## 1. Included Checkpoints & Headline Benchmarks
|
| 36 |
+
|
| 37 |
+
All speeds and VRAM numbers below were measured end-to-end on a single **AMD Radeon RX 9060 XT (`16 GB` GDDR6, `320 GB/s`, `gfx1200` RDNA4, ROCm 7.2 / PyTorch 2.14)** — and the bundled Triton runtime also runs on NVIDIA CUDA GPUs.
|
| 38 |
+
|
| 39 |
+
| Model / Checkpoint | Disk & Resident VRAM | Compression vs BF16 | Mean KLD (`1,849` toks) | PPL (`ref = 2.1416`) | Top-1 Agree (All / Python / C++) | Decode (`4K` / `16K` ctx) | Fits 100% On |
|
| 40 |
+
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
| 41 |
+
| **Official Unquantized `BF16`** *(24-core Xeon + GPU hybrid)* | `52.8 GB` *(12.1G GPU + 40.7G RAM)* | `1.00×` | `0.0000` | `2.1416` | `100%` | `2.62 tok/s` *(offloaded)* | `64 GB+` |
|
| 42 |
+
| **Official `NVFP4+MXFP8`** *(Blackwell / DGX Spark)* | `20.16 GB` | `2.62×` | — | — | — | *OOM on 16 GB* | `24–32 GB+` |
|
| 43 |
+
| **`inkling2_mini_p2_looptop8.safetensors`** ⭐ **Recommended** | **`10.87 GB`** | **`4.86×`** | **`0.0542`** | **`2.1542`** *(+0.0059 loss)* | **`93.35%` / `97.50%` / `97.61%`** | **`54.22` / `48.60 tok/s`** | **16 GB GPUs** *(up to `16K` ctx)* |
|
| 44 |
+
| **`inkling2_mini_p2_maxcomp.safetensors`** *(Max Compression)* | **`8.83 GB`** | **`5.98×`** | `0.1138` | `2.2143` *(+0.0334 loss)* | `91.35%` / `95.39%` / `96.90%` | **`56.23 tok/s`** (`4K`) | **12 GB & 16 GB GPUs** |
|
| 45 |
+
|
| 46 |
+
### Why `loop_top8` (`10.87 GB`) Hits Such Low 2-Bit KL Divergence (`0.0542`)
|
| 47 |
+
|
| 48 |
+
`Inkling-2-Mini` has 24 physical transformer layers where the middle 12 layers (`L6..17`) execute **3 looped passes per token** (`48` logical layer applications). Quantization error in looped layers compounds 3× per token:
|
| 49 |
+
- **`maxcomp` (`8.83 GB`):** All 24 MoE expert banks (`128` experts × `24` layers) are compressed to **`P2_G32` (`2.50 bpw`)**, while attention projections, embeddings, `lm_head`, and the 23-layer ViT use **`P4_G32` (`4.50 bpw`)**.
|
| 50 |
+
- **`loop_top8` (`10.87 GB`):** Promotes only the **top-8 highest-sensitivity looped/boundary MoE layers (`L5, L8, L9, L11, L12, L14, L15, L16`)** from `P2_G32` to `P4_G32`, leaving the other **16 MoE expert banks at 2-bit `P2_G32`**. That cuts mean KL divergence **in half** (`0.1138 → 0.0542`, Python KLD `0.0409 → 0.0217`, Top-1 coding agreement **`97.5%–97.6%`**) for just `+2.04 GB` VRAM and only `-3.6%` decode throughput.
|
| 51 |
+
- **Exact Parameter Coverage:** **`99.85%`** (`26.35B / 26.39B`) of parameters are quantized (`P2_G32` or `P4_G32`). Only **`0.15%`** (`40.2M` params = `124.6 MB`) remains BF16/FP32 by design: rank-64 looped `message_gate` (`84.9 MB`), MoE routers (`28.3 MB`), and per-head sink / relative-position / 4-tap short-conv / Attention-Residual / RMSNorm parameters (`11.4 MB`).
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## 2. Full 5-Domain KL-Divergence & Perplexity Evaluation
|
| 56 |
+
|
| 57 |
+
Evaluated over `1,849` held-out tokens across 5 technical domains directly against exact unquantized BF16 reference log-probabilities (`benchmarks/kld_looptop8.json`, `benchmarks/kld_p2_maxcomp.json`):
|
| 58 |
+
|
| 59 |
+
| Domain (`n_tokens`) | BF16 Ref PPL | `maxcomp` (`8.83 GB`) PPL / KLD / Top-1 | **`loop_top8` (`10.87 GB`) PPL / KLD / Top-1** |
|
| 60 |
+
| :--- | :---: | :---: | :---: |
|
| 61 |
+
| **`python_code`** (`521`) | `1.3042` | `1.3034` / `0.0409` / `95.39%` | **`1.3190` / `0.0217` / `97.50%`** |
|
| 62 |
+
| **`systems_cpp`** (`419`) | `1.2216` | `1.2724` / `0.0337` / `96.90%` | **`1.2525` / `0.0181` / `97.61%`** |
|
| 63 |
+
| **`math_reasoning`** (`390`) | `1.7601` | `1.9600` / `0.1382` / `91.03%` | **`1.8209` / `0.0437` / `93.59%`** |
|
| 64 |
+
| **`technical_prose`** (`216`) | `6.9495` | `8.3906` / `0.2283` / `77.31%` | **`7.6525` / `0.1021` / `83.33%`** |
|
| 65 |
+
| **`inkling_chat_tool`** (`303`) | `6.0739` | `5.3638` / `0.2372` / `87.13%` | **`5.3300` / `0.1395` / `87.13%`** |
|
| 66 |
+
| **Overall (`1,849` tokens)** | **`2.1416`** | **`2.2143` / `0.1138` / `91.35%`** | **`2.1542` / `0.0542` / `93.35%`** |
|
| 67 |
+
|
| 68 |
+
Per-layer MoE weight SNR (`benchmarks/inkling2_looptop8_report.json`): `10.04–10.12 dB` on 2-bit `P2_G32` layers, `23.80–23.89 dB` on 4-bit `P4_G32` layers (`14.68 dB` / `14.65 dB` mean across all 24 `gate_up` / `down` expert banks).
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
## 3. Adversarial Coding Arena: `PRIME-Quant loop_top8` (`10.87 GB`) vs Unquantized Official `BF16` (`52.8 GB`)
|
| 73 |
+
|
| 74 |
+
To test real multi-step software engineering beyond perplexity, we ran both checkpoints head-to-head on a 2-module, **15-test adversarial reactive spreadsheet compiler + DAG engine** (`benchmarks/test_spreadsheet_engine.py`):
|
| 75 |
+
- **Stage A (`formula_parser.py`, 6 tests):** No `eval`/`exec`, multi-letter reversed 2D ranges (`AB2:Z1`), exact precedence (`2^3^2 == 512`, `-2^2 == -4`, `2^-3 == 0.125`, `--5 + +-3 == 2`), non-chaining comparisons, strict short-circuit `IF()`, and empty-vs-explicit-zero aggregate semantics.
|
| 76 |
+
- **Stage B (`spreadsheet_engine.py`, 15 tests):** Iterative 3-color DFS cycle detection & transactional rollback (including cycles hidden inside 2D ranges), atomic `batch_update` dependency swaps (`A1 ↔ B1`), error propagation & self-healing, and incremental Kahn topological recalculation over a **40-layer diamond DAG (`2^40` paths) alongside 1,000 unrelated cells in `< 0.2s`**.
|
| 77 |
+
|
| 78 |
+
### A. Apples-to-Apples Head-to-Head (`max_new_tokens=4500`, `temp=1.0`, `top_p=1.0`, identical prompts & seeds `701–703`)
|
| 79 |
+
|
| 80 |
+
| Metric | **`PRIME-Quant loop_top8` (`10.87 GB`)** | **Official Unquantized `BF16` (`52.8 GB`)** | Delta |
|
| 81 |
+
| :--- | :---: | :---: | :---: |
|
| 82 |
+
| **Memory Footprint** | **`10.87 GB` VRAM** *(100% GPU)* | `52.8 GB` *(12.09G VRAM + 40.7G RAM)* | **`4.86×` smaller** |
|
| 83 |
+
| **Load Time (`meta` → GPU)** | **`7.6 s`** | `75.8 s` | **`10.0×` faster** |
|
| 84 |
+
| **Decode Speed** | **`46.9 – 49.3 tok/s`** | `2.57 – 2.62 tok/s` *(24-core Xeon + GPU)* | **`18.6×` faster** |
|
| 85 |
+
| **Stage A Iter 1** | `4/6` *(266 lines, 1.7 min)* | `3/6` *(310 lines, 29.3 min)* | `PRIME-Quant` |
|
| 86 |
+
| **Stage A Iter 2** | `0/6` *(truncated mid-`_eval`)* | `0/6` *(truncated mid-`_eval`)* | Same native truncation |
|
| 87 |
+
| **Stage A Iter 3** | **`6/6 PASS`** *(230 lines, `4,290` toks)* | `4/6 FAIL` *(334 lines, trunc @ `4,500`)* | **`PRIME-Quant` (+2)** |
|
| 88 |
+
| **Stage A Wall Time** | **`5.3 min`** *(3 iters)* | `92.5 min` *(3 iters)* | **`17.4×` faster** |
|
| 89 |
+
| **Stage B (Full 15-Test DAG)** | **`14/15 PASS (93.3%)`** *(8.4 min, 4 iters)* | *Stopped after Stage A* | **`PRIME-Quant`** |
|
| 90 |
+
|
| 91 |
+
*(Honest engineering audit: Both models exhibited the exact same native `Inkling-2-Mini` verbosity ceiling at `4,500` tokens — Inkling-2's tokenizer encodes Python at `2.64–2.87 chars/tok` (`~11.5–14.7 tok/line`), so a ~340-line class-based module plus `900` thinking tokens requires `~4,990` tokens. In Stage B, `loop_top8` passed the 40-layer diamond DAG, 1,000-cell incremental perf check, 2D-range cycle rollback, and atomic `batch_update` swap, missing only `test_08` due to an eager upstream-error check before short-circuit `IF`. Generated outputs are included verbatim in `benchmarks/formula_parser_looptop8.py` and `benchmarks/spreadsheet_engine_looptop8.py`.)*
|
| 92 |
+
|
| 93 |
+
### B. Fixed `16K`-Context / `8,192`-Token Guard Run (`run_inkling2_prime.py`)
|
| 94 |
+
|
| 95 |
+
After upgrading `Inkling2GraphEngine` with `16K` chunked-prefill KV cache, graceful sentence-boundary thinking wrap-up, `--min-answer-tokens`, and post-answer duplicate-rewrite prevention:
|
| 96 |
+
- **Truncation rate dropped to `0%` (`6/6` turns hit `finish_reason='stop'` cleanly)** across Stage A & Stage B.
|
| 97 |
+
- **Stage A solved `6/6` on Iteration 2** (335-line full class-based AST in `4,381` tokens, saved in `benchmarks/formula_parser_v2_16k.py`).
|
| 98 |
+
- **Peak VRAM at `ctx=16384`:** `12.08–15.67 GB` (**100% resident on 16 GB RX 9060 XT**) at **`46.8–49.2 tok/s`**.
|
| 99 |
+
|
| 100 |
+
---
|
| 101 |
+
|
| 102 |
+
## 4. Kernel & Runtime Engineering Highlights (`52–56 tok/s` on RX 9060 XT)
|
| 103 |
+
|
| 104 |
+
The bundled read-only inference runtime (`prime_infer_runtime.py`, `inkling2_kernels.py`, `run_inkling2_prime.py`) achieves near-bandwidth-limit speed on consumer GPUs:
|
| 105 |
+
- **L0-cached 4-float LUT 2-bit `P2_G32` GEMV & MoE kernels:** `300.7 GB/s` achieved out of `320 GB/s` theoretical peak on RDNA4 (`~94%` hardware bandwidth utilization).
|
| 106 |
+
- **Parallel-K FP32 MoE `down_proj` + weighted reduction (`BLOCK_R=4, GROUPS_K=4`)** and fused `gate_up + SoftcappedSwiGLU` activation (`1.54×` faster than 2-pass).
|
| 107 |
+
- **Fused Triton Inkling-2 decode ops** for all 48 looped passes: 4-tap static & dynamic short convolutions (`192` calls/tok), rank-64 `message_gate` (`96` calls/tok), single-pass `AttnRes` (`120` calls/tok), single-CTA `router_topk` (`4.25×` faster), `unweighted_rmsnorm` (`8.06×` faster), and ring-buffer GQA + RelativePositionBias + Per-Head Sink decode attention (`48` calls/tok).
|
| 108 |
+
- **Chunked prefill attention (`Q_CHUNK=128`) & chunked `AttnRes` (`T=512`):** cuts 12K–16K prefill activation VRAM by ~80× (`2+ GB → ~25 MB`), enabling `16K` context on 16 GB VRAM.
|
| 109 |
+
- **Single-HIP/CUDA-Graph replay** verified bit-exact (`24/24` greedy token parity vs eager `model.generate()`) and backed by a **23/23 passing** parity test suite.
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## 5. Quick Start (Run Locally on a 12 GB or 16 GB GPU)
|
| 114 |
+
|
| 115 |
+
### Install Dependencies
|
| 116 |
+
```bash
|
| 117 |
+
pip install -r requirements.txt
|
| 118 |
+
# Note: Inkling-2-Mini requires transformers >= 5.24.0 (or current transformers main)
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
### Download This Repository
|
| 122 |
+
```bash
|
| 123 |
+
huggingface-cli download batteryphil/Inkling-2-Mini-PRIME-Quant --local-dir ./Inkling-2-Mini-PRIME-Quant
|
| 124 |
+
cd ./Inkling-2-Mini-PRIME-Quant
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
### Run Interactive Chat or Coding Prompts (`10.87 GB` `loop_top8` — Default)
|
| 128 |
+
```bash
|
| 129 |
+
# On AMD ROCm (RX 9060 XT / RDNA3 / RDNA4):
|
| 130 |
+
TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 python run_inkling2_prime.py \
|
| 131 |
+
--checkpoint ./inkling2_mini_p2_looptop8.safetensors \
|
| 132 |
+
--max-cache-len 16384 --max-new-tokens 8192 --max-thinking-tokens 900 \
|
| 133 |
+
--interactive
|
| 134 |
+
|
| 135 |
+
# On NVIDIA CUDA (16 GB RTX 4060 Ti / 4080 / 5060 Ti / 5080):
|
| 136 |
+
python run_inkling2_prime.py \
|
| 137 |
+
--checkpoint ./inkling2_mini_p2_looptop8.safetensors \
|
| 138 |
+
--max-cache-len 16384 --max-new-tokens 8192 --max-thinking-tokens 900 \
|
| 139 |
+
--interactive
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
### Run on a 12 GB GPU (`8.83 GB` `maxcomp` All-2-Bit MoE, `56.2 tok/s`)
|
| 143 |
+
```bash
|
| 144 |
+
python run_inkling2_prime.py \
|
| 145 |
+
--checkpoint ./inkling2_mini_p2_maxcomp.safetensors \
|
| 146 |
+
--max-cache-len 4096 --max-new-tokens 2048 --max-thinking-tokens 600 \
|
| 147 |
+
--prompt "Write a concise Python LRU cache with O(1) get and put."
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
### Recommended Sampling Settings
|
| 151 |
+
- **Follow official Thinking Machines defaults:** `--temperature 1.0 --top-p 1.0 --top-k 0 --min-p 0.0` (avoid low temperatures `< 0.6` on reasoning prompts to prevent CoT repetition loops).
|
| 152 |
+
- **For long coding generations (>250 lines):** Use `--max-cache-len 16384 --max-new-tokens 8192 --max-thinking-tokens 900 --min-answer-tokens 6000` so Inkling-2's tokenizer has full answer runway without truncating mid-function.
|
| 153 |
+
|
| 154 |
+
---
|
| 155 |
+
|
| 156 |
+
## 6. Licensing & Attribution
|
| 157 |
+
|
| 158 |
+
- **Original PRIME-Quant Codecs, Triton Kernels, Inference Runtime, and Compressed Checkpoint Layouts:** Copyright (c) 2026 Philip Bartsch (`@batteryphil`). Licensed under the **[Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0](LICENSE)** — **free (0% royalty)** for personal, hobbyist, academic, and non-profit use; **5% net profit share** (or optional flat-fee buyout) for commercial deployments.
|
| 159 |
+
- **Upstream Base Weights (`thinkingmachines/Inkling-2-Mini`):** Authored by Thinking Machines Lab, Inc. under the **Apache License 2.0** (see [`NOTICE`](NOTICE)).
|
| 160 |
+
|
| 161 |
+
*(Note: This repository contains the quantized weights, benchmarks, and a minimal read-only inference runtime. The full PRIME-Quant quantization, Schur-GPTQ, Shadowless PRIMAL distillation, and scratch-training suite remains in the author's private research repository.)*
|
benchmarks/formula_parser_looptop8.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
class FormulaError(Exception): pass
|
| 5 |
+
class FormulaSyntaxError(Exception): pass
|
| 6 |
+
|
| 7 |
+
NAMES = {"SUM", "AVG", "MIN", "MAX", "COUNT", "IF"}
|
| 8 |
+
CMP_OPS = {"==", "!=", "<", "<=", ">", ">="}
|
| 9 |
+
|
| 10 |
+
def tokenize(expr):
|
| 11 |
+
if not isinstance(expr, str): raise FormulaSyntaxError("expr must be str")
|
| 12 |
+
toks = []; i = 0; n = len(expr)
|
| 13 |
+
while i < n:
|
| 14 |
+
ch = expr[i]
|
| 15 |
+
if ch.isspace(): i += 1; continue
|
| 16 |
+
if ch.isdigit() or (ch == "." and i + 1 < n and expr[i+1].isdigit()):
|
| 17 |
+
j = i
|
| 18 |
+
while j < n and expr[j].isdigit(): j += 1
|
| 19 |
+
if j < n and expr[j] == ".":
|
| 20 |
+
j += 1
|
| 21 |
+
while j < n and expr[j].isdigit(): j += 1
|
| 22 |
+
toks.append(("num", expr[i:j])); i = j; continue
|
| 23 |
+
if ch.isalpha() or ch == "_":
|
| 24 |
+
j = i
|
| 25 |
+
while j < n and (expr[j].isalnum() or expr[j] == "_"): j += 1
|
| 26 |
+
toks.append(("name", expr[i:j])); i = j; continue
|
| 27 |
+
for op in ("<=", ">=", "==", "!=", "<", ">", "+", "-", "*", "/", "^", "(", ")", ",", ":"):
|
| 28 |
+
if expr.startswith(op, i):
|
| 29 |
+
toks.append(("op", op)); i += len(op); break
|
| 30 |
+
else:
|
| 31 |
+
raise FormulaSyntaxError(f"invalid token at {i}")
|
| 32 |
+
toks.append(("eof", ""))
|
| 33 |
+
return toks
|
| 34 |
+
|
| 35 |
+
def _coord_info(coord):
|
| 36 |
+
if not isinstance(coord, str): return None
|
| 37 |
+
m = re.fullmatch(r"([A-Za-z]+)([0-9]+)", coord)
|
| 38 |
+
if not m: return None
|
| 39 |
+
letters = m.group(1).upper(); row = int(m.group(2))
|
| 40 |
+
if row < 1: return None
|
| 41 |
+
col = 0
|
| 42 |
+
for ch in letters: col = col * 26 + (ord(ch) - ord("A") + 1)
|
| 43 |
+
return letters, row, col
|
| 44 |
+
|
| 45 |
+
def normalize_coord(coord):
|
| 46 |
+
info = _coord_info(coord)
|
| 47 |
+
if info is None: raise FormulaSyntaxError("invalid coord")
|
| 48 |
+
letters, row, col = info
|
| 49 |
+
return f"{letters}{row}"
|
| 50 |
+
|
| 51 |
+
def _letters(col):
|
| 52 |
+
out = ""
|
| 53 |
+
while col > 0:
|
| 54 |
+
col -= 1
|
| 55 |
+
out = chr(ord("A") + col % 26) + out
|
| 56 |
+
col //= 26
|
| 57 |
+
return out
|
| 58 |
+
|
| 59 |
+
def _expand_range(node):
|
| 60 |
+
_, s_row, s_col = _coord_info(normalize_coord(node["start"]))
|
| 61 |
+
_, e_row, e_col = _coord_info(normalize_coord(node["end"]))
|
| 62 |
+
cols = range(min(s_col, e_col), max(s_col, e_col) + 1)
|
| 63 |
+
rows = range(min(s_row, e_row), max(s_row, e_row) + 1)
|
| 64 |
+
return [f"{_letters(c)}{r}" for r in rows for c in cols]
|
| 65 |
+
|
| 66 |
+
class Parser:
|
| 67 |
+
def __init__(self, toks): self.toks = toks; self.i = 0
|
| 68 |
+
|
| 69 |
+
def peek(self): return self.toks[self.i]
|
| 70 |
+
def next(self):
|
| 71 |
+
t = self.toks[self.i]
|
| 72 |
+
if self.i < len(self.toks) - 1: self.i += 1
|
| 73 |
+
return t
|
| 74 |
+
def expect_op(self, op):
|
| 75 |
+
t = self.next()
|
| 76 |
+
if t != ("op", op): raise FormulaSyntaxError(f"expected {op}")
|
| 77 |
+
|
| 78 |
+
def parse_comparison(self):
|
| 79 |
+
left = self.parse_additive()
|
| 80 |
+
t = self.peek()
|
| 81 |
+
if t[0] == "op" and t[1] in CMP_OPS:
|
| 82 |
+
op = t[1]; self.next()
|
| 83 |
+
right = self.parse_additive()
|
| 84 |
+
t = self.peek()
|
| 85 |
+
if t[0] == "op" and t[1] in CMP_OPS:
|
| 86 |
+
raise FormulaSyntaxError("non-chaining")
|
| 87 |
+
return {"type": "cmp", "op": op, "left": left, "right": right}
|
| 88 |
+
return left
|
| 89 |
+
|
| 90 |
+
def parse_additive(self):
|
| 91 |
+
left = self.parse_multiplicative()
|
| 92 |
+
while self.peek() in (("op", "+"), ("op", "-")):
|
| 93 |
+
op = self.next()[1]
|
| 94 |
+
right = self.parse_multiplicative()
|
| 95 |
+
left = {"type": "bin", "op": op, "left": left, "right": right}
|
| 96 |
+
return left
|
| 97 |
+
|
| 98 |
+
def parse_multiplicative(self):
|
| 99 |
+
left = self.parse_unary()
|
| 100 |
+
while self.peek() in (("op", "*"), ("op", "/")):
|
| 101 |
+
op = self.next()[1]
|
| 102 |
+
right = self.parse_unary()
|
| 103 |
+
left = {"type": "bin", "op": op, "left": left, "right": right}
|
| 104 |
+
return left
|
| 105 |
+
|
| 106 |
+
def parse_unary(self):
|
| 107 |
+
if self.peek() in (("op", "+"), ("op", "-")):
|
| 108 |
+
op = self.next()[1]
|
| 109 |
+
return {"type": "un", "op": op, "operand": self.parse_unary()}
|
| 110 |
+
return self.parse_power()
|
| 111 |
+
|
| 112 |
+
def parse_power(self):
|
| 113 |
+
left = self.parse_atom()
|
| 114 |
+
if self.peek() == ("op", "^"):
|
| 115 |
+
self.next()
|
| 116 |
+
right = self.parse_unary()
|
| 117 |
+
return {"type": "bin", "op": "^", "left": left, "right": right}
|
| 118 |
+
return left
|
| 119 |
+
|
| 120 |
+
def parse_atom(self):
|
| 121 |
+
t = self.next()
|
| 122 |
+
if t[0] == "num":
|
| 123 |
+
try: return {"type": "num", "value": float(t[1])}
|
| 124 |
+
except ValueError: raise FormulaSyntaxError("bad number")
|
| 125 |
+
if t == ("op", "("):
|
| 126 |
+
node = self.parse_comparison()
|
| 127 |
+
self.expect_op(")")
|
| 128 |
+
return node
|
| 129 |
+
if t[0] == "name":
|
| 130 |
+
name = t[1].upper()
|
| 131 |
+
if self.peek() == ("op", "("):
|
| 132 |
+
if name not in NAMES: raise FormulaSyntaxError("unknown function")
|
| 133 |
+
self.next()
|
| 134 |
+
args = []
|
| 135 |
+
if self.peek() != ("op", ")"):
|
| 136 |
+
args.append(self.parse_comparison())
|
| 137 |
+
while self.peek() == ("op", ","):
|
| 138 |
+
self.next()
|
| 139 |
+
if self.peek() == ("op", ")"): raise FormulaSyntaxError("trailing comma")
|
| 140 |
+
args.append(self.parse_comparison())
|
| 141 |
+
if self.peek() != ("op", ")"): raise FormulaSyntaxError("expected )")
|
| 142 |
+
self.next()
|
| 143 |
+
if not args: raise FormulaSyntaxError("empty call")
|
| 144 |
+
if name == "IF" and len(args) != 3: raise FormulaSyntaxError("IF arity")
|
| 145 |
+
return {"type": "call", "name": name, "args": args}
|
| 146 |
+
coord = normalize_coord(name)
|
| 147 |
+
if self.peek() == ("op", ":"):
|
| 148 |
+
self.next()
|
| 149 |
+
t2 = self.next()
|
| 150 |
+
if t2[0] != "name": raise FormulaSyntaxError("expected coord after :")
|
| 151 |
+
end = normalize_coord(t2[1])
|
| 152 |
+
return {"type": "range", "start": coord, "end": end}
|
| 153 |
+
return {"type": "cell", "coord": coord}
|
| 154 |
+
raise FormulaSyntaxError("bad atom")
|
| 155 |
+
|
| 156 |
+
def parse_formula(expr):
|
| 157 |
+
p = Parser(tokenize(expr))
|
| 158 |
+
node = p.parse_comparison()
|
| 159 |
+
if p.peek()[0] != "eof": raise FormulaSyntaxError("unexpected token")
|
| 160 |
+
return node
|
| 161 |
+
|
| 162 |
+
def collect_refs(node):
|
| 163 |
+
refs = set()
|
| 164 |
+
def visit(n):
|
| 165 |
+
t = n.get("type")
|
| 166 |
+
if t == "cell": refs.add(normalize_coord(n["coord"]))
|
| 167 |
+
elif t == "range": refs.update(_expand_range(n))
|
| 168 |
+
elif t == "un": visit(n["operand"])
|
| 169 |
+
elif t in ("bin", "cmp"): visit(n["left"]); visit(n["right"])
|
| 170 |
+
elif t == "call":
|
| 171 |
+
for arg in n["args"]: visit(arg)
|
| 172 |
+
visit(node)
|
| 173 |
+
return refs
|
| 174 |
+
|
| 175 |
+
def eval_formula(node, get_val, is_populated): return _eval(node, get_val, is_populated)
|
| 176 |
+
|
| 177 |
+
def _eval(node, get_val, is_populated):
|
| 178 |
+
t = node["type"]
|
| 179 |
+
if t == "num": return node["value"]
|
| 180 |
+
if t == "cell": return get_val(normalize_coord(node["coord"]))
|
| 181 |
+
if t == "range": raise FormulaError("range only valid as function argument")
|
| 182 |
+
if t == "un":
|
| 183 |
+
v = _eval(node["operand"], get_val, is_populated)
|
| 184 |
+
return -v if node["op"] == "-" else v
|
| 185 |
+
if t == "bin":
|
| 186 |
+
lhs = _eval(node["left"], get_val, is_populated)
|
| 187 |
+
rhs = _eval(node["right"], get_val, is_populated)
|
| 188 |
+
op = node["op"]
|
| 189 |
+
if op == "+": return lhs + rhs
|
| 190 |
+
if op == "-": return lhs - rhs
|
| 191 |
+
if op == "*": return lhs * rhs
|
| 192 |
+
if op == "/":
|
| 193 |
+
if rhs == 0: raise FormulaError("div by zero")
|
| 194 |
+
return lhs / rhs
|
| 195 |
+
if op == "^": return lhs ** rhs
|
| 196 |
+
raise FormulaError("bad op")
|
| 197 |
+
if t == "cmp":
|
| 198 |
+
lhs = _eval(node["left"], get_val, is_populated)
|
| 199 |
+
rhs = _eval(node["right"], get_val, is_populated)
|
| 200 |
+
op = node["op"]
|
| 201 |
+
val = {"==": lhs == rhs, "!=": lhs != rhs, "<": lhs < rhs, "<=": lhs <= rhs, ">": lhs > rhs, ">=": lhs >= rhs}[op]
|
| 202 |
+
return 1.0 if val else 0.0
|
| 203 |
+
if t == "call":
|
| 204 |
+
name = node["name"].upper()
|
| 205 |
+
args = node["args"]
|
| 206 |
+
if name == "IF":
|
| 207 |
+
if len(args) != 3: raise FormulaSyntaxError("IF arity")
|
| 208 |
+
cond = _eval(args[0], get_val, is_populated)
|
| 209 |
+
return _eval(args[1] if cond != 0.0 else args[2], get_val, is_populated)
|
| 210 |
+
values = []
|
| 211 |
+
for arg in args:
|
| 212 |
+
if arg["type"] == "range":
|
| 213 |
+
for coord in _expand_range(arg):
|
| 214 |
+
if not is_populated(coord): continue
|
| 215 |
+
values.append(get_val(coord))
|
| 216 |
+
else:
|
| 217 |
+
values.append(_eval(arg, get_val, is_populated))
|
| 218 |
+
if name == "SUM": return sum(values)
|
| 219 |
+
if name == "COUNT": return float(len(values))
|
| 220 |
+
if name == "AVG":
|
| 221 |
+
if not values: raise FormulaError("AVG over 0 values")
|
| 222 |
+
return sum(values) / len(values)
|
| 223 |
+
if name == "MIN":
|
| 224 |
+
if not values: raise FormulaError("MIN over 0 values")
|
| 225 |
+
return min(values)
|
| 226 |
+
if name == "MAX":
|
| 227 |
+
if not values: raise FormulaError("MAX over 0 values")
|
| 228 |
+
return max(values)
|
| 229 |
+
raise FormulaSyntaxError("unknown function")
|
| 230 |
+
raise FormulaError("unknown node")
|
benchmarks/formula_parser_v2_16k.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
class FormulaError(Exception):
|
| 4 |
+
pass
|
| 5 |
+
|
| 6 |
+
class FormulaSyntaxError(Exception):
|
| 7 |
+
pass
|
| 8 |
+
|
| 9 |
+
COORD_RE = re.compile(r'^([A-Za-z]+)([0-9]+)$')
|
| 10 |
+
|
| 11 |
+
def normalize_coord(coord):
|
| 12 |
+
if not isinstance(coord, str):
|
| 13 |
+
raise FormulaSyntaxError('invalid coord')
|
| 14 |
+
m = COORD_RE.match(coord.strip())
|
| 15 |
+
if not m:
|
| 16 |
+
raise FormulaSyntaxError('invalid coord: ' + repr(coord))
|
| 17 |
+
letters = m.group(1).upper()
|
| 18 |
+
row = int(m.group(2))
|
| 19 |
+
if row < 1 or not letters:
|
| 20 |
+
raise FormulaSyntaxError('invalid coord: ' + repr(coord))
|
| 21 |
+
return f'{letters}{row}'
|
| 22 |
+
|
| 23 |
+
def _tokens(expr):
|
| 24 |
+
if not isinstance(expr, str):
|
| 25 |
+
raise FormulaSyntaxError('expr must be string')
|
| 26 |
+
i = 0
|
| 27 |
+
n = len(expr)
|
| 28 |
+
while i < n:
|
| 29 |
+
c = expr[i]
|
| 30 |
+
if c in ' \t\r\n':
|
| 31 |
+
i += 1
|
| 32 |
+
continue
|
| 33 |
+
if c.isdigit() or (c == '.' and i + 1 < n and expr[i+1].isdigit()):
|
| 34 |
+
j = i
|
| 35 |
+
while j < n and (expr[j].isdigit() or expr[j] == '.'):
|
| 36 |
+
j += 1
|
| 37 |
+
s = expr[i:j]
|
| 38 |
+
if s.count('.') > 1:
|
| 39 |
+
raise FormulaSyntaxError('invalid number: ' + s)
|
| 40 |
+
try:
|
| 41 |
+
float(s)
|
| 42 |
+
except ValueError:
|
| 43 |
+
raise FormulaSyntaxError('invalid number: ' + s)
|
| 44 |
+
yield ('NUM', s)
|
| 45 |
+
i = j
|
| 46 |
+
continue
|
| 47 |
+
if c.isalpha() or c == '_':
|
| 48 |
+
j = i
|
| 49 |
+
while j < n and (expr[j].isalnum() or expr[j] == '_'):
|
| 50 |
+
j += 1
|
| 51 |
+
yield ('NAME', expr[i:j])
|
| 52 |
+
i = j
|
| 53 |
+
continue
|
| 54 |
+
two = expr[i:i+2]
|
| 55 |
+
if two in ('==', '!=', '<=', '>='):
|
| 56 |
+
yield (two, two)
|
| 57 |
+
i += 2
|
| 58 |
+
continue
|
| 59 |
+
if c in '+-*/^<>(),:':
|
| 60 |
+
yield (c, c)
|
| 61 |
+
i += 1
|
| 62 |
+
continue
|
| 63 |
+
raise FormulaSyntaxError('unexpected char at ' + str(i) + ': ' + c)
|
| 64 |
+
|
| 65 |
+
class Node:
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
class Num(Node):
|
| 69 |
+
def __init__(self, value):
|
| 70 |
+
self.value = value
|
| 71 |
+
|
| 72 |
+
class Cell(Node):
|
| 73 |
+
def __init__(self, coord):
|
| 74 |
+
self.coord = coord
|
| 75 |
+
|
| 76 |
+
class Range(Node):
|
| 77 |
+
def __init__(self, top_left, bottom_right):
|
| 78 |
+
self.top_left = top_left
|
| 79 |
+
self.bottom_right = bottom_right
|
| 80 |
+
|
| 81 |
+
class Unary(Node):
|
| 82 |
+
def __init__(self, op, operand):
|
| 83 |
+
self.op = op
|
| 84 |
+
self.operand = operand
|
| 85 |
+
|
| 86 |
+
class Bin(Node):
|
| 87 |
+
def __init__(self, op, left, right):
|
| 88 |
+
self.op = op
|
| 89 |
+
self.left = left
|
| 90 |
+
self.right = right
|
| 91 |
+
|
| 92 |
+
class Call(Node):
|
| 93 |
+
def __init__(self, name, args):
|
| 94 |
+
self.name = name.upper()
|
| 95 |
+
self.args = args
|
| 96 |
+
|
| 97 |
+
def coord_parts(coord):
|
| 98 |
+
m = COORD_RE.match(normalize_coord(coord))
|
| 99 |
+
letters = m.group(1).upper()
|
| 100 |
+
row = int(m.group(2))
|
| 101 |
+
col = 0
|
| 102 |
+
for ch in letters:
|
| 103 |
+
col = col * 26 + (ord(ch) - ord('A') + 1)
|
| 104 |
+
return col, row
|
| 105 |
+
|
| 106 |
+
def coord_from_parts(col, row):
|
| 107 |
+
letters = ''
|
| 108 |
+
c = col
|
| 109 |
+
while c > 0:
|
| 110 |
+
c, r = divmod(c - 1, 26)
|
| 111 |
+
letters = chr(r + ord('A')) + letters
|
| 112 |
+
return f'{letters}{row}'
|
| 113 |
+
|
| 114 |
+
def coords_in_range(a, b):
|
| 115 |
+
c1, r1 = coord_parts(a)
|
| 116 |
+
c2, r2 = coord_parts(b)
|
| 117 |
+
left, right = min(c1, c2), max(c1, c2)
|
| 118 |
+
top, bottom = min(r1, r2), max(r1, r2)
|
| 119 |
+
for r in range(top, bottom + 1):
|
| 120 |
+
for c in range(left, right + 1):
|
| 121 |
+
yield coord_from_parts(c, r)
|
| 122 |
+
|
| 123 |
+
def parse_formula(expr):
|
| 124 |
+
if not isinstance(expr, str) or not expr.strip():
|
| 125 |
+
raise FormulaSyntaxError('empty formula')
|
| 126 |
+
toks = list(_tokens(expr))
|
| 127 |
+
return Parser(toks).parse_formula()
|
| 128 |
+
|
| 129 |
+
class Parser:
|
| 130 |
+
def __init__(self, toks):
|
| 131 |
+
self.toks = toks
|
| 132 |
+
self.i = 0
|
| 133 |
+
def peek(self):
|
| 134 |
+
return self.toks[self.i] if self.i < len(self.toks) else (None, None)
|
| 135 |
+
def next(self):
|
| 136 |
+
t = self.peek()
|
| 137 |
+
self.i += 1
|
| 138 |
+
return t
|
| 139 |
+
def expect(self, kind):
|
| 140 |
+
t = self.next()
|
| 141 |
+
if t[0] != kind:
|
| 142 |
+
raise FormulaSyntaxError(f'expected {kind}, got {t}')
|
| 143 |
+
return t
|
| 144 |
+
def parse_formula(self):
|
| 145 |
+
node = self.parse_comparison()
|
| 146 |
+
if self.i != len(self.toks):
|
| 147 |
+
raise FormulaSyntaxError('unexpected trailing input')
|
| 148 |
+
return node
|
| 149 |
+
def parse_comparison(self):
|
| 150 |
+
left = self.parse_additive()
|
| 151 |
+
t = self.peek()
|
| 152 |
+
if t[0] in ('==', '!=', '<', '<=', '>', '>='):
|
| 153 |
+
op = self.next()[0]
|
| 154 |
+
right = self.parse_additive()
|
| 155 |
+
if self.peek()[0] in ('==', '!=', '<', '<=', '>', '>='):
|
| 156 |
+
raise FormulaSyntaxError('comparisons do not chain')
|
| 157 |
+
return Bin(op, left, right)
|
| 158 |
+
return left
|
| 159 |
+
def parse_additive(self):
|
| 160 |
+
left = self.parse_multiplicative()
|
| 161 |
+
while self.peek()[0] in ('+', '-'):
|
| 162 |
+
op = self.next()[0]
|
| 163 |
+
right = self.parse_multiplicative()
|
| 164 |
+
left = Bin(op, left, right)
|
| 165 |
+
return left
|
| 166 |
+
def parse_multiplicative(self):
|
| 167 |
+
left = self.parse_unary()
|
| 168 |
+
while self.peek()[0] in ('*', '/'):
|
| 169 |
+
op = self.next()[0]
|
| 170 |
+
right = self.parse_unary()
|
| 171 |
+
left = Bin(op, left, right)
|
| 172 |
+
return left
|
| 173 |
+
def parse_unary(self):
|
| 174 |
+
if self.peek()[0] in ('+', '-'):
|
| 175 |
+
op = self.next()[0]
|
| 176 |
+
operand = self.parse_unary()
|
| 177 |
+
return Unary(op, operand)
|
| 178 |
+
return self.parse_power()
|
| 179 |
+
def parse_power(self):
|
| 180 |
+
left = self.parse_atom()
|
| 181 |
+
if self.peek()[0] == '^':
|
| 182 |
+
self.next()
|
| 183 |
+
right = self.parse_unary()
|
| 184 |
+
return Bin('^', left, right)
|
| 185 |
+
return left
|
| 186 |
+
def parse_atom(self):
|
| 187 |
+
t = self.next()
|
| 188 |
+
kind, value = t
|
| 189 |
+
if kind == 'NUM':
|
| 190 |
+
return Num(float(value))
|
| 191 |
+
if kind == 'NAME':
|
| 192 |
+
if COORD_RE.match(value):
|
| 193 |
+
coord = normalize_coord(value)
|
| 194 |
+
if self.peek()[0] == ':':
|
| 195 |
+
self.next()
|
| 196 |
+
t2 = self.next()
|
| 197 |
+
if t2[0] != 'NAME' or not COORD_RE.match(t2[1]):
|
| 198 |
+
raise FormulaSyntaxError('expected range endpoint')
|
| 199 |
+
end = normalize_coord(t2[1])
|
| 200 |
+
return Range(coord, end)
|
| 201 |
+
return Cell(coord)
|
| 202 |
+
name = value.upper()
|
| 203 |
+
if self.peek()[0] != '(':
|
| 204 |
+
raise FormulaSyntaxError('unknown bare identifier: ' + value)
|
| 205 |
+
return self.parse_call(name)
|
| 206 |
+
if kind == '(':
|
| 207 |
+
node = self.parse_comparison()
|
| 208 |
+
self.expect(')')
|
| 209 |
+
return node
|
| 210 |
+
raise FormulaSyntaxError('unexpected token ' + str(t))
|
| 211 |
+
def parse_call(self, name):
|
| 212 |
+
self.expect('(')
|
| 213 |
+
args = []
|
| 214 |
+
if self.peek()[0] == ')':
|
| 215 |
+
raise FormulaSyntaxError('empty call')
|
| 216 |
+
while True:
|
| 217 |
+
args.append(self.parse_comparison())
|
| 218 |
+
if self.peek()[0] == ',':
|
| 219 |
+
self.next()
|
| 220 |
+
if self.peek()[0] == ')':
|
| 221 |
+
raise FormulaSyntaxError('trailing comma in call')
|
| 222 |
+
continue
|
| 223 |
+
self.expect(')')
|
| 224 |
+
break
|
| 225 |
+
allowed = {'SUM', 'AVG', 'MIN', 'MAX', 'COUNT', 'IF'}
|
| 226 |
+
if name not in allowed:
|
| 227 |
+
raise FormulaSyntaxError('unknown function: ' + name)
|
| 228 |
+
if name == 'IF' and len(args) != 3:
|
| 229 |
+
raise FormulaSyntaxError('IF requires 3 args')
|
| 230 |
+
if name != 'IF' and len(args) < 1:
|
| 231 |
+
raise FormulaSyntaxError(name + ' requires >=1 arg')
|
| 232 |
+
return Call(name, args)
|
| 233 |
+
|
| 234 |
+
def collect_refs(node):
|
| 235 |
+
refs = set()
|
| 236 |
+
def visit(n):
|
| 237 |
+
if isinstance(n, Cell):
|
| 238 |
+
refs.add(n.coord)
|
| 239 |
+
elif isinstance(n, Range):
|
| 240 |
+
for c in coords_in_range(n.top_left, n.bottom_right):
|
| 241 |
+
refs.add(c)
|
| 242 |
+
elif isinstance(n, Unary):
|
| 243 |
+
visit(n.operand)
|
| 244 |
+
elif isinstance(n, Bin):
|
| 245 |
+
visit(n.left)
|
| 246 |
+
visit(n.right)
|
| 247 |
+
elif isinstance(n, Call):
|
| 248 |
+
for a in n.args:
|
| 249 |
+
visit(a)
|
| 250 |
+
elif isinstance(n, Num):
|
| 251 |
+
pass
|
| 252 |
+
else:
|
| 253 |
+
raise FormulaSyntaxError('unknown AST node')
|
| 254 |
+
visit(node)
|
| 255 |
+
return refs
|
| 256 |
+
|
| 257 |
+
def _eval(node, get_val, is_populated):
|
| 258 |
+
if isinstance(node, Num):
|
| 259 |
+
return node.value
|
| 260 |
+
if isinstance(node, Cell):
|
| 261 |
+
return get_val(node.coord)
|
| 262 |
+
if isinstance(node, Unary):
|
| 263 |
+
v = _eval(node.operand, get_val, is_populated)
|
| 264 |
+
return v if node.op == '+' else -v
|
| 265 |
+
if isinstance(node, Bin):
|
| 266 |
+
op = node.op
|
| 267 |
+
if op in ('==', '!=', '<', '<=', '>', '>='):
|
| 268 |
+
l = _eval(node.left, get_val, is_populated)
|
| 269 |
+
r = _eval(node.right, get_val, is_populated)
|
| 270 |
+
if op == '==': return 1.0 if l == r else 0.0
|
| 271 |
+
if op == '!=': return 0.0 if l == r else 1.0
|
| 272 |
+
if op == '<': return 1.0 if l < r else 0.0
|
| 273 |
+
if op == '<=': return 1.0 if l <= r else 0.0
|
| 274 |
+
if op == '>': return 1.0 if l > r else 0.0
|
| 275 |
+
if op == '>=': return 1.0 if l >= r else 0.0
|
| 276 |
+
l = _eval(node.left, get_val, is_populated)
|
| 277 |
+
r = _eval(node.right, get_val, is_populated)
|
| 278 |
+
if op == '+': return l + r
|
| 279 |
+
if op == '-': return l - r
|
| 280 |
+
if op == '*': return l * r
|
| 281 |
+
if op == '/':
|
| 282 |
+
if r == 0:
|
| 283 |
+
raise FormulaError('div by zero')
|
| 284 |
+
return l / r
|
| 285 |
+
if op == '^':
|
| 286 |
+
return l ** r
|
| 287 |
+
raise FormulaSyntaxError('unknown op ' + op)
|
| 288 |
+
if isinstance(node, Call):
|
| 289 |
+
name = node.name
|
| 290 |
+
if name == 'IF':
|
| 291 |
+
cond = _eval(node.args[0], get_val, is_populated)
|
| 292 |
+
if cond != 0:
|
| 293 |
+
return _eval(node.args[1], get_val, is_populated)
|
| 294 |
+
return _eval(node.args[2], get_val, is_populated)
|
| 295 |
+
values = []
|
| 296 |
+
for arg in node.args:
|
| 297 |
+
if isinstance(arg, Range):
|
| 298 |
+
for c in coords_in_range(arg.top_left, arg.bottom_right):
|
| 299 |
+
if not is_populated(c):
|
| 300 |
+
continue
|
| 301 |
+
values.append(get_val(c))
|
| 302 |
+
else:
|
| 303 |
+
v = _eval(arg, get_val, is_populated)
|
| 304 |
+
values.append(v)
|
| 305 |
+
if name == 'SUM':
|
| 306 |
+
return sum(values)
|
| 307 |
+
if name == 'COUNT':
|
| 308 |
+
return float(len(values))
|
| 309 |
+
if name == 'AVG':
|
| 310 |
+
if not values:
|
| 311 |
+
raise FormulaError('AVG over 0 values')
|
| 312 |
+
return sum(values) / len(values)
|
| 313 |
+
if name == 'MIN':
|
| 314 |
+
if not values:
|
| 315 |
+
raise FormulaError('MIN over 0 values')
|
| 316 |
+
return min(values)
|
| 317 |
+
if name == 'MAX':
|
| 318 |
+
if not values:
|
| 319 |
+
raise FormulaError('MAX over 0 values')
|
| 320 |
+
return max(values)
|
| 321 |
+
raise FormulaSyntaxError('unknown function ' + name)
|
| 322 |
+
raise FormulaSyntaxError('unknown AST node')
|
| 323 |
+
|
| 324 |
+
def eval_formula(node, get_val, is_populated):
|
| 325 |
+
if isinstance(node, Range):
|
| 326 |
+
return float(sum(_eval_range(node, get_val, is_populated)))
|
| 327 |
+
return _eval(node, get_val, is_populated)
|
| 328 |
+
|
| 329 |
+
def _eval_range(range_node, get_val, is_populated):
|
| 330 |
+
vals = []
|
| 331 |
+
for c in coords_in_range(range_node.top_left, range_node.bottom_right):
|
| 332 |
+
if not is_populated(c):
|
| 333 |
+
continue
|
| 334 |
+
vals.append(get_val(c))
|
| 335 |
+
return vals
|
benchmarks/inkling2_looptop8_report.json
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_model": "/data/prime_quant_models/Inkling-2-Mini",
|
| 3 |
+
"out_safetensors": "/data/prime_quant_models/inkling2_mini_p2_looptop8.safetensors",
|
| 4 |
+
"calib_gptq": false,
|
| 5 |
+
"protect_layers": [
|
| 6 |
+
5,
|
| 7 |
+
8,
|
| 8 |
+
9,
|
| 9 |
+
11,
|
| 10 |
+
12,
|
| 11 |
+
14,
|
| 12 |
+
15,
|
| 13 |
+
16
|
| 14 |
+
],
|
| 15 |
+
"protect_down_only": [],
|
| 16 |
+
"disk_gb": 10.868,
|
| 17 |
+
"resident_vram_gb": 10.867,
|
| 18 |
+
"meta_load_secs": 6.76,
|
| 19 |
+
"moe_mean_gu_snr_db": 14.68,
|
| 20 |
+
"moe_mean_dn_snr_db": 14.65,
|
| 21 |
+
"moe_per_layer": [
|
| 22 |
+
{
|
| 23 |
+
"layer": 0,
|
| 24 |
+
"gu_fmt": "p2_0",
|
| 25 |
+
"dn_fmt": "p2_0",
|
| 26 |
+
"gu_snr_db": 10.07,
|
| 27 |
+
"dn_snr_db": 10.09
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"layer": 1,
|
| 31 |
+
"gu_fmt": "p2_0",
|
| 32 |
+
"dn_fmt": "p2_0",
|
| 33 |
+
"gu_snr_db": 10.06,
|
| 34 |
+
"dn_snr_db": 10.08
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"layer": 2,
|
| 38 |
+
"gu_fmt": "p2_0",
|
| 39 |
+
"dn_fmt": "p2_0",
|
| 40 |
+
"gu_snr_db": 10.04,
|
| 41 |
+
"dn_snr_db": 10.08
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"layer": 3,
|
| 45 |
+
"gu_fmt": "p2_0",
|
| 46 |
+
"dn_fmt": "p2_0",
|
| 47 |
+
"gu_snr_db": 10.04,
|
| 48 |
+
"dn_snr_db": 10.08
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"layer": 4,
|
| 52 |
+
"gu_fmt": "p2_0",
|
| 53 |
+
"dn_fmt": "p2_0",
|
| 54 |
+
"gu_snr_db": 10.05,
|
| 55 |
+
"dn_snr_db": 10.08
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"layer": 5,
|
| 59 |
+
"gu_fmt": "p4_0",
|
| 60 |
+
"dn_fmt": "p4_0",
|
| 61 |
+
"gu_snr_db": 23.87,
|
| 62 |
+
"dn_snr_db": 23.88
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"layer": 6,
|
| 66 |
+
"gu_fmt": "p2_0",
|
| 67 |
+
"dn_fmt": "p2_0",
|
| 68 |
+
"gu_snr_db": 10.08,
|
| 69 |
+
"dn_snr_db": 10.08
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"layer": 7,
|
| 73 |
+
"gu_fmt": "p2_0",
|
| 74 |
+
"dn_fmt": "p2_0",
|
| 75 |
+
"gu_snr_db": 10.08,
|
| 76 |
+
"dn_snr_db": 10.08
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"layer": 8,
|
| 80 |
+
"gu_fmt": "p4_0",
|
| 81 |
+
"dn_fmt": "p4_0",
|
| 82 |
+
"gu_snr_db": 23.88,
|
| 83 |
+
"dn_snr_db": 23.89
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"layer": 9,
|
| 87 |
+
"gu_fmt": "p4_0",
|
| 88 |
+
"dn_fmt": "p4_0",
|
| 89 |
+
"gu_snr_db": 23.88,
|
| 90 |
+
"dn_snr_db": 23.89
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"layer": 10,
|
| 94 |
+
"gu_fmt": "p2_0",
|
| 95 |
+
"dn_fmt": "p2_0",
|
| 96 |
+
"gu_snr_db": 10.07,
|
| 97 |
+
"dn_snr_db": 10.05
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"layer": 11,
|
| 101 |
+
"gu_fmt": "p4_0",
|
| 102 |
+
"dn_fmt": "p4_0",
|
| 103 |
+
"gu_snr_db": 23.88,
|
| 104 |
+
"dn_snr_db": 23.85
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"layer": 12,
|
| 108 |
+
"gu_fmt": "p4_0",
|
| 109 |
+
"dn_fmt": "p4_0",
|
| 110 |
+
"gu_snr_db": 23.89,
|
| 111 |
+
"dn_snr_db": 23.88
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"layer": 13,
|
| 115 |
+
"gu_fmt": "p2_0",
|
| 116 |
+
"dn_fmt": "p2_0",
|
| 117 |
+
"gu_snr_db": 10.09,
|
| 118 |
+
"dn_snr_db": 10.04
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"layer": 14,
|
| 122 |
+
"gu_fmt": "p4_0",
|
| 123 |
+
"dn_fmt": "p4_0",
|
| 124 |
+
"gu_snr_db": 23.89,
|
| 125 |
+
"dn_snr_db": 23.86
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"layer": 15,
|
| 129 |
+
"gu_fmt": "p4_0",
|
| 130 |
+
"dn_fmt": "p4_0",
|
| 131 |
+
"gu_snr_db": 23.88,
|
| 132 |
+
"dn_snr_db": 23.84
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"layer": 16,
|
| 136 |
+
"gu_fmt": "p4_0",
|
| 137 |
+
"dn_fmt": "p4_0",
|
| 138 |
+
"gu_snr_db": 23.87,
|
| 139 |
+
"dn_snr_db": 23.8
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"layer": 17,
|
| 143 |
+
"gu_fmt": "p2_0",
|
| 144 |
+
"dn_fmt": "p2_0",
|
| 145 |
+
"gu_snr_db": 10.03,
|
| 146 |
+
"dn_snr_db": 9.76
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"layer": 18,
|
| 150 |
+
"gu_fmt": "p2_0",
|
| 151 |
+
"dn_fmt": "p2_0",
|
| 152 |
+
"gu_snr_db": 10.1,
|
| 153 |
+
"dn_snr_db": 10.06
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"layer": 19,
|
| 157 |
+
"gu_fmt": "p2_0",
|
| 158 |
+
"dn_fmt": "p2_0",
|
| 159 |
+
"gu_snr_db": 10.11,
|
| 160 |
+
"dn_snr_db": 10.07
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"layer": 20,
|
| 164 |
+
"gu_fmt": "p2_0",
|
| 165 |
+
"dn_fmt": "p2_0",
|
| 166 |
+
"gu_snr_db": 10.12,
|
| 167 |
+
"dn_snr_db": 10.08
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"layer": 21,
|
| 171 |
+
"gu_fmt": "p2_0",
|
| 172 |
+
"dn_fmt": "p2_0",
|
| 173 |
+
"gu_snr_db": 10.11,
|
| 174 |
+
"dn_snr_db": 10.07
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"layer": 22,
|
| 178 |
+
"gu_fmt": "p2_0",
|
| 179 |
+
"dn_fmt": "p2_0",
|
| 180 |
+
"gu_snr_db": 10.11,
|
| 181 |
+
"dn_snr_db": 10.04
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"layer": 23,
|
| 185 |
+
"gu_fmt": "p2_0",
|
| 186 |
+
"dn_fmt": "p2_0",
|
| 187 |
+
"gu_snr_db": 10.1,
|
| 188 |
+
"dn_snr_db": 9.98
|
| 189 |
+
}
|
| 190 |
+
],
|
| 191 |
+
"quant_code_loss": 0.2769,
|
| 192 |
+
"quant_code_ppl": 1.319
|
| 193 |
+
}
|
benchmarks/kld_looptop8.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": "/data/prime_quant_models/inkling2_mini_p2_looptop8.safetensors",
|
| 3 |
+
"disk_gb": 10.868,
|
| 4 |
+
"vram_gb": 10.867,
|
| 5 |
+
"total_tokens": 1849,
|
| 6 |
+
"mean_kld": 0.0542,
|
| 7 |
+
"top1_pct": 93.35,
|
| 8 |
+
"ref_ppl": 2.1416,
|
| 9 |
+
"q_ppl": 2.1542,
|
| 10 |
+
"delta_loss": 0.00586,
|
| 11 |
+
"domains": {
|
| 12 |
+
"python_code": {
|
| 13 |
+
"n_tokens": 521,
|
| 14 |
+
"ref_ppl": 1.3042,
|
| 15 |
+
"q_ppl": 1.319,
|
| 16 |
+
"delta_loss": 0.0113,
|
| 17 |
+
"mean_kld": 0.02169,
|
| 18 |
+
"top1_pct": 97.5
|
| 19 |
+
},
|
| 20 |
+
"systems_cpp": {
|
| 21 |
+
"n_tokens": 419,
|
| 22 |
+
"ref_ppl": 1.2216,
|
| 23 |
+
"q_ppl": 1.2525,
|
| 24 |
+
"delta_loss": 0.02501,
|
| 25 |
+
"mean_kld": 0.01806,
|
| 26 |
+
"top1_pct": 97.61
|
| 27 |
+
},
|
| 28 |
+
"math_reasoning": {
|
| 29 |
+
"n_tokens": 390,
|
| 30 |
+
"ref_ppl": 1.7601,
|
| 31 |
+
"q_ppl": 1.8209,
|
| 32 |
+
"delta_loss": 0.03397,
|
| 33 |
+
"mean_kld": 0.04371,
|
| 34 |
+
"top1_pct": 93.59
|
| 35 |
+
},
|
| 36 |
+
"technical_prose": {
|
| 37 |
+
"n_tokens": 216,
|
| 38 |
+
"ref_ppl": 6.9495,
|
| 39 |
+
"q_ppl": 7.6525,
|
| 40 |
+
"delta_loss": 0.09637,
|
| 41 |
+
"mean_kld": 0.10205,
|
| 42 |
+
"top1_pct": 83.33
|
| 43 |
+
},
|
| 44 |
+
"inkling_chat_tool": {
|
| 45 |
+
"n_tokens": 303,
|
| 46 |
+
"ref_ppl": 6.0739,
|
| 47 |
+
"q_ppl": 5.33,
|
| 48 |
+
"delta_loss": -0.13065,
|
| 49 |
+
"mean_kld": 0.13945,
|
| 50 |
+
"top1_pct": 87.13
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
benchmarks/kld_p2_gptq.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": "/data/prime_quant_models/inkling2_mini_p2_gptq.safetensors",
|
| 3 |
+
"disk_gb": 8.829,
|
| 4 |
+
"vram_gb": 8.829,
|
| 5 |
+
"total_tokens": 1849,
|
| 6 |
+
"mean_kld": 0.11362,
|
| 7 |
+
"top1_pct": 90.97,
|
| 8 |
+
"ref_ppl": 2.1416,
|
| 9 |
+
"q_ppl": 2.1894,
|
| 10 |
+
"delta_loss": 0.02206,
|
| 11 |
+
"domains": {
|
| 12 |
+
"python_code": {
|
| 13 |
+
"n_tokens": 521,
|
| 14 |
+
"ref_ppl": 1.3042,
|
| 15 |
+
"q_ppl": 1.3159,
|
| 16 |
+
"delta_loss": 0.0089,
|
| 17 |
+
"mean_kld": 0.0507,
|
| 18 |
+
"top1_pct": 94.63
|
| 19 |
+
},
|
| 20 |
+
"systems_cpp": {
|
| 21 |
+
"n_tokens": 419,
|
| 22 |
+
"ref_ppl": 1.2216,
|
| 23 |
+
"q_ppl": 1.2868,
|
| 24 |
+
"delta_loss": 0.052,
|
| 25 |
+
"mean_kld": 0.03792,
|
| 26 |
+
"top1_pct": 96.9
|
| 27 |
+
},
|
| 28 |
+
"math_reasoning": {
|
| 29 |
+
"n_tokens": 390,
|
| 30 |
+
"ref_ppl": 1.7601,
|
| 31 |
+
"q_ppl": 1.9391,
|
| 32 |
+
"delta_loss": 0.09687,
|
| 33 |
+
"mean_kld": 0.13181,
|
| 34 |
+
"top1_pct": 90.51
|
| 35 |
+
},
|
| 36 |
+
"technical_prose": {
|
| 37 |
+
"n_tokens": 216,
|
| 38 |
+
"ref_ppl": 6.9495,
|
| 39 |
+
"q_ppl": 8.229,
|
| 40 |
+
"delta_loss": 0.16899,
|
| 41 |
+
"mean_kld": 0.24517,
|
| 42 |
+
"top1_pct": 76.85
|
| 43 |
+
},
|
| 44 |
+
"inkling_chat_tool": {
|
| 45 |
+
"n_tokens": 303,
|
| 46 |
+
"ref_ppl": 6.0739,
|
| 47 |
+
"q_ppl": 4.9839,
|
| 48 |
+
"delta_loss": -0.19778,
|
| 49 |
+
"mean_kld": 0.20932,
|
| 50 |
+
"top1_pct": 87.13
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
benchmarks/kld_p2_maxcomp.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": "/data/prime_quant_models/inkling2_mini_p2_maxcomp.safetensors",
|
| 3 |
+
"disk_gb": 8.829,
|
| 4 |
+
"vram_gb": 8.829,
|
| 5 |
+
"total_tokens": 1849,
|
| 6 |
+
"mean_kld": 0.11384,
|
| 7 |
+
"top1_pct": 91.35,
|
| 8 |
+
"ref_ppl": 2.1416,
|
| 9 |
+
"q_ppl": 2.2143,
|
| 10 |
+
"delta_loss": 0.03339,
|
| 11 |
+
"domains": {
|
| 12 |
+
"python_code": {
|
| 13 |
+
"n_tokens": 521,
|
| 14 |
+
"ref_ppl": 1.3042,
|
| 15 |
+
"q_ppl": 1.3034,
|
| 16 |
+
"delta_loss": -0.00061,
|
| 17 |
+
"mean_kld": 0.04086,
|
| 18 |
+
"top1_pct": 95.39
|
| 19 |
+
},
|
| 20 |
+
"systems_cpp": {
|
| 21 |
+
"n_tokens": 419,
|
| 22 |
+
"ref_ppl": 1.2216,
|
| 23 |
+
"q_ppl": 1.2724,
|
| 24 |
+
"delta_loss": 0.04075,
|
| 25 |
+
"mean_kld": 0.0337,
|
| 26 |
+
"top1_pct": 96.9
|
| 27 |
+
},
|
| 28 |
+
"math_reasoning": {
|
| 29 |
+
"n_tokens": 390,
|
| 30 |
+
"ref_ppl": 1.7601,
|
| 31 |
+
"q_ppl": 1.96,
|
| 32 |
+
"delta_loss": 0.10758,
|
| 33 |
+
"mean_kld": 0.13821,
|
| 34 |
+
"top1_pct": 91.03
|
| 35 |
+
},
|
| 36 |
+
"technical_prose": {
|
| 37 |
+
"n_tokens": 216,
|
| 38 |
+
"ref_ppl": 6.9495,
|
| 39 |
+
"q_ppl": 8.3906,
|
| 40 |
+
"delta_loss": 0.18845,
|
| 41 |
+
"mean_kld": 0.22825,
|
| 42 |
+
"top1_pct": 77.31
|
| 43 |
+
},
|
| 44 |
+
"inkling_chat_tool": {
|
| 45 |
+
"n_tokens": 303,
|
| 46 |
+
"ref_ppl": 6.0739,
|
| 47 |
+
"q_ppl": 5.3638,
|
| 48 |
+
"delta_loss": -0.12433,
|
| 49 |
+
"mean_kld": 0.23724,
|
| 50 |
+
"top1_pct": 87.13
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
benchmarks/spreadsheet_engine_looptop8.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""spreadsheet_engine.py"""
|
| 2 |
+
from collections import deque
|
| 3 |
+
from formula_parser import (
|
| 4 |
+
FormulaError,
|
| 5 |
+
FormulaSyntaxError,
|
| 6 |
+
parse_formula,
|
| 7 |
+
collect_refs,
|
| 8 |
+
normalize_coord,
|
| 9 |
+
_eval,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CircularReferenceError(Exception):
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _Cell:
|
| 18 |
+
__slots__ = ("coord", "kind", "literal", "ast", "deps", "error", "value")
|
| 19 |
+
|
| 20 |
+
def __init__(self, coord, kind, literal=None, ast=None, deps=None):
|
| 21 |
+
self.coord = coord
|
| 22 |
+
self.kind = kind
|
| 23 |
+
self.literal = literal
|
| 24 |
+
self.ast = ast
|
| 25 |
+
self.deps = set(deps or ())
|
| 26 |
+
self.error = None
|
| 27 |
+
self.value = literal if kind == "constant" else None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Spreadsheet:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.cells = {}
|
| 33 |
+
self.dependents = {}
|
| 34 |
+
|
| 35 |
+
def set_cell(self, coord, value):
|
| 36 |
+
self.batch_update({coord: value})
|
| 37 |
+
|
| 38 |
+
def get(self, coord):
|
| 39 |
+
info = normalize_coord(coord)
|
| 40 |
+
cell = self.cells.get(info)
|
| 41 |
+
if cell is None:
|
| 42 |
+
return 0
|
| 43 |
+
if cell.error is not None:
|
| 44 |
+
raise cell.error
|
| 45 |
+
if cell.kind == "constant":
|
| 46 |
+
return cell.literal
|
| 47 |
+
return cell.value
|
| 48 |
+
|
| 49 |
+
def _spec(self, coord, value):
|
| 50 |
+
info = normalize_coord(coord)
|
| 51 |
+
if value is None:
|
| 52 |
+
return (info, "clear", None, None, set())
|
| 53 |
+
if isinstance(value, bool):
|
| 54 |
+
raise FormulaSyntaxError("bool is not a valid spreadsheet value")
|
| 55 |
+
if isinstance(value, (int, float)):
|
| 56 |
+
return (info, "constant", value, None, set())
|
| 57 |
+
if isinstance(value, str):
|
| 58 |
+
if value.startswith("="):
|
| 59 |
+
ast = parse_formula(value[1:])
|
| 60 |
+
return (info, "formula", None, ast, set(collect_refs(ast)))
|
| 61 |
+
try:
|
| 62 |
+
return (info, "constant", int(value), None, set())
|
| 63 |
+
except ValueError:
|
| 64 |
+
pass
|
| 65 |
+
try:
|
| 66 |
+
return (info, "constant", float(value), None, set())
|
| 67 |
+
except ValueError:
|
| 68 |
+
raise FormulaSyntaxError("invalid numeric literal")
|
| 69 |
+
raise FormulaSyntaxError("invalid value type")
|
| 70 |
+
|
| 71 |
+
def batch_update(self, updates):
|
| 72 |
+
if updates is None:
|
| 73 |
+
return
|
| 74 |
+
spec_map = {}
|
| 75 |
+
specs = []
|
| 76 |
+
for coord, value in updates.items():
|
| 77 |
+
info, kind, literal, ast, deps = self._spec(coord, value)
|
| 78 |
+
spec_map[info] = (kind, literal, ast, deps)
|
| 79 |
+
specs.append((info, kind, literal, ast, deps))
|
| 80 |
+
|
| 81 |
+
tentative = {}
|
| 82 |
+
for info, cell in self.cells.items():
|
| 83 |
+
if info in spec_map:
|
| 84 |
+
continue
|
| 85 |
+
if cell.kind == "formula":
|
| 86 |
+
tentative[info] = set(cell.deps)
|
| 87 |
+
for info, kind, literal, ast, deps in specs:
|
| 88 |
+
if kind == "formula":
|
| 89 |
+
tentative[info] = set(deps)
|
| 90 |
+
elif kind == "constant":
|
| 91 |
+
pass
|
| 92 |
+
else:
|
| 93 |
+
tentative.pop(info, None)
|
| 94 |
+
|
| 95 |
+
visiting = {}
|
| 96 |
+
|
| 97 |
+
def dfs(start):
|
| 98 |
+
visiting[start] = 1
|
| 99 |
+
stack = [(start, 0)]
|
| 100 |
+
while stack:
|
| 101 |
+
node, idx = stack[-1]
|
| 102 |
+
deps = list(tentative.get(node, set()))
|
| 103 |
+
if idx < len(deps):
|
| 104 |
+
dep = deps[idx]
|
| 105 |
+
stack[-1] = (node, idx + 1)
|
| 106 |
+
if dep in tentative:
|
| 107 |
+
if visiting.get(dep) == 1:
|
| 108 |
+
raise CircularReferenceError("cycle detected")
|
| 109 |
+
if visiting.get(dep) is None:
|
| 110 |
+
visiting[dep] = 1
|
| 111 |
+
stack.append((dep, 0))
|
| 112 |
+
else:
|
| 113 |
+
visiting[node] = 2
|
| 114 |
+
stack.pop()
|
| 115 |
+
|
| 116 |
+
for info in list(tentative):
|
| 117 |
+
if visiting.get(info) != 2:
|
| 118 |
+
dfs(info)
|
| 119 |
+
|
| 120 |
+
new_cells = {}
|
| 121 |
+
for info, cell in self.cells.items():
|
| 122 |
+
if info in spec_map:
|
| 123 |
+
continue
|
| 124 |
+
new_cells[info] = cell
|
| 125 |
+
for info, kind, literal, ast, deps in specs:
|
| 126 |
+
if kind == "clear":
|
| 127 |
+
new_cells.pop(info, None)
|
| 128 |
+
elif kind == "constant":
|
| 129 |
+
new_cells[info] = _Cell(info, "constant", literal=literal)
|
| 130 |
+
else:
|
| 131 |
+
new_cells[info] = _Cell(info, "formula", ast=ast, deps=deps)
|
| 132 |
+
|
| 133 |
+
self.cells = new_cells
|
| 134 |
+
self.dependents = {}
|
| 135 |
+
for info, cell in self.cells.items():
|
| 136 |
+
if cell.kind != "formula":
|
| 137 |
+
continue
|
| 138 |
+
for dep in cell.deps:
|
| 139 |
+
self.dependents.setdefault(dep, set()).add(info)
|
| 140 |
+
|
| 141 |
+
affected = set()
|
| 142 |
+
q = deque()
|
| 143 |
+
for info, kind, literal, ast, deps in specs:
|
| 144 |
+
q.append(info)
|
| 145 |
+
while q:
|
| 146 |
+
u = q.popleft()
|
| 147 |
+
for v in self.dependents.get(u, set()):
|
| 148 |
+
if v not in affected:
|
| 149 |
+
affected.add(v)
|
| 150 |
+
q.append(v)
|
| 151 |
+
|
| 152 |
+
affected_formulas = {info for info, cell in self.cells.items()
|
| 153 |
+
if cell.kind == "formula" and info in affected}
|
| 154 |
+
for info, kind, literal, ast, deps in specs:
|
| 155 |
+
if kind == "formula":
|
| 156 |
+
affected_formulas.add(info)
|
| 157 |
+
|
| 158 |
+
in_deg = {}
|
| 159 |
+
for node in affected_formulas:
|
| 160 |
+
cell = self.cells[node]
|
| 161 |
+
in_deg[node] = sum(1 for dep in cell.deps if dep in affected_formulas)
|
| 162 |
+
|
| 163 |
+
q = deque([n for n, d in in_deg.items() if d == 0])
|
| 164 |
+
order = []
|
| 165 |
+
while q:
|
| 166 |
+
node = q.popleft()
|
| 167 |
+
order.append(node)
|
| 168 |
+
for dependent in self.dependents.get(node, set()):
|
| 169 |
+
if dependent in in_deg:
|
| 170 |
+
in_deg[dependent] -= 1
|
| 171 |
+
if in_deg[dependent] == 0:
|
| 172 |
+
q.append(dependent)
|
| 173 |
+
|
| 174 |
+
def get_val(coord):
|
| 175 |
+
info = normalize_coord(coord)
|
| 176 |
+
cell = self.cells.get(info)
|
| 177 |
+
if cell is None:
|
| 178 |
+
return 0
|
| 179 |
+
if cell.error is not None:
|
| 180 |
+
return 0
|
| 181 |
+
if cell.kind == "constant":
|
| 182 |
+
return cell.literal
|
| 183 |
+
if cell.value is None:
|
| 184 |
+
return 0
|
| 185 |
+
return cell.value
|
| 186 |
+
|
| 187 |
+
def is_populated(coord):
|
| 188 |
+
info = normalize_coord(coord)
|
| 189 |
+
cell = self.cells.get(info)
|
| 190 |
+
if cell is None:
|
| 191 |
+
return False
|
| 192 |
+
if cell.kind == "formula":
|
| 193 |
+
return cell.error is None and cell.value is not None
|
| 194 |
+
return True
|
| 195 |
+
|
| 196 |
+
for info, kind, literal, ast, deps in specs:
|
| 197 |
+
if kind == "constant":
|
| 198 |
+
cell = self.cells.get(info)
|
| 199 |
+
if cell is not None:
|
| 200 |
+
cell.value = literal
|
| 201 |
+
cell.error = None
|
| 202 |
+
|
| 203 |
+
# Propagate upstream error state before evaluating downstream formulas.
|
| 204 |
+
for node in order:
|
| 205 |
+
cell = self.cells.get(node)
|
| 206 |
+
if cell is None or cell.kind != "formula":
|
| 207 |
+
continue
|
| 208 |
+
upstream_error = None
|
| 209 |
+
for dep in cell.deps:
|
| 210 |
+
dep_cell = self.cells.get(dep)
|
| 211 |
+
if dep_cell is not None and dep_cell.error is not None:
|
| 212 |
+
upstream_error = dep_cell.error
|
| 213 |
+
break
|
| 214 |
+
if upstream_error is not None:
|
| 215 |
+
cell.value = None
|
| 216 |
+
cell.error = upstream_error
|
| 217 |
+
continue
|
| 218 |
+
try:
|
| 219 |
+
cell.value = _eval(cell.ast, get_val, is_populated)
|
| 220 |
+
cell.error = None
|
| 221 |
+
except FormulaError as exc:
|
| 222 |
+
cell.error = exc
|
| 223 |
+
cell.value = None
|
| 224 |
+
|
| 225 |
+
def clear_error_if_fixed(node):
|
| 226 |
+
cell = self.cells.get(node)
|
| 227 |
+
if cell is not None and cell.kind == "constant":
|
| 228 |
+
cell.error = None
|
| 229 |
+
cell.value = cell.literal
|
| 230 |
+
clear_error_if_fixed("nonexistent")
|
benchmarks/test_spreadsheet_engine.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from spreadsheet_engine import (
|
| 8 |
+
CircularReferenceError,
|
| 9 |
+
FormulaError,
|
| 10 |
+
FormulaSyntaxError,
|
| 11 |
+
Spreadsheet,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_01_no_eval_or_exec_used():
|
| 16 |
+
"""Enforce a real parser — no eval(), exec(), or compile() shortcuts."""
|
| 17 |
+
src_path = os.path.join(os.path.dirname(__file__), "spreadsheet_engine.py")
|
| 18 |
+
with open(src_path, "r", encoding="utf-8") as f:
|
| 19 |
+
tree = ast.parse(f.read())
|
| 20 |
+
banned = {"eval", "exec", "compile", "__import__"}
|
| 21 |
+
for node in ast.walk(tree):
|
| 22 |
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
| 23 |
+
assert node.func.id not in banned, f"Forbidden builtin `{node.func.id}` used!"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_02_basic_literals_and_case_insensitive_coords():
|
| 27 |
+
s = Spreadsheet()
|
| 28 |
+
s.set_cell("a1", 10)
|
| 29 |
+
s.set_cell("B2", 2.5)
|
| 30 |
+
s.set_cell("C3", "=-a1 + b2 * 4")
|
| 31 |
+
assert s.get("A1") == 10
|
| 32 |
+
assert s.get("b2") == 2.5
|
| 33 |
+
assert s.get("c3") == pytest.approx(0.0)
|
| 34 |
+
assert s.get("Z99") == 0 # unset cell defaults to 0
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_03_multi_letter_columns_and_ranges():
|
| 38 |
+
s = Spreadsheet()
|
| 39 |
+
s.set_cell("Z1", 10)
|
| 40 |
+
s.set_cell("AA1", 20)
|
| 41 |
+
s.set_cell("AB1", 30)
|
| 42 |
+
s.set_cell("AC1", "=SUM(Z1:AB1)")
|
| 43 |
+
assert s.get("AC1") == pytest.approx(60.0)
|
| 44 |
+
# Reversed 2D range
|
| 45 |
+
s.set_cell("Z2", 4)
|
| 46 |
+
s.set_cell("AA2", 6)
|
| 47 |
+
s.set_cell("AB2", 10)
|
| 48 |
+
s.set_cell("AD1", "=SUM(AB2:Z1)")
|
| 49 |
+
assert s.get("AD1") == pytest.approx(80.0)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_04_operator_precedence_and_right_assoc_power():
|
| 53 |
+
s = Spreadsheet()
|
| 54 |
+
s.set_cell("A1", "=2^3^2") # right-associative: 2^(3^2) = 512
|
| 55 |
+
s.set_cell("A2", "=(2^3)^2") # 64
|
| 56 |
+
s.set_cell("A3", "=-2^2") # unary minus lower than ^: -(2^2) = -4
|
| 57 |
+
s.set_cell("A4", "=(-2)^2") # 4
|
| 58 |
+
s.set_cell("A5", "=2^-3") # 2^(-3) = 0.125
|
| 59 |
+
s.set_cell("A6", "=10 - 3 - 2") # left-associative: 5
|
| 60 |
+
s.set_cell("A7", "=20 / 4 / 2") # left-associative: 2.5
|
| 61 |
+
s.set_cell("A8", "=--5 + +-3") # chained unary ops: 5 + (-3) = 2
|
| 62 |
+
assert s.get("A1") == pytest.approx(512.0)
|
| 63 |
+
assert s.get("A2") == pytest.approx(64.0)
|
| 64 |
+
assert s.get("A3") == pytest.approx(-4.0)
|
| 65 |
+
assert s.get("A4") == pytest.approx(4.0)
|
| 66 |
+
assert s.get("A5") == pytest.approx(0.125)
|
| 67 |
+
assert s.get("A6") == pytest.approx(5.0)
|
| 68 |
+
assert s.get("A7") == pytest.approx(2.5)
|
| 69 |
+
assert s.get("A8") == pytest.approx(2.0)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_05_comparisons_and_if_short_circuit_div_zero():
|
| 73 |
+
s = Spreadsheet()
|
| 74 |
+
s.set_cell("A1", 0)
|
| 75 |
+
s.set_cell("B1", "=IF(A1 == 0, 99, 10 / A1)")
|
| 76 |
+
assert s.get("B1") == pytest.approx(99.0)
|
| 77 |
+
s.set_cell("A1", 2)
|
| 78 |
+
assert s.get("B1") == pytest.approx(5.0)
|
| 79 |
+
# Comparison operators
|
| 80 |
+
s.set_cell("C1", "=IF(A1 >= 2, IF(A1 < 3, 1, 0), -1)")
|
| 81 |
+
s.set_cell("C2", "=IF(A1 != 2, 100, 200)")
|
| 82 |
+
assert s.get("C1") == pytest.approx(1.0)
|
| 83 |
+
assert s.get("C2") == pytest.approx(200.0)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_06_aggregates_empty_cell_semantics():
|
| 87 |
+
s = Spreadsheet()
|
| 88 |
+
s.set_cell("A1", 10)
|
| 89 |
+
s.set_cell("A3", 30) # A2 is unset/empty!
|
| 90 |
+
s.set_cell("A4", 0) # explicit zero IS populated!
|
| 91 |
+
s.set_cell("B1", "=SUM(A1:A4)")
|
| 92 |
+
s.set_cell("B2", "=COUNT(A1:A4)") # 3 populated cells (A1, A3, A4)
|
| 93 |
+
s.set_cell("B3", "=AVG(A1:A4)") # (10 + 30 + 0) / 3 = 13.3333...
|
| 94 |
+
s.set_cell("B4", "=MIN(A1:A4)") # 0
|
| 95 |
+
s.set_cell("B5", "=MAX(A1:A4)") # 30
|
| 96 |
+
assert s.get("B1") == pytest.approx(40.0)
|
| 97 |
+
assert s.get("B2") == pytest.approx(3.0)
|
| 98 |
+
assert s.get("B3") == pytest.approx(40.0 / 3.0)
|
| 99 |
+
assert s.get("B4") == pytest.approx(0.0)
|
| 100 |
+
assert s.get("B5") == pytest.approx(30.0)
|
| 101 |
+
# Clearing A4 to None removes it from populated set
|
| 102 |
+
s.set_cell("A4", None)
|
| 103 |
+
assert s.get("B2") == pytest.approx(2.0)
|
| 104 |
+
assert s.get("B3") == pytest.approx(20.0)
|
| 105 |
+
assert s.get("B4") == pytest.approx(10.0)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_07_nested_functions_and_mixed_range_scalar_args():
|
| 109 |
+
s = Spreadsheet()
|
| 110 |
+
s.set_cell("A1", 2)
|
| 111 |
+
s.set_cell("A2", 4)
|
| 112 |
+
s.set_cell("B1", 6)
|
| 113 |
+
s.set_cell("B2", 8)
|
| 114 |
+
s.set_cell("C1", "=SUM(A1:B2, MAX(A1:B2) * 2, IF(MIN(A1:B2) == 2, 10, 0))")
|
| 115 |
+
assert s.get("C1") == pytest.approx(20.0 + 16.0 + 10.0)
|
| 116 |
+
# AVG on completely empty range raises FormulaError
|
| 117 |
+
s.set_cell("D1", "=AVG(K1:K5)")
|
| 118 |
+
with pytest.raises(FormulaError):
|
| 119 |
+
s.get("D1")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_08_error_propagation_and_self_healing():
|
| 123 |
+
s = Spreadsheet()
|
| 124 |
+
s.set_cell("A1", 0)
|
| 125 |
+
s.set_cell("B1", "=10 / A1")
|
| 126 |
+
s.set_cell("C1", "=B1 + 5")
|
| 127 |
+
s.set_cell("D1", "=SUM(B1:C1)")
|
| 128 |
+
s.set_cell("E1", "=IF(1, 42, B1)") # short-circuits past errored cell B1!
|
| 129 |
+
assert s.get("E1") == pytest.approx(42.0)
|
| 130 |
+
for cell in ("B1", "C1", "D1"):
|
| 131 |
+
with pytest.raises(FormulaError):
|
| 132 |
+
s.get(cell)
|
| 133 |
+
# Heal A1 -> all downstream cells must automatically heal!
|
| 134 |
+
s.set_cell("A1", 2)
|
| 135 |
+
assert s.get("B1") == pytest.approx(5.0)
|
| 136 |
+
assert s.get("C1") == pytest.approx(10.0)
|
| 137 |
+
assert s.get("D1") == pytest.approx(15.0)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_09_direct_and_indirect_cycle_transactional_rollback():
|
| 141 |
+
s = Spreadsheet()
|
| 142 |
+
s.set_cell("A1", 5)
|
| 143 |
+
s.set_cell("B1", "=A1 * 2")
|
| 144 |
+
s.set_cell("C1", "=B1 + 3")
|
| 145 |
+
s.set_cell("D1", "=C1 + 1")
|
| 146 |
+
assert s.get("D1") == pytest.approx(14.0)
|
| 147 |
+
|
| 148 |
+
# Self-cycle
|
| 149 |
+
with pytest.raises(CircularReferenceError):
|
| 150 |
+
s.set_cell("A1", "=A1 + 1")
|
| 151 |
+
assert s.get("A1") == 5 and s.get("D1") == pytest.approx(14.0)
|
| 152 |
+
|
| 153 |
+
# 4-hop cycle A1 -> B1 -> C1 -> D1 -> A1
|
| 154 |
+
with pytest.raises(CircularReferenceError):
|
| 155 |
+
s.set_cell("A1", "=D1 + 1")
|
| 156 |
+
assert s.get("A1") == 5
|
| 157 |
+
assert s.get("B1") == pytest.approx(10.0)
|
| 158 |
+
assert s.get("C1") == pytest.approx(13.0)
|
| 159 |
+
assert s.get("D1") == pytest.approx(14.0)
|
| 160 |
+
|
| 161 |
+
# Downstream still updates cleanly after rejected cycle!
|
| 162 |
+
s.set_cell("A1", 10)
|
| 163 |
+
assert s.get("D1") == pytest.approx(24.0)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_10_cycle_hidden_inside_2d_range_rollback():
|
| 167 |
+
s = Spreadsheet()
|
| 168 |
+
s.set_cell("A1", 1)
|
| 169 |
+
s.set_cell("B2", 2)
|
| 170 |
+
s.set_cell("C3", 3)
|
| 171 |
+
s.set_cell("D1", "=SUM(A1:C3)")
|
| 172 |
+
assert s.get("D1") == pytest.approx(6.0)
|
| 173 |
+
|
| 174 |
+
# B2 is inside A1:C3 -> making B2 depend on D1 creates cycle B2 -> D1 -> B2!
|
| 175 |
+
with pytest.raises(CircularReferenceError):
|
| 176 |
+
s.set_cell("B2", "=D1 + 1")
|
| 177 |
+
assert s.get("B2") == 2
|
| 178 |
+
assert s.get("D1") == pytest.approx(6.0)
|
| 179 |
+
|
| 180 |
+
# Self-inclusion in range: B2 = "=SUM(A1:C3)"
|
| 181 |
+
with pytest.raises(CircularReferenceError):
|
| 182 |
+
s.set_cell("B2", "=SUM(A1:C3)")
|
| 183 |
+
assert s.get("B2") == 2
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def test_11_syntax_error_rollback():
|
| 187 |
+
s = Spreadsheet()
|
| 188 |
+
s.set_cell("A1", 42)
|
| 189 |
+
s.set_cell("B1", "=A1 + 8")
|
| 190 |
+
assert s.get("B1") == pytest.approx(50.0)
|
| 191 |
+
for bad in ("=1 +", "=SUM(A1, )", "=((1+2)", "=1 + 2)", "=UNKNOWN_FN(1)", "=1 == == 2"):
|
| 192 |
+
with pytest.raises(FormulaSyntaxError):
|
| 193 |
+
s.set_cell("B1", bad)
|
| 194 |
+
assert s.get("B1") == pytest.approx(50.0)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_12_batch_update_dependency_swap_and_atomic_rollback():
|
| 198 |
+
s = Spreadsheet()
|
| 199 |
+
s.set_cell("A1", 10)
|
| 200 |
+
s.set_cell("B1", "=A1 + 5")
|
| 201 |
+
s.set_cell("C1", "=B1 * 2")
|
| 202 |
+
assert s.get("C1") == pytest.approx(30.0)
|
| 203 |
+
|
| 204 |
+
# Reversing dependency direction atomically MUST succeed (no false cycle!)
|
| 205 |
+
s.batch_update({"A1": "=B1 * 3", "B1": 4})
|
| 206 |
+
assert s.get("B1") == 4
|
| 207 |
+
assert s.get("A1") == pytest.approx(12.0)
|
| 208 |
+
assert s.get("C1") == pytest.approx(8.0)
|
| 209 |
+
|
| 210 |
+
# Batch with a cycle in the combined graph MUST roll back ALL updates including unrelated X1!
|
| 211 |
+
s.set_cell("X1", 100)
|
| 212 |
+
with pytest.raises(CircularReferenceError):
|
| 213 |
+
s.batch_update({"X1": 999, "B1": "=A1 + 1"})
|
| 214 |
+
assert s.get("X1") == 100
|
| 215 |
+
assert s.get("B1") == 4
|
| 216 |
+
assert s.get("A1") == pytest.approx(12.0)
|
| 217 |
+
assert s.get("C1") == pytest.approx(8.0)
|
| 218 |
+
|
| 219 |
+
# Batch with a syntax error in one entry MUST roll back ALL updates!
|
| 220 |
+
with pytest.raises(FormulaSyntaxError):
|
| 221 |
+
s.batch_update({"X1": 555, "B1": "=1 + * 2"})
|
| 222 |
+
assert s.get("X1") == 100
|
| 223 |
+
assert s.get("B1") == 4
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_13_diamond_dag_and_incremental_recalc_performance():
|
| 227 |
+
"""Verifies diamond DAG evaluates accurately and incremental updates don't recompute unrelated subgraphs."""
|
| 228 |
+
s = Spreadsheet()
|
| 229 |
+
# Build 1,000 unrelated formula cells in column Z
|
| 230 |
+
s.set_cell("Y1", 1)
|
| 231 |
+
s.batch_update({f"Z{i}": f"=Y1 + {i}" for i in range(1, 1001)})
|
| 232 |
+
assert s.get("Z1000") == pytest.approx(1001.0)
|
| 233 |
+
|
| 234 |
+
# Build a 40-layer diamond DAG in A/B where naive recursive eval takes 2^40 steps!
|
| 235 |
+
updates = {"A1": 1, "B1": 1}
|
| 236 |
+
for i in range(2, 42):
|
| 237 |
+
updates[f"A{i}"] = f"=A{i-1} + B{i-1}"
|
| 238 |
+
updates[f"B{i}"] = f"=A{i-1} + B{i-1}"
|
| 239 |
+
s.batch_update(updates)
|
| 240 |
+
expected = float(2 ** 40)
|
| 241 |
+
assert s.get("A41") == pytest.approx(expected)
|
| 242 |
+
|
| 243 |
+
# Now mutate A1 50 times — must complete in well under 0.5s (proves incremental topo eval, not naive recursion or full-sheet recompute!)
|
| 244 |
+
t0 = time.perf_counter()
|
| 245 |
+
for k in range(1, 51):
|
| 246 |
+
s.set_cell("A1", k)
|
| 247 |
+
elapsed = time.perf_counter() - t0
|
| 248 |
+
assert s.get("A41") == pytest.approx(float((50 + 1) * (2 ** 39)))
|
| 249 |
+
assert elapsed < 0.5, f"Incremental update too slow ({elapsed:.3f}s) — likely recomputing unrelated cells or exponential recursion!"
|
| 250 |
+
# Check eval_count if exposed or unrelated Z1000 untouched
|
| 251 |
+
assert s.get("Z1000") == pytest.approx(1001.0)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_14_overwriting_formula_cleans_up_old_dependencies():
|
| 255 |
+
"""After replacing a formula with a constant, old upstream cells must no longer block new dependencies."""
|
| 256 |
+
s = Spreadsheet()
|
| 257 |
+
s.set_cell("A1", 1)
|
| 258 |
+
s.set_cell("B1", "=A1 + 1")
|
| 259 |
+
assert s.get("B1") == pytest.approx(2.0)
|
| 260 |
+
# Break B1 -> A1 edge
|
| 261 |
+
s.set_cell("B1", 10)
|
| 262 |
+
# Now A1 -> B1 MUST succeed without false CircularReferenceError!
|
| 263 |
+
s.set_cell("A1", "=B1 * 3")
|
| 264 |
+
assert s.get("A1") == pytest.approx(30.0)
|
| 265 |
+
assert s.get("B1") == 10
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_15_string_number_coercion_and_none_clear():
|
| 269 |
+
s = Spreadsheet()
|
| 270 |
+
s.set_cell("A1", "3.5")
|
| 271 |
+
s.set_cell("A2", "-7")
|
| 272 |
+
s.set_cell("A3", "=A1 + A2")
|
| 273 |
+
assert s.get("A3") == pytest.approx(-3.5)
|
| 274 |
+
s.set_cell("A1", None)
|
| 275 |
+
assert s.get("A1") == 0
|
| 276 |
+
assert s.get("A3") == pytest.approx(-7.0)
|
benchmarks/verified_results.json
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"benchmarks": {
|
| 3 |
+
"llama3_8b_p2_primal_wave32_swar": {
|
| 4 |
+
"architecture": "Llama-3 8B (32 layers, d=4096, ffn=14336, GQA 32/8)",
|
| 5 |
+
"quantization_tier": "STH3 v2 Pure-Prime Asymmetric P2_G32 (85.94% body) + P4_G64 (embed, lm_head, QKV, L0/1/31 down_proj)",
|
| 6 |
+
"bf16_size_gb": 16.06,
|
| 7 |
+
"prime_quant_size_gb": 2.955,
|
| 8 |
+
"prime_quant_size_gib": 2.752,
|
| 9 |
+
"compression_ratio_vs_bf16": 5.43,
|
| 10 |
+
"wikitext2_heldout_test_perplexity": {
|
| 11 |
+
"bf16_teacher_token_ppl": 12.6503,
|
| 12 |
+
"naive_rtn_p2_g32_token_ppl": 45.61,
|
| 13 |
+
"schur_two_pass_gptq_p2_g32_token_ppl": 22.9612,
|
| 14 |
+
"blockwise_primal_p2_g32_token_ppl": 21.3931,
|
| 15 |
+
"full_primal_topk_tail_kl_p2_g32_token_ppl": 18.6014
|
| 16 |
+
},
|
| 17 |
+
"primal_committed_discrete_flips": 2814,
|
| 18 |
+
"rx9060xt_gfx1200_decode_tok_per_sec": 93.1
|
| 19 |
+
},
|
| 20 |
+
"wan22_ti2v_5b_100pct_full_p4_v2": {
|
| 21 |
+
"architecture": "UMT5-XXL (5.68B, 24 blocks) + Wan 2.2 TI2V-5B 3D DiT (5.00B, 30 blocks)",
|
| 22 |
+
"quantization_tier": "100% Full V3_P4_0 (476/476 heavy matrices: 169/169 UMT5 + 307/307 DiT, ZERO BF16 weight matrices)",
|
| 23 |
+
"codebook_advantage_vs_uniform_int4_db": 1.85,
|
| 24 |
+
"umt5_xxl": {
|
| 25 |
+
"bf16_vram_mb": 11361.82,
|
| 26 |
+
"v1_partial_vram_mb": 4705.46,
|
| 27 |
+
"v2_full_p4_vram_mb": 3195.87,
|
| 28 |
+
"compression_ratio_vs_bf16": 3.56,
|
| 29 |
+
"p4_modules": 169,
|
| 30 |
+
"unquantized_bf16_matrices": 0,
|
| 31 |
+
"video_psnr_delta_vs_bf16_umt5_db": -0.04
|
| 32 |
+
},
|
| 33 |
+
"wan22_3d_dit": {
|
| 34 |
+
"bf16_vram_mb": 10023.0,
|
| 35 |
+
"v1_partial_vram_mb": 2855.23,
|
| 36 |
+
"v2_full_p4_vram_mb": 2818.5,
|
| 37 |
+
"compression_ratio_vs_bf16": 3.56,
|
| 38 |
+
"p4_modules": 307,
|
| 39 |
+
"unquantized_bf16_matrices": 0,
|
| 40 |
+
"mean_block_weight_snr_db": 22.58,
|
| 41 |
+
"min_block_weight_snr_db": 22.15,
|
| 42 |
+
"v1_min_block_weight_snr_db": 16.41,
|
| 43 |
+
"time_proj_adaln_val_snr_db": 49.6,
|
| 44 |
+
"heldout_scene_video_psnr_db": 27.97,
|
| 45 |
+
"heldout_scene_video_ssim": 0.8764,
|
| 46 |
+
"v1_end_to_end_scene_video_psnr_db": 24.49,
|
| 47 |
+
"v1_end_to_end_scene_video_ssim": 0.7648
|
| 48 |
+
},
|
| 49 |
+
"combined_vram_gb": {
|
| 50 |
+
"bf16": 21.38,
|
| 51 |
+
"v1_partial": 7.56,
|
| 52 |
+
"v2_100pct_full_p4": 6.01,
|
| 53 |
+
"vram_saved_gb": 15.37
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"inkling2_mini_prime_quant_p2_p4": {
|
| 57 |
+
"architecture": "Thinking Machines Inkling-2-Mini (26.39B total / 3.4B-5.4B effective active, 24 physical layers / 48 logical passes via 3x looped middle layers 6-17, 128 routed top-8 MoE experts, 20 sliding + 4 full GQA 24/8 layers, 23-layer ViT)",
|
| 58 |
+
"bf16_size_gb": 52.8,
|
| 59 |
+
"official_nvfp4_mxfp8_size_gb": 20.16,
|
| 60 |
+
"quantized_parameter_coverage_pct": 99.85,
|
| 61 |
+
"unquantized_bf16_fp32_mb": 124.6,
|
| 62 |
+
"maxcomp_p2_all_moe": {
|
| 63 |
+
"checkpoint_file": "inkling2_mini_p2_maxcomp.safetensors",
|
| 64 |
+
"recipe": "All 24 MoE expert banks P2_G32 (2.50 bpw) + attention/embed/lm_head/vision P4_G32 (4.50 bpw)",
|
| 65 |
+
"disk_gb": 8.829,
|
| 66 |
+
"resident_vram_gb": 8.829,
|
| 67 |
+
"compression_vs_bf16": 5.98,
|
| 68 |
+
"rx9060xt_4k_decode_tok_per_sec": 56.23,
|
| 69 |
+
"eval_1849_toks": {
|
| 70 |
+
"mean_kld": 0.11384,
|
| 71 |
+
"top1_agreement_pct": 91.35,
|
| 72 |
+
"ref_ppl": 2.1416,
|
| 73 |
+
"q_ppl": 2.2143,
|
| 74 |
+
"delta_loss": 0.03339,
|
| 75 |
+
"python_code_kld": 0.04086,
|
| 76 |
+
"python_code_top1_pct": 95.39,
|
| 77 |
+
"systems_cpp_kld": 0.0337,
|
| 78 |
+
"systems_cpp_top1_pct": 96.9
|
| 79 |
+
}
|
| 80 |
+
},
|
| 81 |
+
"loop_top8_p2_p4_hybrid": {
|
| 82 |
+
"checkpoint_file": "inkling2_mini_p2_looptop8.safetensors",
|
| 83 |
+
"recipe": "16 MoE expert banks P2_G32 (2.50 bpw) + top-8 looped/boundary MoE layers [5,8,9,11,12,14,15,16] P4_G32 (4.50 bpw) + attention/embed/lm_head/vision P4_G32",
|
| 84 |
+
"disk_gb": 10.868,
|
| 85 |
+
"resident_vram_gb": 10.867,
|
| 86 |
+
"compression_vs_bf16": 4.86,
|
| 87 |
+
"meta_load_secs": 6.76,
|
| 88 |
+
"rx9060xt_4k_decode_tok_per_sec": 54.22,
|
| 89 |
+
"rx9060xt_16k_decode_tok_per_sec": 48.6,
|
| 90 |
+
"rx9060xt_16k_peak_vram_gb": 15.67,
|
| 91 |
+
"greedy_24tok_parity_vs_eager": "24/24",
|
| 92 |
+
"eval_1849_toks": {
|
| 93 |
+
"mean_kld": 0.0542,
|
| 94 |
+
"top1_agreement_pct": 93.35,
|
| 95 |
+
"ref_ppl": 2.1416,
|
| 96 |
+
"q_ppl": 2.1542,
|
| 97 |
+
"delta_loss": 0.00586,
|
| 98 |
+
"python_code_kld": 0.02169,
|
| 99 |
+
"python_code_top1_pct": 97.5,
|
| 100 |
+
"systems_cpp_kld": 0.01806,
|
| 101 |
+
"systems_cpp_top1_pct": 97.61,
|
| 102 |
+
"math_reasoning_kld": 0.04371,
|
| 103 |
+
"math_reasoning_top1_pct": 93.59
|
| 104 |
+
},
|
| 105 |
+
"adversarial_spreadsheet_dag_arena": {
|
| 106 |
+
"head_to_head_4500tok_cap": {
|
| 107 |
+
"prime_quant_stage_a": "6/6 (Iter 3, 5.3 min, 47.7-49.3 tok/s)",
|
| 108 |
+
"prime_quant_stage_b_15tests": "14/15 (Iter 2, 8.4 min, 46.9-48.1 tok/s)",
|
| 109 |
+
"official_bf16_24core_hybrid_stage_a": "4/6 (3 iters truncated at 4500 toks, 92.5 min, 2.57-2.62 tok/s)",
|
| 110 |
+
"speedup_vs_offloaded_bf16": 18.6
|
| 111 |
+
},
|
| 112 |
+
"fixed_16k_ctx_8192tok_cap": {
|
| 113 |
+
"truncations": "0/6 turns (100% finish=stop)",
|
| 114 |
+
"stage_a": "6/6 (Iter 2, 335-line class AST, 4381 toks)"
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%}
|
| 2 |
+
{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
|
| 3 |
+
|
| 4 |
+
{%- macro emit_thinking_effort() -%}
|
| 5 |
+
{%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%}
|
| 6 |
+
{%- if eff is string -%}
|
| 7 |
+
{%- set key = eff | trim -%}
|
| 8 |
+
{%- if key not in effort_map -%}
|
| 9 |
+
{{- raise_exception("Unknown reasoning_effort: " ~ eff) -}}
|
| 10 |
+
{%- endif -%}
|
| 11 |
+
{%- set num = effort_map[key] -%}
|
| 12 |
+
{%- else -%}
|
| 13 |
+
{%- set num = eff | float -%}
|
| 14 |
+
{%- endif -%}
|
| 15 |
+
{%- if num < 0.0 or num > 0.99 -%}
|
| 16 |
+
{{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}}
|
| 17 |
+
{%- endif -%}
|
| 18 |
+
{{- "<|message_system|><|content_text|>Thinking effort level: " -}}
|
| 19 |
+
{%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%}
|
| 20 |
+
{{- "<|end_message|>" -}}
|
| 21 |
+
{%- endmacro -%}
|
| 22 |
+
|
| 23 |
+
{%- if tools -%}
|
| 24 |
+
{%- set tool_state = namespace(specs=[]) -%}
|
| 25 |
+
{%- for tool in tools -%}
|
| 26 |
+
{%- set fn = tool.function if tool.function is defined else tool -%}
|
| 27 |
+
{%- set spec = {
|
| 28 |
+
"description": (fn.description if fn.description is defined and fn.description else ""),
|
| 29 |
+
"name": fn.name,
|
| 30 |
+
"parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}),
|
| 31 |
+
"type": (tool.type if tool.type is defined and tool.type else "function"),
|
| 32 |
+
} -%}
|
| 33 |
+
{%- set tool_state.specs = tool_state.specs + [spec] -%}
|
| 34 |
+
{%- endfor -%}
|
| 35 |
+
{{- "<|message_system|>tool_declare<|content_xml|>" -}}
|
| 36 |
+
{{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}}
|
| 37 |
+
{{- "<|end_message|>" -}}
|
| 38 |
+
{%- endif -%}
|
| 39 |
+
|
| 40 |
+
{%- set state = namespace(effort_emitted=false) -%}
|
| 41 |
+
{%- for message in messages -%}
|
| 42 |
+
{%- if message.role not in role_token -%}
|
| 43 |
+
{{- raise_exception("Unknown message role: " ~ message.role) -}}
|
| 44 |
+
{%- endif -%}
|
| 45 |
+
{%- if not state.effort_emitted and message.role != "system" -%}
|
| 46 |
+
{{- emit_thinking_effort() -}}
|
| 47 |
+
{%- set state.effort_emitted = true -%}
|
| 48 |
+
{%- endif -%}
|
| 49 |
+
|
| 50 |
+
{%- set header = namespace(text=role_token[message.role]) -%}
|
| 51 |
+
{%- if message.role == "tool" -%}
|
| 52 |
+
{%- if message.name is defined and message.name -%}
|
| 53 |
+
{%- set header.text = header.text ~ message.name -%}
|
| 54 |
+
{%- elif message.tool_call_id is defined and message.tool_call_id -%}
|
| 55 |
+
{%- for prev in messages -%}
|
| 56 |
+
{%- if prev.role == "assistant" and prev.tool_calls -%}
|
| 57 |
+
{%- for tc in prev.tool_calls -%}
|
| 58 |
+
{%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%}
|
| 59 |
+
{%- set header.text = header.text ~ tc.function.name -%}
|
| 60 |
+
{%- endif -%}
|
| 61 |
+
{%- endfor -%}
|
| 62 |
+
{%- endif -%}
|
| 63 |
+
{%- endfor -%}
|
| 64 |
+
{%- endif -%}
|
| 65 |
+
{%- elif message.role == "assistant" and message.name is defined and message.name -%}
|
| 66 |
+
{%- set header.text = header.text ~ message.name -%}
|
| 67 |
+
{%- endif -%}
|
| 68 |
+
{%- set rtok = header.text -%}
|
| 69 |
+
{%- set rendered -%}
|
| 70 |
+
|
| 71 |
+
{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%}
|
| 72 |
+
{{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}}
|
| 73 |
+
{%- endif -%}
|
| 74 |
+
|
| 75 |
+
{%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%}
|
| 76 |
+
{{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}}
|
| 77 |
+
{%- elif message.content -%}
|
| 78 |
+
{%- for part in message.content -%}
|
| 79 |
+
{%- if part is string -%}
|
| 80 |
+
{{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}}
|
| 81 |
+
{%- elif part.type is not defined or part.type in ("text", "input_text") -%}
|
| 82 |
+
{%- set text_part = (part.text if part.text is defined and part.text is string else "") -%}
|
| 83 |
+
{{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}}
|
| 84 |
+
{%- elif part.type in ("image", "input_image", "image_url") -%}
|
| 85 |
+
{%- if message.role not in ("user", "tool") -%}
|
| 86 |
+
{{- raise_exception("Image content is only supported for user and tool messages") -}}
|
| 87 |
+
{%- endif -%}
|
| 88 |
+
{{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}}
|
| 89 |
+
{%- elif part.type in ("audio", "input_audio", "audio_url") -%}
|
| 90 |
+
{{- raise_exception("Inkling 2 does not accept audio input") -}}
|
| 91 |
+
{%- else -%}
|
| 92 |
+
{{- raise_exception("Unsupported content part type: " ~ part.type) -}}
|
| 93 |
+
{%- endif -%}
|
| 94 |
+
{%- endfor -%}
|
| 95 |
+
{%- endif -%}
|
| 96 |
+
|
| 97 |
+
{%- if message.role == "assistant" and message.tool_calls -%}
|
| 98 |
+
{%- for tc in message.tool_calls -%}
|
| 99 |
+
{%- set fn = tc.function -%}
|
| 100 |
+
{%- if fn.name is not defined or fn.name is not string -%}
|
| 101 |
+
{{- raise_exception("tool call function name must be a string") -}}
|
| 102 |
+
{%- endif -%}
|
| 103 |
+
{%- if message.name is defined and message.name and message.name != fn.name -%}
|
| 104 |
+
{{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}}
|
| 105 |
+
{%- endif -%}
|
| 106 |
+
{%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%}
|
| 107 |
+
{%- if args is string -%}
|
| 108 |
+
{{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}}
|
| 109 |
+
{%- endif -%}
|
| 110 |
+
{%- if args is not mapping -%}
|
| 111 |
+
{{- raise_exception("tool call arguments must be an object") -}}
|
| 112 |
+
{%- endif -%}
|
| 113 |
+
{{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}}
|
| 114 |
+
{{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}}
|
| 115 |
+
{{- "{" -}}
|
| 116 |
+
{%- for key, value in args | dictsort(case_sensitive=true) -%}
|
| 117 |
+
{{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}}
|
| 118 |
+
{%- if not loop.last -%},{%- endif -%}
|
| 119 |
+
{%- endfor -%}
|
| 120 |
+
{{- "}}<|end_message|>" -}}
|
| 121 |
+
{%- endfor -%}
|
| 122 |
+
{%- endif -%}
|
| 123 |
+
|
| 124 |
+
{%- if message.role == "assistant" -%}
|
| 125 |
+
{{- "<|content_model_end_sampling|>" -}}
|
| 126 |
+
{%- endif -%}
|
| 127 |
+
{%- endset -%}
|
| 128 |
+
{%- if message.role == "assistant" -%}
|
| 129 |
+
{%- generation -%}{{- rendered -}}{%- endgeneration -%}
|
| 130 |
+
{%- else -%}
|
| 131 |
+
{{- rendered -}}
|
| 132 |
+
{%- endif -%}
|
| 133 |
+
{%- endfor -%}
|
| 134 |
+
|
| 135 |
+
{%- if not state.effort_emitted -%}
|
| 136 |
+
{{- emit_thinking_effort() -}}
|
| 137 |
+
{%- endif -%}
|
config.json
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dtype": "bfloat16",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"Inkling2LoopForConditionalGeneration"
|
| 5 |
+
],
|
| 6 |
+
"model_type": "inkling2_loop",
|
| 7 |
+
"eos_token_id": 200006,
|
| 8 |
+
"text_config": {
|
| 9 |
+
"model_type": "inkling2_loop_text",
|
| 10 |
+
"model_max_length": 1048576,
|
| 11 |
+
"torch_dtype": "bfloat16",
|
| 12 |
+
"hidden_size": 2304,
|
| 13 |
+
"num_hidden_layers": 24,
|
| 14 |
+
"vocab_size": 201024,
|
| 15 |
+
"num_attention_heads": 24,
|
| 16 |
+
"num_key_value_heads": 8,
|
| 17 |
+
"head_dim": 128,
|
| 18 |
+
"d_rel": 16,
|
| 19 |
+
"rel_extent": 1024,
|
| 20 |
+
"q_bias": false,
|
| 21 |
+
"o_bias": false,
|
| 22 |
+
"log_scaling_n_floor": 8192,
|
| 23 |
+
"log_scaling_alpha": 0.1,
|
| 24 |
+
"rms_norm_eps": 1e-06,
|
| 25 |
+
"use_value_norm_no_gamma": true,
|
| 26 |
+
"qk_l2_clip_threshold": 22.627416997969522,
|
| 27 |
+
"rel_l2_clip_threshold": 8.0,
|
| 28 |
+
"local_layer_ids": [
|
| 29 |
+
0,
|
| 30 |
+
1,
|
| 31 |
+
2,
|
| 32 |
+
3,
|
| 33 |
+
4,
|
| 34 |
+
6,
|
| 35 |
+
7,
|
| 36 |
+
8,
|
| 37 |
+
9,
|
| 38 |
+
10,
|
| 39 |
+
12,
|
| 40 |
+
13,
|
| 41 |
+
14,
|
| 42 |
+
15,
|
| 43 |
+
16,
|
| 44 |
+
18,
|
| 45 |
+
19,
|
| 46 |
+
20,
|
| 47 |
+
21,
|
| 48 |
+
22
|
| 49 |
+
],
|
| 50 |
+
"sconv_kernel_size": 4,
|
| 51 |
+
"unpadded_vocab_size": 200058,
|
| 52 |
+
"final_logit_softcapping": 30.0,
|
| 53 |
+
"swa_head_dim": 128,
|
| 54 |
+
"swa_num_attention_heads": 24,
|
| 55 |
+
"swa_num_key_value_heads": 8,
|
| 56 |
+
"sliding_window_size": 1024,
|
| 57 |
+
"n_layers_per_attn_res_block": 6,
|
| 58 |
+
"attn_res_normalize_values": true,
|
| 59 |
+
"n_routed_experts": 128,
|
| 60 |
+
"num_experts_per_tok": 8,
|
| 61 |
+
"n_shared_experts": 0,
|
| 62 |
+
"intermediate_size": 1152,
|
| 63 |
+
"mlp_gate_softcap": 4.0,
|
| 64 |
+
"mlp_up_softcap": 25.0,
|
| 65 |
+
"route_scale": 8.0,
|
| 66 |
+
"use_gate_bias": true,
|
| 67 |
+
"loop_config": {
|
| 68 |
+
"core_start": 6,
|
| 69 |
+
"core_end": 18,
|
| 70 |
+
"num_passes": 3,
|
| 71 |
+
"gate_rank": 64,
|
| 72 |
+
"is_varloop": false
|
| 73 |
+
}
|
| 74 |
+
},
|
| 75 |
+
"vision_config": {
|
| 76 |
+
"model_type": "inkling2_vision",
|
| 77 |
+
"text_hidden_size": 2304,
|
| 78 |
+
"temporal_patch_size": 2,
|
| 79 |
+
"native_patch_size": 20,
|
| 80 |
+
"adapter_merge_size": 2,
|
| 81 |
+
"projection_hidden_dim": 4096,
|
| 82 |
+
"projector_bias": false,
|
| 83 |
+
"hidden_size": 1024,
|
| 84 |
+
"num_hidden_layers": 23,
|
| 85 |
+
"num_attention_heads": 16,
|
| 86 |
+
"mlp_ratio": 4.0,
|
| 87 |
+
"posemb_grid_size": 32,
|
| 88 |
+
"layer_norm_eps": 1e-05
|
| 89 |
+
},
|
| 90 |
+
"mtp_config": {
|
| 91 |
+
"hidden_size": 2304,
|
| 92 |
+
"num_hidden_layers": 3,
|
| 93 |
+
"num_attention_heads": 24,
|
| 94 |
+
"num_key_value_heads": 8,
|
| 95 |
+
"head_dim": 128,
|
| 96 |
+
"intermediate_size": 9216,
|
| 97 |
+
"max_position_embeddings": 1048576,
|
| 98 |
+
"torch_dtype": "bfloat16",
|
| 99 |
+
"q_bias": false,
|
| 100 |
+
"o_bias": false,
|
| 101 |
+
"rms_norm_eps": 1e-06,
|
| 102 |
+
"rope_theta": 1000000.0,
|
| 103 |
+
"local_layer_ids": [
|
| 104 |
+
0,
|
| 105 |
+
2
|
| 106 |
+
],
|
| 107 |
+
"sliding_window_size": 1024,
|
| 108 |
+
"block_size": 8,
|
| 109 |
+
"markov_rank": 256,
|
| 110 |
+
"markov_head_type": "rnn_hidden",
|
| 111 |
+
"target_layer_ids": [
|
| 112 |
+
5,
|
| 113 |
+
23,
|
| 114 |
+
41,
|
| 115 |
+
48
|
| 116 |
+
]
|
| 117 |
+
}
|
| 118 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"do_sample": true,
|
| 3 |
+
"temperature": 1.0,
|
| 4 |
+
"eos_token_id": 200006,
|
| 5 |
+
"pad_token_id": 199999
|
| 6 |
+
}
|
inkling2_kernels.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2026 Philip Bartsch (@batteryphil).
|
| 2 |
+
# Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE).
|
| 3 |
+
"""
|
| 4 |
+
Exact Fused Triton Decode Kernels for `thinkingmachines/Inkling-2-Mini`
|
| 5 |
+
=======================================================================
|
| 6 |
+
Eliminates the `~43 ms/tok` non-quantized PyTorch/rocBLAS overhead inside `Inkling-2-Mini`'s
|
| 7 |
+
48-pass looped decode step while preserving 100% exact mathematical parity with Hugging Face
|
| 8 |
+
`transformers.models.inkling2_loop.modeling_inkling2_loop`:
|
| 9 |
+
|
| 10 |
+
1. `short_conv1d_step_res_triton` (176 calls/tok): in-place 4-tap conv state shift + residual / sqrt(5)
|
| 11 |
+
2. `dyn_short_conv1d_step_res_triton` ( 16 calls/tok): dynamic + static 4-tap conv state shift + residual / 3
|
| 12 |
+
3. `message_gate_triton` ( 96 calls/tok): 2-kernel fused RMSNorm + rank-64 tanh forget/message gate
|
| 13 |
+
4. `attn_res_step_triton` (120 calls/tok): 2-kernel fused Block & Message Attention Residuals (zero rocBLAS)
|
| 14 |
+
5. `dense_gemv_triton` (112 calls/tok): fast M=1 FP32/BF16 GEMV for TopKRouter, sink_proj, weight_proj
|
| 15 |
+
6. `inkling2_decode_attn_triton` ( 48 calls/tok): fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer
|
| 16 |
+
Sliding Window / Full Attention (supports 1K..32K+ context in
|
| 17 |
+
one single HIP/CUDA Graph with zero per-token KV cache roll!)
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import triton
|
| 27 |
+
import triton.language as tl
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@triton.jit
|
| 31 |
+
def _short_conv1d_step_res_kernel(
|
| 32 |
+
x_ptr,
|
| 33 |
+
state_ptr,
|
| 34 |
+
w_ptr,
|
| 35 |
+
out_ptr,
|
| 36 |
+
C,
|
| 37 |
+
INV_SCALE: tl.constexpr,
|
| 38 |
+
BLOCK_C: tl.constexpr,
|
| 39 |
+
):
|
| 40 |
+
"""In-place 4-tap static depthwise causal conv1d update + residual / sqrt(5) for B=1, T=1."""
|
| 41 |
+
pid = tl.program_id(0)
|
| 42 |
+
c = pid * BLOCK_C + tl.arange(0, BLOCK_C)
|
| 43 |
+
m = c < C
|
| 44 |
+
|
| 45 |
+
x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32)
|
| 46 |
+
base = c * 4
|
| 47 |
+
s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32)
|
| 48 |
+
s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32)
|
| 49 |
+
s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32)
|
| 50 |
+
s3 = x_f
|
| 51 |
+
|
| 52 |
+
tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m)
|
| 53 |
+
tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m)
|
| 54 |
+
tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m)
|
| 55 |
+
tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m)
|
| 56 |
+
|
| 57 |
+
w0 = tl.load(w_ptr + base + 0, mask=m, other=0.0).to(tl.float32)
|
| 58 |
+
w1 = tl.load(w_ptr + base + 1, mask=m, other=0.0).to(tl.float32)
|
| 59 |
+
w2 = tl.load(w_ptr + base + 2, mask=m, other=0.0).to(tl.float32)
|
| 60 |
+
w3 = tl.load(w_ptr + base + 3, mask=m, other=0.0).to(tl.float32)
|
| 61 |
+
|
| 62 |
+
dot = s0 * w0 + s1 * w1 + s2 * w2 + s3 * w3
|
| 63 |
+
out = (dot + x_f) * INV_SCALE
|
| 64 |
+
tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@triton.jit
|
| 68 |
+
def _dyn_short_conv1d_step_res_kernel(
|
| 69 |
+
x_ptr,
|
| 70 |
+
state_ptr,
|
| 71 |
+
static_w_ptr, # [4, C] row-major: lag 0 = current token, lag 3 = oldest
|
| 72 |
+
dyn_w_ptr, # [num_heads, 4] row-major
|
| 73 |
+
out_ptr,
|
| 74 |
+
C,
|
| 75 |
+
HEAD_DIM: tl.constexpr,
|
| 76 |
+
INV_SCALE: tl.constexpr,
|
| 77 |
+
BLOCK_C: tl.constexpr,
|
| 78 |
+
):
|
| 79 |
+
"""In-place 4-tap dynamic+static causal conv1d update + residual / sqrt(9) for B=1, T=1."""
|
| 80 |
+
pid = tl.program_id(0)
|
| 81 |
+
c = pid * BLOCK_C + tl.arange(0, BLOCK_C)
|
| 82 |
+
m = c < C
|
| 83 |
+
h = c // HEAD_DIM
|
| 84 |
+
|
| 85 |
+
x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32)
|
| 86 |
+
base = c * 4
|
| 87 |
+
s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32) # lag 3 (oldest)
|
| 88 |
+
s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32) # lag 2
|
| 89 |
+
s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32) # lag 1
|
| 90 |
+
s3 = x_f # lag 0 (current)
|
| 91 |
+
|
| 92 |
+
tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m)
|
| 93 |
+
tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m)
|
| 94 |
+
tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m)
|
| 95 |
+
tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m)
|
| 96 |
+
|
| 97 |
+
# static_w[lag, c] + dyn_w[h, lag] where lag 0 multiplies s3 (current) and lag 3 multiplies s0 (oldest)
|
| 98 |
+
w_lag0 = tl.load(static_w_ptr + 0 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 0, mask=m, other=0.0).to(tl.float32)
|
| 99 |
+
w_lag1 = tl.load(static_w_ptr + 1 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 1, mask=m, other=0.0).to(tl.float32)
|
| 100 |
+
w_lag2 = tl.load(static_w_ptr + 2 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 2, mask=m, other=0.0).to(tl.float32)
|
| 101 |
+
w_lag3 = tl.load(static_w_ptr + 3 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 3, mask=m, other=0.0).to(tl.float32)
|
| 102 |
+
|
| 103 |
+
dot = s3 * w_lag0 + s2 * w_lag1 + s1 * w_lag2 + s0 * w_lag3
|
| 104 |
+
out = (dot + x_f) * INV_SCALE
|
| 105 |
+
tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@triton.jit
|
| 109 |
+
def _dense_gemv_kernel(
|
| 110 |
+
x_ptr,
|
| 111 |
+
w_ptr,
|
| 112 |
+
out_ptr,
|
| 113 |
+
rows,
|
| 114 |
+
cols,
|
| 115 |
+
BLOCK_R: tl.constexpr,
|
| 116 |
+
BLOCK_K: tl.constexpr,
|
| 117 |
+
):
|
| 118 |
+
"""Coalesced FP32/BF16 M=1 GEMV (y = W @ x) bypassing slow rocBLAS small-M Tensile kernels."""
|
| 119 |
+
pid = tl.program_id(0)
|
| 120 |
+
r = pid * BLOCK_R + tl.arange(0, BLOCK_R)
|
| 121 |
+
r_mask = r < rows
|
| 122 |
+
r_i64 = r.to(tl.int64)
|
| 123 |
+
acc = tl.zeros((BLOCK_R,), dtype=tl.float32)
|
| 124 |
+
k_offs = tl.arange(0, BLOCK_K)
|
| 125 |
+
for k0 in range(0, cols, BLOCK_K):
|
| 126 |
+
k = k0 + k_offs
|
| 127 |
+
k_mask = k < cols
|
| 128 |
+
xv = tl.load(x_ptr + k, mask=k_mask, other=0.0).to(tl.float32)
|
| 129 |
+
wv = tl.load(w_ptr + r_i64[:, None] * cols + k[None, :], mask=r_mask[:, None] & k_mask[None, :], other=0.0).to(tl.float32)
|
| 130 |
+
acc += tl.sum(wv * xv[None, :], axis=1)
|
| 131 |
+
tl.store(out_ptr + r, acc.to(out_ptr.dtype.element_ty), mask=r_mask)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@triton.jit
|
| 135 |
+
def _msg_gate_stage1_kernel(
|
| 136 |
+
h_ptr,
|
| 137 |
+
m_ptr,
|
| 138 |
+
wdn_ptr, # [R=64, 2*H] bf16/fp32
|
| 139 |
+
g_ptr, # [R=64] fp32
|
| 140 |
+
R,
|
| 141 |
+
H,
|
| 142 |
+
eps,
|
| 143 |
+
BLOCK_R: tl.constexpr,
|
| 144 |
+
BLOCK_K: tl.constexpr,
|
| 145 |
+
):
|
| 146 |
+
"""Fused RMSNorm(h), RMSNorm(m), and down_proj -> g[64] in fp32 (exact cast parity with wdn.dtype)."""
|
| 147 |
+
pid = tl.program_id(0)
|
| 148 |
+
r = pid * BLOCK_R + tl.arange(0, BLOCK_R)
|
| 149 |
+
r_mask = r < R
|
| 150 |
+
r_i64 = r.to(tl.int64)
|
| 151 |
+
k_offs = tl.arange(0, BLOCK_K)
|
| 152 |
+
|
| 153 |
+
ss_h = 0.0
|
| 154 |
+
ss_m = 0.0
|
| 155 |
+
for k0 in range(0, H, BLOCK_K):
|
| 156 |
+
k = k0 + k_offs
|
| 157 |
+
km = k < H
|
| 158 |
+
hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32)
|
| 159 |
+
mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32)
|
| 160 |
+
ss_h += tl.sum(hv * hv, axis=0)
|
| 161 |
+
ss_m += tl.sum(mv * mv, axis=0)
|
| 162 |
+
inv_h = tl.rsqrt(ss_h / H + eps)
|
| 163 |
+
inv_m = tl.rsqrt(ss_m / H + eps)
|
| 164 |
+
|
| 165 |
+
acc = tl.zeros((BLOCK_R,), dtype=tl.float32)
|
| 166 |
+
stride_r = 2 * H
|
| 167 |
+
for k0 in range(0, H, BLOCK_K):
|
| 168 |
+
k = k0 + k_offs
|
| 169 |
+
km = k < H
|
| 170 |
+
hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32)
|
| 171 |
+
mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32)
|
| 172 |
+
# Match upstream `gate_hidden_states.to(self.down_proj.weight.dtype)` rounding
|
| 173 |
+
hn = (hv * inv_h).to(wdn_ptr.dtype.element_ty).to(tl.float32)
|
| 174 |
+
mn = (mv * inv_m).to(wdn_ptr.dtype.element_ty).to(tl.float32)
|
| 175 |
+
w0 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + k[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32)
|
| 176 |
+
w1 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + (H + k)[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32)
|
| 177 |
+
acc += tl.sum(w0 * hn[None, :] + w1 * mn[None, :], axis=1)
|
| 178 |
+
tl.store(g_ptr + r, acc, mask=r_mask)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@triton.jit
|
| 182 |
+
def _msg_gate_stage2_kernel(
|
| 183 |
+
h_ptr,
|
| 184 |
+
m_ptr,
|
| 185 |
+
g_ptr, # [R=64] fp32
|
| 186 |
+
wfg_ptr, # [H, R=64] fp32
|
| 187 |
+
wmg_ptr, # [H, R=64] fp32
|
| 188 |
+
out_ptr, # [H] fp32
|
| 189 |
+
H,
|
| 190 |
+
R: tl.constexpr,
|
| 191 |
+
BLOCK_H: tl.constexpr,
|
| 192 |
+
):
|
| 193 |
+
"""Fused tanh(w_fg @ g), tanh(w_mg @ g), and (1 - fg) * h + mg * m -> fp32."""
|
| 194 |
+
pid = tl.program_id(0)
|
| 195 |
+
h_idx = pid * BLOCK_H + tl.arange(0, BLOCK_H)
|
| 196 |
+
hm = h_idx < H
|
| 197 |
+
h_i64 = h_idx.to(tl.int64)
|
| 198 |
+
|
| 199 |
+
r_offs = tl.arange(0, R)
|
| 200 |
+
gv = tl.load(g_ptr + r_offs).to(tl.float32)
|
| 201 |
+
|
| 202 |
+
off = h_i64[:, None] * R + r_offs[None, :]
|
| 203 |
+
wfg = tl.load(wfg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32)
|
| 204 |
+
wmg = tl.load(wmg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32)
|
| 205 |
+
|
| 206 |
+
fg_pre = tl.sum(wfg * gv[None, :], axis=1)
|
| 207 |
+
mg_pre = tl.sum(wmg * gv[None, :], axis=1)
|
| 208 |
+
fg = 2.0 * tl.sigmoid(2.0 * fg_pre) - 1.0
|
| 209 |
+
mg = 2.0 * tl.sigmoid(2.0 * mg_pre) - 1.0
|
| 210 |
+
|
| 211 |
+
hv = tl.load(h_ptr + h_idx, mask=hm, other=0.0).to(tl.float32)
|
| 212 |
+
mv = tl.load(m_ptr + h_idx, mask=hm, other=0.0).to(tl.float32)
|
| 213 |
+
out = (1.0 - fg) * hv + mg * mv
|
| 214 |
+
tl.store(out_ptr + h_idx, out, mask=hm)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@triton.jit
|
| 218 |
+
def _attn_res_stage1_kernel(
|
| 219 |
+
bs_ptr, # [S_prev, H]
|
| 220 |
+
part_ptr, # [H]
|
| 221 |
+
q_ptr, # [Q, H] fp32
|
| 222 |
+
inv_rms_ptr, # [S] fp32
|
| 223 |
+
scores_ptr, # [Q, S] fp32
|
| 224 |
+
S_prev,
|
| 225 |
+
H,
|
| 226 |
+
Q,
|
| 227 |
+
Q_PAD: tl.constexpr,
|
| 228 |
+
BLOCK_K: tl.constexpr,
|
| 229 |
+
):
|
| 230 |
+
"""Single-pass AttnRes stage 1: computes inv_rms[s] and (q @ v) * inv_rms / sqrt(H) in ONE pass over H."""
|
| 231 |
+
s = tl.program_id(0)
|
| 232 |
+
is_part = s == S_prev
|
| 233 |
+
s_i64 = s.to(tl.int64)
|
| 234 |
+
k_offs = tl.arange(0, BLOCK_K)
|
| 235 |
+
q_offs = tl.arange(0, Q_PAD)
|
| 236 |
+
qm = q_offs < Q
|
| 237 |
+
q_i64 = q_offs.to(tl.int64)
|
| 238 |
+
|
| 239 |
+
ss = 0.0
|
| 240 |
+
acc = tl.zeros((Q_PAD,), dtype=tl.float32)
|
| 241 |
+
for k0 in range(0, H, BLOCK_K):
|
| 242 |
+
k = k0 + k_offs
|
| 243 |
+
km = k < H
|
| 244 |
+
if is_part:
|
| 245 |
+
v = tl.load(part_ptr + k, mask=km, other=0.0).to(tl.float32)
|
| 246 |
+
else:
|
| 247 |
+
v = tl.load(bs_ptr + s_i64 * H + k, mask=km, other=0.0).to(tl.float32)
|
| 248 |
+
ss += tl.sum(v * v, axis=0)
|
| 249 |
+
qv = tl.load(q_ptr + q_i64[:, None] * H + k[None, :], mask=qm[:, None] & km[None, :], other=0.0).to(tl.float32)
|
| 250 |
+
acc += tl.sum(qv * v[None, :], axis=1)
|
| 251 |
+
|
| 252 |
+
inv_r = tl.rsqrt(ss / H + 1.0e-6)
|
| 253 |
+
tl.store(inv_rms_ptr + s, inv_r)
|
| 254 |
+
scale = inv_r * tl.rsqrt(tl.cast(H, tl.float32))
|
| 255 |
+
S_tot = S_prev + 1
|
| 256 |
+
tl.store(scores_ptr + q_i64 * S_tot + s, acc * scale, mask=qm)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@triton.jit
|
| 260 |
+
def _router_topk_kernel(
|
| 261 |
+
logits_ptr,
|
| 262 |
+
bias_ptr,
|
| 263 |
+
out_w_ptr,
|
| 264 |
+
out_idx_ptr,
|
| 265 |
+
scale,
|
| 266 |
+
E: tl.constexpr,
|
| 267 |
+
TOP_K: tl.constexpr,
|
| 268 |
+
):
|
| 269 |
+
"""Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale (4.25x faster than 4 PyTorch kernels)."""
|
| 270 |
+
offs = tl.arange(0, E)
|
| 271 |
+
logits = tl.load(logits_ptr + offs).to(tl.float32)
|
| 272 |
+
bias = tl.load(bias_ptr + offs).to(tl.float32)
|
| 273 |
+
scores = tl.sigmoid(logits)
|
| 274 |
+
biased = scores + bias
|
| 275 |
+
|
| 276 |
+
w_sum = 0.0
|
| 277 |
+
for k in tl.static_range(0, TOP_K):
|
| 278 |
+
idx = tl.argmax(biased, axis=0)
|
| 279 |
+
w_k = tl.sum(tl.where(offs == idx, scores, 0.0), axis=0)
|
| 280 |
+
w_sum += w_k
|
| 281 |
+
tl.store(out_idx_ptr + k, idx.to(tl.int64))
|
| 282 |
+
tl.store(out_w_ptr + k, w_k)
|
| 283 |
+
biased = tl.where(offs == idx, -1.0e30, biased)
|
| 284 |
+
|
| 285 |
+
inv_sum = scale / (w_sum + 1.0e-20)
|
| 286 |
+
k_offs = tl.arange(0, TOP_K)
|
| 287 |
+
wk_all = tl.load(out_w_ptr + k_offs) * inv_sum
|
| 288 |
+
tl.store(out_w_ptr + k_offs, wk_all)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@triton.jit
|
| 292 |
+
def _unweighted_rmsnorm_kernel(
|
| 293 |
+
x_ptr,
|
| 294 |
+
out_ptr,
|
| 295 |
+
eps,
|
| 296 |
+
D: tl.constexpr,
|
| 297 |
+
):
|
| 298 |
+
"""Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than 4-op eager path)."""
|
| 299 |
+
row = tl.program_id(0).to(tl.int64)
|
| 300 |
+
d = tl.arange(0, D)
|
| 301 |
+
xv = tl.load(x_ptr + row * D + d).to(tl.float32)
|
| 302 |
+
inv_r = tl.rsqrt(tl.sum(xv * xv, axis=0) / D + eps)
|
| 303 |
+
tl.store(out_ptr + row * D + d, (xv * inv_r).to(out_ptr.dtype.element_ty))
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@triton.jit
|
| 307 |
+
def _attn_res_stage2_kernel(
|
| 308 |
+
bs_ptr, # [S_prev, H]
|
| 309 |
+
part_ptr, # [H]
|
| 310 |
+
inv_rms_ptr, # [S] fp32
|
| 311 |
+
scores_ptr, # [Q, S] fp32
|
| 312 |
+
out_ptr, # [Q, H] fp32
|
| 313 |
+
S_prev,
|
| 314 |
+
H,
|
| 315 |
+
Q,
|
| 316 |
+
Q_PAD: tl.constexpr,
|
| 317 |
+
S_PAD: tl.constexpr,
|
| 318 |
+
BLOCK_H: tl.constexpr,
|
| 319 |
+
):
|
| 320 |
+
"""Applies exact softmax over S states and accumulates weighted normalized states -> [Q, H] fp32."""
|
| 321 |
+
pid = tl.program_id(0)
|
| 322 |
+
h = pid * BLOCK_H + tl.arange(0, BLOCK_H)
|
| 323 |
+
hm = h < H
|
| 324 |
+
h_i64 = h.to(tl.int64)
|
| 325 |
+
|
| 326 |
+
S_tot = S_prev + 1
|
| 327 |
+
s_offs = tl.arange(0, S_PAD)
|
| 328 |
+
s_mask = s_offs < S_tot
|
| 329 |
+
q_offs = tl.arange(0, Q_PAD)
|
| 330 |
+
qm = q_offs < Q
|
| 331 |
+
q_i64 = q_offs.to(tl.int64)
|
| 332 |
+
|
| 333 |
+
# Load scores [Q_PAD, S_PAD] and compute softmax over axis=1
|
| 334 |
+
sc = tl.load(
|
| 335 |
+
scores_ptr + q_i64[:, None] * S_tot + s_offs[None, :],
|
| 336 |
+
mask=qm[:, None] & s_mask[None, :],
|
| 337 |
+
other=-1.0e9,
|
| 338 |
+
)
|
| 339 |
+
sc_max = tl.max(sc, axis=1)[:, None]
|
| 340 |
+
ex = tl.where(s_mask[None, :], tl.exp(sc - sc_max), 0.0)
|
| 341 |
+
w = ex / tl.sum(ex, axis=1)[:, None] # [Q_PAD, S_PAD]
|
| 342 |
+
|
| 343 |
+
inv_r = tl.load(inv_rms_ptr + s_offs, mask=s_mask, other=0.0) # [S_PAD]
|
| 344 |
+
w_eff = w * inv_r[None, :] # [Q_PAD, S_PAD]
|
| 345 |
+
|
| 346 |
+
acc = tl.zeros((Q_PAD, BLOCK_H), dtype=tl.float32)
|
| 347 |
+
for s in range(0, S_tot):
|
| 348 |
+
if s == S_prev:
|
| 349 |
+
v = tl.load(part_ptr + h, mask=hm, other=0.0).to(tl.float32)
|
| 350 |
+
else:
|
| 351 |
+
v = tl.load(bs_ptr + tl.cast(s, tl.int64) * H + h, mask=hm, other=0.0).to(tl.float32)
|
| 352 |
+
ws = tl.sum(tl.where(s_offs[None, :] == s, w_eff, 0.0), axis=1) # [Q_PAD]
|
| 353 |
+
acc += ws[:, None] * v[None, :]
|
| 354 |
+
|
| 355 |
+
tl.store(out_ptr + q_i64[:, None] * H + h_i64[None, :], acc, mask=qm[:, None] & hm[None, :])
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@triton.jit
|
| 359 |
+
def _kv_cache_write_kernel(
|
| 360 |
+
k_new_ptr, # [H_kv, D]
|
| 361 |
+
v_new_ptr, # [H_kv, D]
|
| 362 |
+
k_cache_ptr, # [H_kv, L, D]
|
| 363 |
+
v_cache_ptr, # [H_kv, L, D]
|
| 364 |
+
cur_pos_ptr, # [1] int64
|
| 365 |
+
L,
|
| 366 |
+
IS_SLIDING: tl.constexpr,
|
| 367 |
+
SLIDING_MASK: tl.constexpr,
|
| 368 |
+
D: tl.constexpr,
|
| 369 |
+
):
|
| 370 |
+
"""Writes single-token K/V into StaticCache at `pos` (full) or `pos & (W-1)` (ring-buffer sliding)."""
|
| 371 |
+
h = tl.program_id(0)
|
| 372 |
+
d = tl.arange(0, D)
|
| 373 |
+
pos = tl.load(cur_pos_ptr).to(tl.int64)
|
| 374 |
+
slot = (pos & SLIDING_MASK) if IS_SLIDING else pos
|
| 375 |
+
|
| 376 |
+
src_off = h.to(tl.int64) * D + d
|
| 377 |
+
dst_off = (h.to(tl.int64) * L + slot) * D + d
|
| 378 |
+
tl.store(k_cache_ptr + dst_off, tl.load(k_new_ptr + src_off))
|
| 379 |
+
tl.store(v_cache_ptr + dst_off, tl.load(v_new_ptr + src_off))
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@triton.jit
|
| 383 |
+
def _inkling2_decode_attn_kernel(
|
| 384 |
+
q_ptr, # [H_q, D] bf16
|
| 385 |
+
k_cache_ptr, # [H_kv, L, D] bf16
|
| 386 |
+
v_cache_ptr, # [H_kv, L, D] bf16
|
| 387 |
+
rel_s_ptr, # [H_q, D_REL] bf16
|
| 388 |
+
rel_p_ptr, # [D_REL, REL_EXTENT] bf16
|
| 389 |
+
sinks_ptr, # [H_q] bf16
|
| 390 |
+
cur_pos_ptr, # [1] int64
|
| 391 |
+
out_ptr, # [H_q, D] bf16
|
| 392 |
+
L,
|
| 393 |
+
scaling,
|
| 394 |
+
GQA_GROUPS: tl.constexpr,
|
| 395 |
+
IS_SLIDING: tl.constexpr,
|
| 396 |
+
SLIDING_WIN: tl.constexpr,
|
| 397 |
+
REL_EXTENT: tl.constexpr,
|
| 398 |
+
D: tl.constexpr,
|
| 399 |
+
D_REL: tl.constexpr,
|
| 400 |
+
BLOCK_N: tl.constexpr,
|
| 401 |
+
):
|
| 402 |
+
"""
|
| 403 |
+
Exact fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer Sliding/Full Decode Attention.
|
| 404 |
+
Zero `repeat_kv`, zero `[H_q, L]` materialization, dynamic loop bound `j0 < n_valid` inside CUDA Graph.
|
| 405 |
+
"""
|
| 406 |
+
h = tl.program_id(0)
|
| 407 |
+
kv_h = h // GQA_GROUPS
|
| 408 |
+
d = tl.arange(0, D)
|
| 409 |
+
r_idx = tl.arange(0, D_REL)
|
| 410 |
+
|
| 411 |
+
q = tl.load(q_ptr + h.to(tl.int64) * D + d).to(tl.float32) * scaling
|
| 412 |
+
rs = tl.load(rel_s_ptr + h.to(tl.int64) * D_REL + r_idx).to(tl.float32)
|
| 413 |
+
sink = tl.load(sinks_ptr + h).to(tl.float32)
|
| 414 |
+
cur_pos = tl.load(cur_pos_ptr).to(tl.int32)
|
| 415 |
+
|
| 416 |
+
n_valid = tl.minimum(cur_pos + 1, SLIDING_WIN) if IS_SLIDING else (cur_pos + 1)
|
| 417 |
+
|
| 418 |
+
# Exact attention sink initialization: one extra logit `sink` with zero value vector
|
| 419 |
+
m_i = sink
|
| 420 |
+
l_i = 1.0
|
| 421 |
+
acc = tl.zeros((D,), dtype=tl.float32)
|
| 422 |
+
|
| 423 |
+
kv_base = kv_h.to(tl.int64) * L * D
|
| 424 |
+
n_offs = tl.arange(0, BLOCK_N)
|
| 425 |
+
j0 = 0
|
| 426 |
+
while j0 < n_valid:
|
| 427 |
+
j = j0 + n_offs
|
| 428 |
+
j_mask = j < n_valid
|
| 429 |
+
j_i64 = j.to(tl.int64)
|
| 430 |
+
|
| 431 |
+
kv_off = kv_base + j_i64[:, None] * D + d[None, :]
|
| 432 |
+
k_tile = tl.load(k_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32)
|
| 433 |
+
scores = tl.sum(k_tile * q[None, :], axis=1)
|
| 434 |
+
|
| 435 |
+
if IS_SLIDING:
|
| 436 |
+
dist = (cur_pos - j) & (SLIDING_WIN - 1)
|
| 437 |
+
else:
|
| 438 |
+
dist = cur_pos - j
|
| 439 |
+
in_rel = j_mask & (dist >= 0) & (dist < REL_EXTENT)
|
| 440 |
+
dist_safe = tl.where(in_rel, dist, 0).to(tl.int64)
|
| 441 |
+
|
| 442 |
+
rp_off = r_idx[:, None].to(tl.int64) * REL_EXTENT + dist_safe[None, :]
|
| 443 |
+
rp_tile = tl.load(rel_p_ptr + rp_off, mask=in_rel[None, :], other=0.0).to(tl.float32)
|
| 444 |
+
bias = tl.sum(rp_tile * rs[:, None], axis=0)
|
| 445 |
+
scores = scores + tl.where(in_rel, bias, 0.0)
|
| 446 |
+
scores = tl.where(j_mask, scores, -1.0e9)
|
| 447 |
+
|
| 448 |
+
m_blk = tl.max(scores, axis=0)
|
| 449 |
+
m_new = tl.maximum(m_i, m_blk)
|
| 450 |
+
alpha = tl.exp(m_i - m_new)
|
| 451 |
+
p = tl.where(j_mask, tl.exp(scores - m_new), 0.0)
|
| 452 |
+
l_i = l_i * alpha + tl.sum(p, axis=0)
|
| 453 |
+
|
| 454 |
+
v_tile = tl.load(v_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32)
|
| 455 |
+
acc = acc * alpha + tl.sum(p[:, None] * v_tile, axis=0)
|
| 456 |
+
m_i = m_new
|
| 457 |
+
j0 += BLOCK_N
|
| 458 |
+
|
| 459 |
+
out = acc / l_i
|
| 460 |
+
tl.store(out_ptr + h.to(tl.int64) * D + d, out.to(out_ptr.dtype.element_ty))
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def short_conv1d_step_res_triton(
|
| 464 |
+
x: torch.Tensor,
|
| 465 |
+
conv_state: torch.Tensor,
|
| 466 |
+
weight_2d: torch.Tensor,
|
| 467 |
+
) -> torch.Tensor:
|
| 468 |
+
"""Fast Triton 4-tap static short conv update + residual / sqrt(5) for `[1, 1, C]` decode."""
|
| 469 |
+
C = x.shape[-1]
|
| 470 |
+
out = torch.empty_like(x)
|
| 471 |
+
BLOCK_C = 256
|
| 472 |
+
_short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)](
|
| 473 |
+
x.contiguous(),
|
| 474 |
+
conv_state,
|
| 475 |
+
weight_2d.contiguous(),
|
| 476 |
+
out,
|
| 477 |
+
C,
|
| 478 |
+
INV_SCALE=1.0 / math.sqrt(5.0),
|
| 479 |
+
BLOCK_C=BLOCK_C,
|
| 480 |
+
num_warps=4,
|
| 481 |
+
)
|
| 482 |
+
return out
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def dense_gemv_triton(x_1d: torch.Tensor, weight_2d: torch.Tensor, out_dtype: Optional[torch.dtype] = None) -> torch.Tensor:
|
| 486 |
+
"""Fast coalesced M=1 Triton GEMV for small/medium FP32/BF16 linear layers."""
|
| 487 |
+
rows, cols = weight_2d.shape
|
| 488 |
+
dt = out_dtype if out_dtype is not None else x_1d.dtype
|
| 489 |
+
out = torch.empty((rows,), device=weight_2d.device, dtype=dt)
|
| 490 |
+
BLOCK_R = 4 if rows <= 128 else 8
|
| 491 |
+
_dense_gemv_kernel[(triton.cdiv(rows, BLOCK_R),)](
|
| 492 |
+
x_1d.contiguous(),
|
| 493 |
+
weight_2d.contiguous(),
|
| 494 |
+
out,
|
| 495 |
+
rows,
|
| 496 |
+
cols,
|
| 497 |
+
BLOCK_R=BLOCK_R,
|
| 498 |
+
BLOCK_K=256,
|
| 499 |
+
num_warps=4,
|
| 500 |
+
)
|
| 501 |
+
return out
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def dyn_short_conv1d_step_res_triton(
|
| 505 |
+
x: torch.Tensor,
|
| 506 |
+
dynamic_input: torch.Tensor,
|
| 507 |
+
conv_state: torch.Tensor,
|
| 508 |
+
static_weight: torch.Tensor,
|
| 509 |
+
weight_proj_w: torch.Tensor,
|
| 510 |
+
num_heads: int,
|
| 511 |
+
) -> torch.Tensor:
|
| 512 |
+
"""Fast Triton 4-tap dynamic+static short conv update + residual / 3 for `[1, 1, C]` decode."""
|
| 513 |
+
C = x.shape[-1]
|
| 514 |
+
dyn_w = dense_gemv_triton(dynamic_input.view(-1), weight_proj_w, out_dtype=torch.float32)
|
| 515 |
+
out = torch.empty_like(x)
|
| 516 |
+
BLOCK_C = 256
|
| 517 |
+
_dyn_short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)](
|
| 518 |
+
x.contiguous(),
|
| 519 |
+
conv_state,
|
| 520 |
+
static_weight.contiguous(),
|
| 521 |
+
dyn_w,
|
| 522 |
+
out,
|
| 523 |
+
C,
|
| 524 |
+
HEAD_DIM=C // num_heads,
|
| 525 |
+
INV_SCALE=1.0 / 3.0,
|
| 526 |
+
BLOCK_C=BLOCK_C,
|
| 527 |
+
num_warps=4,
|
| 528 |
+
)
|
| 529 |
+
return out
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def message_gate_triton(
|
| 533 |
+
h: torch.Tensor,
|
| 534 |
+
m: torch.Tensor,
|
| 535 |
+
w_dn: torch.Tensor,
|
| 536 |
+
w_fg: torch.Tensor,
|
| 537 |
+
w_mg: torch.Tensor,
|
| 538 |
+
eps: float,
|
| 539 |
+
) -> torch.Tensor:
|
| 540 |
+
"""Exact 2-kernel fused Triton Inkling2LoopMessageGate for `B*T == 1` (returns fp32 `[1, 1, H]`)."""
|
| 541 |
+
R, two_H = w_dn.shape
|
| 542 |
+
H = two_H // 2
|
| 543 |
+
g = torch.empty((R,), device=h.device, dtype=torch.float32)
|
| 544 |
+
BLOCK_R = 2
|
| 545 |
+
_msg_gate_stage1_kernel[(triton.cdiv(R, BLOCK_R),)](
|
| 546 |
+
h.contiguous(),
|
| 547 |
+
m.contiguous(),
|
| 548 |
+
w_dn.contiguous(),
|
| 549 |
+
g,
|
| 550 |
+
R,
|
| 551 |
+
H,
|
| 552 |
+
eps,
|
| 553 |
+
BLOCK_R=BLOCK_R,
|
| 554 |
+
BLOCK_K=512,
|
| 555 |
+
num_warps=2,
|
| 556 |
+
)
|
| 557 |
+
out = torch.empty(h.shape, device=h.device, dtype=torch.float32)
|
| 558 |
+
BLOCK_H = 32
|
| 559 |
+
_msg_gate_stage2_kernel[(triton.cdiv(H, BLOCK_H),)](
|
| 560 |
+
h.contiguous(),
|
| 561 |
+
m.contiguous(),
|
| 562 |
+
g,
|
| 563 |
+
w_fg.contiguous(),
|
| 564 |
+
w_mg.contiguous(),
|
| 565 |
+
out,
|
| 566 |
+
H,
|
| 567 |
+
R=R,
|
| 568 |
+
BLOCK_H=BLOCK_H,
|
| 569 |
+
num_warps=4,
|
| 570 |
+
)
|
| 571 |
+
return out
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def router_topk_triton(
|
| 575 |
+
logits: torch.Tensor,
|
| 576 |
+
bias: torch.Tensor,
|
| 577 |
+
top_k: int,
|
| 578 |
+
scale: float,
|
| 579 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 580 |
+
"""Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale for `B*T == 1`."""
|
| 581 |
+
E = int(bias.shape[-1])
|
| 582 |
+
w_out = torch.empty((1, top_k), device=logits.device, dtype=torch.float32)
|
| 583 |
+
i_out = torch.empty((1, top_k), device=logits.device, dtype=torch.long)
|
| 584 |
+
_router_topk_kernel[(1,)](
|
| 585 |
+
logits.contiguous(),
|
| 586 |
+
bias.contiguous(),
|
| 587 |
+
w_out,
|
| 588 |
+
i_out,
|
| 589 |
+
float(scale),
|
| 590 |
+
E=E,
|
| 591 |
+
TOP_K=int(top_k),
|
| 592 |
+
num_warps=2,
|
| 593 |
+
)
|
| 594 |
+
return w_out, i_out
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def unweighted_rmsnorm_triton(x: torch.Tensor, eps: float) -> torch.Tensor:
|
| 598 |
+
"""Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than eager)."""
|
| 599 |
+
D = int(x.shape[-1])
|
| 600 |
+
x_c = x.contiguous()
|
| 601 |
+
out = torch.empty_like(x_c)
|
| 602 |
+
n_rows = x_c.numel() // D
|
| 603 |
+
_unweighted_rmsnorm_kernel[(n_rows,)](x_c, out, float(eps), D=D, num_warps=2)
|
| 604 |
+
return out
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def attn_res_step_triton(
|
| 608 |
+
block_states: torch.Tensor,
|
| 609 |
+
partial: torch.Tensor,
|
| 610 |
+
query: torch.Tensor,
|
| 611 |
+
) -> torch.Tensor:
|
| 612 |
+
"""Exact 2-kernel fused Triton Block/Message Attention Residual for `B=1, T=1` -> `[1, 1, Q, H]` fp32."""
|
| 613 |
+
S_prev = int(block_states.shape[-2])
|
| 614 |
+
H = int(partial.shape[-1])
|
| 615 |
+
q_2d = query.view(-1, H).contiguous()
|
| 616 |
+
Q = int(q_2d.shape[0])
|
| 617 |
+
Q_PAD = 1 << (Q - 1).bit_length()
|
| 618 |
+
S_tot = S_prev + 1
|
| 619 |
+
S_PAD = 1 << (S_tot - 1).bit_length()
|
| 620 |
+
if S_PAD < 2:
|
| 621 |
+
S_PAD = 2
|
| 622 |
+
|
| 623 |
+
inv_rms = torch.empty((S_tot,), device=partial.device, dtype=torch.float32)
|
| 624 |
+
scores = torch.empty((Q, S_tot), device=partial.device, dtype=torch.float32)
|
| 625 |
+
bs_c = block_states.contiguous()
|
| 626 |
+
p_c = partial.contiguous()
|
| 627 |
+
_attn_res_stage1_kernel[(S_tot,)](
|
| 628 |
+
bs_c,
|
| 629 |
+
p_c,
|
| 630 |
+
q_2d,
|
| 631 |
+
inv_rms,
|
| 632 |
+
scores,
|
| 633 |
+
S_prev,
|
| 634 |
+
H,
|
| 635 |
+
Q,
|
| 636 |
+
Q_PAD=Q_PAD,
|
| 637 |
+
BLOCK_K=512,
|
| 638 |
+
num_warps=4,
|
| 639 |
+
)
|
| 640 |
+
out = torch.empty((1, 1, Q, H), device=partial.device, dtype=torch.float32)
|
| 641 |
+
BLOCK_H = 64
|
| 642 |
+
_attn_res_stage2_kernel[(triton.cdiv(H, BLOCK_H),)](
|
| 643 |
+
bs_c,
|
| 644 |
+
p_c,
|
| 645 |
+
inv_rms,
|
| 646 |
+
scores,
|
| 647 |
+
out,
|
| 648 |
+
S_prev,
|
| 649 |
+
H,
|
| 650 |
+
Q,
|
| 651 |
+
Q_PAD=Q_PAD,
|
| 652 |
+
S_PAD=S_PAD,
|
| 653 |
+
BLOCK_H=BLOCK_H,
|
| 654 |
+
num_warps=2,
|
| 655 |
+
)
|
| 656 |
+
return out
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def inkling2_decode_attn_triton(
|
| 660 |
+
q: torch.Tensor, # [1, 24, 1, 128]
|
| 661 |
+
k_new: torch.Tensor, # [1, 8, 1, 128]
|
| 662 |
+
v_new: torch.Tensor, # [1, 8, 1, 128]
|
| 663 |
+
k_cache: torch.Tensor, # [1, 8, L, 128]
|
| 664 |
+
v_cache: torch.Tensor, # [1, 8, L, 128]
|
| 665 |
+
rel_states: torch.Tensor, # [1, 1, 24, 16]
|
| 666 |
+
rel_proj: torch.Tensor, # [16, 1024]
|
| 667 |
+
sinks: torch.Tensor, # [1, 24, 1, 1] or [24]
|
| 668 |
+
cur_pos: torch.Tensor, # [1] int64
|
| 669 |
+
scaling: float,
|
| 670 |
+
is_sliding: bool,
|
| 671 |
+
sliding_window: int = 1024,
|
| 672 |
+
rel_extent: int = 1024,
|
| 673 |
+
) -> torch.Tensor:
|
| 674 |
+
"""Writes single-token K/V into cache and runs exact fused GQA+RelBias+Sink attention -> `[1, 1, 24, 128]`."""
|
| 675 |
+
H_q = int(q.shape[1])
|
| 676 |
+
H_kv = int(k_cache.shape[1])
|
| 677 |
+
L = int(k_cache.shape[2])
|
| 678 |
+
D = int(q.shape[-1])
|
| 679 |
+
D_rel = int(rel_states.shape[-1])
|
| 680 |
+
|
| 681 |
+
_kv_cache_write_kernel[(H_kv,)](
|
| 682 |
+
k_new.contiguous(),
|
| 683 |
+
v_new.contiguous(),
|
| 684 |
+
k_cache,
|
| 685 |
+
v_cache,
|
| 686 |
+
cur_pos,
|
| 687 |
+
L,
|
| 688 |
+
IS_SLIDING=is_sliding,
|
| 689 |
+
SLIDING_MASK=sliding_window - 1,
|
| 690 |
+
D=D,
|
| 691 |
+
num_warps=2,
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
out = torch.empty((1, 1, H_q, D), device=q.device, dtype=q.dtype)
|
| 695 |
+
_inkling2_decode_attn_kernel[(H_q,)](
|
| 696 |
+
q.contiguous(),
|
| 697 |
+
k_cache,
|
| 698 |
+
v_cache,
|
| 699 |
+
rel_states.contiguous(),
|
| 700 |
+
rel_proj.contiguous(),
|
| 701 |
+
sinks.contiguous(),
|
| 702 |
+
cur_pos,
|
| 703 |
+
out,
|
| 704 |
+
L,
|
| 705 |
+
scaling,
|
| 706 |
+
GQA_GROUPS=H_q // H_kv,
|
| 707 |
+
IS_SLIDING=is_sliding,
|
| 708 |
+
SLIDING_WIN=sliding_window,
|
| 709 |
+
REL_EXTENT=rel_extent,
|
| 710 |
+
D=D,
|
| 711 |
+
D_REL=D_rel,
|
| 712 |
+
BLOCK_N=64,
|
| 713 |
+
num_warps=4,
|
| 714 |
+
)
|
| 715 |
+
return out
|
prime_infer_runtime.py
ADDED
|
@@ -0,0 +1,1265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2026 Philip Bartsch (@batteryphil).
|
| 2 |
+
# Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE).
|
| 3 |
+
"""
|
| 4 |
+
True In-VRAM Compressed PyTorch + Triton Runtime (`PrimeLiveModule`)
|
| 5 |
+
====================================================================
|
| 6 |
+
Keeps weights permanently compressed in GPU VRAM (`2.50 bpw` `Q2_G32` / `P2_G32` or `4.50 bpw` `P4_G32`)
|
| 7 |
+
and dequantizes on-the-fly per layer forward pass with zero persistent `FP16`/`BF16` weight copy!
|
| 8 |
+
Supports `linear`, `embedding`, `conv2d`, and `conv3d`, plus `<1.5s` `torch.device("meta")`
|
| 9 |
+
SafeTensors v2 serialization and loading.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from safetensors import safe_open
|
| 20 |
+
|
| 21 |
+
P2_LUT_LIST: List[float] = [-23.0, -7.0, 5.0, 17.0]
|
| 22 |
+
P4_LUT_LIST: List[float] = [
|
| 23 |
+
-127.0, -101.0, -80.0, -62.0, -46.0, -33.0, -21.0, -10.0,
|
| 24 |
+
0.0, 10.0, 21.0, 33.0, 46.0, 62.0, 80.0, 101.0,
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
_BYTE_LUT_CACHE: Dict[Tuple[torch.device, torch.dtype, str], torch.Tensor] = {}
|
| 28 |
+
_TRITON_LUT_CACHE: Dict[Tuple[torch.device, str], torch.Tensor] = {}
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
import triton as _triton
|
| 32 |
+
import triton.language as _tl
|
| 33 |
+
|
| 34 |
+
@_triton.jit
|
| 35 |
+
def _unpack_p4_g32_triton(
|
| 36 |
+
qp_ptr,
|
| 37 |
+
df_ptr,
|
| 38 |
+
lut_ptr,
|
| 39 |
+
out_ptr,
|
| 40 |
+
n_blocks,
|
| 41 |
+
BLOCK_B: _tl.constexpr,
|
| 42 |
+
):
|
| 43 |
+
pid = _tl.program_id(0)
|
| 44 |
+
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
|
| 45 |
+
b_mask = b < n_blocks
|
| 46 |
+
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
|
| 47 |
+
offs16 = _tl.arange(0, 16)
|
| 48 |
+
byte_idx = b[:, None] * 16 + offs16[None, :]
|
| 49 |
+
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
|
| 50 |
+
v_lo = _tl.load(lut_ptr + (packed & 0x0F)) * scale[:, None]
|
| 51 |
+
v_hi = _tl.load(lut_ptr + ((packed >> 4) & 0x0F)) * scale[:, None]
|
| 52 |
+
v_full = _tl.interleave(v_lo, v_hi).to(out_ptr.dtype.element_ty)
|
| 53 |
+
offs32 = _tl.arange(0, 32)
|
| 54 |
+
out_idx = b[:, None] * 32 + offs32[None, :]
|
| 55 |
+
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
|
| 56 |
+
|
| 57 |
+
@_triton.jit
|
| 58 |
+
def _unpack_q2_g32_triton(
|
| 59 |
+
qp_ptr,
|
| 60 |
+
df_ptr,
|
| 61 |
+
out_ptr,
|
| 62 |
+
n_blocks,
|
| 63 |
+
BLOCK_B: _tl.constexpr,
|
| 64 |
+
):
|
| 65 |
+
pid = _tl.program_id(0)
|
| 66 |
+
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
|
| 67 |
+
b_mask = b < n_blocks
|
| 68 |
+
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
|
| 69 |
+
offs8 = _tl.arange(0, 8)
|
| 70 |
+
byte_idx = b[:, None] * 8 + offs8[None, :]
|
| 71 |
+
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
|
| 72 |
+
c0 = ((packed & 0x03) - 2).to(_tl.float32) * scale[:, None]
|
| 73 |
+
c1 = (((packed >> 2) & 0x03) - 2).to(_tl.float32) * scale[:, None]
|
| 74 |
+
c2 = (((packed >> 4) & 0x03) - 2).to(_tl.float32) * scale[:, None]
|
| 75 |
+
c3 = (((packed >> 6) & 0x03) - 2).to(_tl.float32) * scale[:, None]
|
| 76 |
+
ce = _tl.interleave(c0, c2)
|
| 77 |
+
co = _tl.interleave(c1, c3)
|
| 78 |
+
v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty)
|
| 79 |
+
offs32 = _tl.arange(0, 32)
|
| 80 |
+
out_idx = b[:, None] * 32 + offs32[None, :]
|
| 81 |
+
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
|
| 82 |
+
|
| 83 |
+
@_triton.jit
|
| 84 |
+
def _unpack_p2_g32_triton(
|
| 85 |
+
qp_ptr,
|
| 86 |
+
df_ptr,
|
| 87 |
+
lut_ptr,
|
| 88 |
+
out_ptr,
|
| 89 |
+
n_blocks,
|
| 90 |
+
BLOCK_B: _tl.constexpr,
|
| 91 |
+
):
|
| 92 |
+
pid = _tl.program_id(0)
|
| 93 |
+
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
|
| 94 |
+
b_mask = b < n_blocks
|
| 95 |
+
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
|
| 96 |
+
offs8 = _tl.arange(0, 8)
|
| 97 |
+
byte_idx = b[:, None] * 8 + offs8[None, :]
|
| 98 |
+
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
|
| 99 |
+
c0 = _tl.load(lut_ptr + (packed & 0x03)) * scale[:, None]
|
| 100 |
+
c1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03)) * scale[:, None]
|
| 101 |
+
c2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03)) * scale[:, None]
|
| 102 |
+
c3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03)) * scale[:, None]
|
| 103 |
+
ce = _tl.interleave(c0, c2)
|
| 104 |
+
co = _tl.interleave(c1, c3)
|
| 105 |
+
v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty)
|
| 106 |
+
offs32 = _tl.arange(0, 32)
|
| 107 |
+
out_idx = b[:, None] * 32 + offs32[None, :]
|
| 108 |
+
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
|
| 109 |
+
|
| 110 |
+
@_triton.jit
|
| 111 |
+
def _dequant_p4_i8_triton(
|
| 112 |
+
q_ptr,
|
| 113 |
+
d_ptr,
|
| 114 |
+
lut_ptr,
|
| 115 |
+
out_ptr,
|
| 116 |
+
n_blocks,
|
| 117 |
+
BLOCK_B: _tl.constexpr,
|
| 118 |
+
):
|
| 119 |
+
pid = _tl.program_id(0)
|
| 120 |
+
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
|
| 121 |
+
b_mask = b < n_blocks
|
| 122 |
+
scale = _tl.load(d_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
|
| 123 |
+
offs32 = _tl.arange(0, 32)
|
| 124 |
+
idx = b[:, None] * 32 + offs32[None, :]
|
| 125 |
+
qi = _tl.load(q_ptr + idx, mask=b_mask[:, None], other=8).to(_tl.int32)
|
| 126 |
+
v_full = (_tl.load(lut_ptr + qi) * scale[:, None]).to(out_ptr.dtype.element_ty)
|
| 127 |
+
_tl.store(out_ptr + idx, v_full, mask=b_mask[:, None])
|
| 128 |
+
|
| 129 |
+
@_triton.jit
|
| 130 |
+
def _gemv_2bit_g32_triton(
|
| 131 |
+
x_ptr,
|
| 132 |
+
qp_ptr,
|
| 133 |
+
df_ptr,
|
| 134 |
+
lut_ptr,
|
| 135 |
+
bias_ptr,
|
| 136 |
+
e_ids_ptr,
|
| 137 |
+
out_ptr,
|
| 138 |
+
rows,
|
| 139 |
+
cols_real,
|
| 140 |
+
pack_cols,
|
| 141 |
+
n_groups,
|
| 142 |
+
num_experts,
|
| 143 |
+
stride_qe,
|
| 144 |
+
stride_de,
|
| 145 |
+
stride_xk,
|
| 146 |
+
IS_MOE: _tl.constexpr,
|
| 147 |
+
HAS_BIAS: _tl.constexpr,
|
| 148 |
+
BLOCK_R: _tl.constexpr,
|
| 149 |
+
GROUPS_K: _tl.constexpr,
|
| 150 |
+
):
|
| 151 |
+
pid_r = _tl.program_id(0)
|
| 152 |
+
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
|
| 153 |
+
r_mask = r < rows
|
| 154 |
+
r_i64 = r.to(_tl.int64)
|
| 155 |
+
|
| 156 |
+
if IS_MOE:
|
| 157 |
+
pid_k = _tl.program_id(1)
|
| 158 |
+
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
|
| 159 |
+
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
|
| 160 |
+
qp_base = e_idx * stride_qe
|
| 161 |
+
df_base = e_idx * stride_de
|
| 162 |
+
x_base = pid_k.to(_tl.int64) * stride_xk
|
| 163 |
+
out_base = pid_k.to(_tl.int64) * rows
|
| 164 |
+
else:
|
| 165 |
+
qp_base = _tl.cast(0, _tl.int64)
|
| 166 |
+
df_base = _tl.cast(0, _tl.int64)
|
| 167 |
+
x_base = _tl.cast(0, _tl.int64)
|
| 168 |
+
out_base = _tl.cast(0, _tl.int64)
|
| 169 |
+
|
| 170 |
+
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 171 |
+
g_offs = _tl.arange(0, GROUPS_K)
|
| 172 |
+
b_offs = _tl.arange(0, GROUPS_K * 8)
|
| 173 |
+
x_offs = _tl.arange(0, GROUPS_K * 32)
|
| 174 |
+
|
| 175 |
+
for g0 in range(0, n_groups, GROUPS_K):
|
| 176 |
+
g = g0 + g_offs
|
| 177 |
+
g_mask = g < n_groups
|
| 178 |
+
df_off = df_base + r_i64[:, None] * n_groups + g[None, :]
|
| 179 |
+
scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 180 |
+
|
| 181 |
+
xc = g0 * 32 + x_offs
|
| 182 |
+
xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
|
| 183 |
+
xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2))
|
| 184 |
+
x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2))
|
| 185 |
+
x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2))
|
| 186 |
+
|
| 187 |
+
k_byte = g0 * 8 + b_offs
|
| 188 |
+
kb_mask = k_byte < pack_cols
|
| 189 |
+
qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :]
|
| 190 |
+
packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32)
|
| 191 |
+
|
| 192 |
+
# L0-cached 16-byte 4-float LUT decode (matches P4 throughput, beats 32-op VALU arithmetic by 1.45x on RDNA4)
|
| 193 |
+
v0 = _tl.load(lut_ptr + (packed & 0x03))
|
| 194 |
+
v1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03))
|
| 195 |
+
v2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03))
|
| 196 |
+
v3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03))
|
| 197 |
+
|
| 198 |
+
dot = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape(
|
| 199 |
+
BLOCK_R, GROUPS_K, 8
|
| 200 |
+
)
|
| 201 |
+
acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1)
|
| 202 |
+
|
| 203 |
+
if HAS_BIAS:
|
| 204 |
+
acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32)
|
| 205 |
+
_tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask)
|
| 206 |
+
|
| 207 |
+
@_triton.jit
|
| 208 |
+
def _gemv_p4_g32_triton(
|
| 209 |
+
x_ptr,
|
| 210 |
+
qp_ptr,
|
| 211 |
+
df_ptr,
|
| 212 |
+
lut_ptr,
|
| 213 |
+
bias_ptr,
|
| 214 |
+
e_ids_ptr,
|
| 215 |
+
out_ptr,
|
| 216 |
+
rows,
|
| 217 |
+
cols_real,
|
| 218 |
+
pack_cols,
|
| 219 |
+
n_groups,
|
| 220 |
+
num_experts,
|
| 221 |
+
stride_qe,
|
| 222 |
+
stride_de,
|
| 223 |
+
stride_xk,
|
| 224 |
+
IS_MOE: _tl.constexpr,
|
| 225 |
+
HAS_BIAS: _tl.constexpr,
|
| 226 |
+
BLOCK_R: _tl.constexpr,
|
| 227 |
+
GROUPS_K: _tl.constexpr,
|
| 228 |
+
):
|
| 229 |
+
pid_r = _tl.program_id(0)
|
| 230 |
+
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
|
| 231 |
+
r_mask = r < rows
|
| 232 |
+
r_i64 = r.to(_tl.int64)
|
| 233 |
+
|
| 234 |
+
if IS_MOE:
|
| 235 |
+
pid_k = _tl.program_id(1)
|
| 236 |
+
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
|
| 237 |
+
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
|
| 238 |
+
qp_base = e_idx * stride_qe
|
| 239 |
+
df_base = e_idx * stride_de
|
| 240 |
+
x_base = pid_k.to(_tl.int64) * stride_xk
|
| 241 |
+
out_base = pid_k.to(_tl.int64) * rows
|
| 242 |
+
else:
|
| 243 |
+
qp_base = _tl.cast(0, _tl.int64)
|
| 244 |
+
df_base = _tl.cast(0, _tl.int64)
|
| 245 |
+
x_base = _tl.cast(0, _tl.int64)
|
| 246 |
+
out_base = _tl.cast(0, _tl.int64)
|
| 247 |
+
|
| 248 |
+
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 249 |
+
g_offs = _tl.arange(0, GROUPS_K)
|
| 250 |
+
b_offs = _tl.arange(0, GROUPS_K * 16)
|
| 251 |
+
x_offs = _tl.arange(0, GROUPS_K * 32)
|
| 252 |
+
|
| 253 |
+
for g0 in range(0, n_groups, GROUPS_K):
|
| 254 |
+
g = g0 + g_offs
|
| 255 |
+
g_mask = g < n_groups
|
| 256 |
+
df_off = df_base + r_i64[:, None] * n_groups + g[None, :]
|
| 257 |
+
scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 258 |
+
|
| 259 |
+
xc = g0 * 32 + x_offs
|
| 260 |
+
xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
|
| 261 |
+
x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2))
|
| 262 |
+
|
| 263 |
+
k_byte = g0 * 16 + b_offs
|
| 264 |
+
kb_mask = k_byte < pack_cols
|
| 265 |
+
qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :]
|
| 266 |
+
packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32)
|
| 267 |
+
|
| 268 |
+
v0 = _tl.load(lut_ptr + (packed & 0x0F))
|
| 269 |
+
v1 = _tl.load(lut_ptr + ((packed >> 4) & 0x0F))
|
| 270 |
+
|
| 271 |
+
dot = (v0 * x0[None, :] + v1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
|
| 272 |
+
acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1)
|
| 273 |
+
|
| 274 |
+
if HAS_BIAS:
|
| 275 |
+
acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32)
|
| 276 |
+
_tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask)
|
| 277 |
+
|
| 278 |
+
@_triton.jit
|
| 279 |
+
def _moe_gu_act_2bit_triton(
|
| 280 |
+
x_ptr,
|
| 281 |
+
qp_ptr,
|
| 282 |
+
df_ptr,
|
| 283 |
+
lut_ptr,
|
| 284 |
+
e_ids_ptr,
|
| 285 |
+
out_ptr,
|
| 286 |
+
I_dim,
|
| 287 |
+
cols_real,
|
| 288 |
+
pack_cols,
|
| 289 |
+
n_groups,
|
| 290 |
+
num_experts,
|
| 291 |
+
stride_qe,
|
| 292 |
+
stride_de,
|
| 293 |
+
G_CAP: _tl.constexpr,
|
| 294 |
+
U_CAP: _tl.constexpr,
|
| 295 |
+
BLOCK_R: _tl.constexpr,
|
| 296 |
+
GROUPS_K: _tl.constexpr,
|
| 297 |
+
):
|
| 298 |
+
"""Fused paired gate+up 2-bit MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue (L0 4-float LUT, 300+ GB/s on RDNA4)."""
|
| 299 |
+
pid_r = _tl.program_id(0)
|
| 300 |
+
pid_k = _tl.program_id(1)
|
| 301 |
+
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
|
| 302 |
+
r_mask = r < I_dim
|
| 303 |
+
rg = r.to(_tl.int64)
|
| 304 |
+
ru = (r + I_dim).to(_tl.int64)
|
| 305 |
+
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
|
| 306 |
+
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
|
| 307 |
+
qp_base = e_idx * stride_qe
|
| 308 |
+
df_base = e_idx * stride_de
|
| 309 |
+
|
| 310 |
+
acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 311 |
+
acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 312 |
+
g_offs = _tl.arange(0, GROUPS_K)
|
| 313 |
+
b_offs = _tl.arange(0, GROUPS_K * 8)
|
| 314 |
+
x_offs = _tl.arange(0, GROUPS_K * 32)
|
| 315 |
+
|
| 316 |
+
for g0 in range(0, n_groups, GROUPS_K):
|
| 317 |
+
g = g0 + g_offs
|
| 318 |
+
g_mask = g < n_groups
|
| 319 |
+
sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 320 |
+
su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 321 |
+
|
| 322 |
+
xc = g0 * 32 + x_offs
|
| 323 |
+
xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
|
| 324 |
+
xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2))
|
| 325 |
+
x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2))
|
| 326 |
+
x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2))
|
| 327 |
+
|
| 328 |
+
kb = g0 * 8 + b_offs
|
| 329 |
+
kbm = kb < pack_cols
|
| 330 |
+
pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
|
| 331 |
+
pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
|
| 332 |
+
|
| 333 |
+
v0 = _tl.load(lut_ptr + (pg & 3))
|
| 334 |
+
v1 = _tl.load(lut_ptr + ((pg >> 2) & 3))
|
| 335 |
+
v2 = _tl.load(lut_ptr + ((pg >> 4) & 3))
|
| 336 |
+
v3 = _tl.load(lut_ptr + ((pg >> 6) & 3))
|
| 337 |
+
u0 = _tl.load(lut_ptr + (pu & 3))
|
| 338 |
+
u1 = _tl.load(lut_ptr + ((pu >> 2) & 3))
|
| 339 |
+
u2 = _tl.load(lut_ptr + ((pu >> 4) & 3))
|
| 340 |
+
u3 = _tl.load(lut_ptr + ((pu >> 6) & 3))
|
| 341 |
+
|
| 342 |
+
dg = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8)
|
| 343 |
+
du = (u0 * x0[None, :] + u1 * x1[None, :] + u2 * x2[None, :] + u3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8)
|
| 344 |
+
acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1)
|
| 345 |
+
acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1)
|
| 346 |
+
|
| 347 |
+
tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g
|
| 348 |
+
tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u
|
| 349 |
+
res = tg * _tl.sigmoid(acc_g) * tu
|
| 350 |
+
_tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask)
|
| 351 |
+
|
| 352 |
+
@_triton.jit
|
| 353 |
+
def _moe_gu_act_p4_triton(
|
| 354 |
+
x_ptr,
|
| 355 |
+
qp_ptr,
|
| 356 |
+
df_ptr,
|
| 357 |
+
lut_ptr,
|
| 358 |
+
e_ids_ptr,
|
| 359 |
+
out_ptr,
|
| 360 |
+
I_dim,
|
| 361 |
+
cols_real,
|
| 362 |
+
pack_cols,
|
| 363 |
+
n_groups,
|
| 364 |
+
num_experts,
|
| 365 |
+
stride_qe,
|
| 366 |
+
stride_de,
|
| 367 |
+
G_CAP: _tl.constexpr,
|
| 368 |
+
U_CAP: _tl.constexpr,
|
| 369 |
+
BLOCK_R: _tl.constexpr,
|
| 370 |
+
GROUPS_K: _tl.constexpr,
|
| 371 |
+
):
|
| 372 |
+
"""Fused paired gate+up P4_G32 MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue."""
|
| 373 |
+
pid_r = _tl.program_id(0)
|
| 374 |
+
pid_k = _tl.program_id(1)
|
| 375 |
+
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
|
| 376 |
+
r_mask = r < I_dim
|
| 377 |
+
rg = r.to(_tl.int64)
|
| 378 |
+
ru = (r + I_dim).to(_tl.int64)
|
| 379 |
+
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
|
| 380 |
+
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
|
| 381 |
+
qp_base = e_idx * stride_qe
|
| 382 |
+
df_base = e_idx * stride_de
|
| 383 |
+
|
| 384 |
+
acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 385 |
+
acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 386 |
+
g_offs = _tl.arange(0, GROUPS_K)
|
| 387 |
+
b_offs = _tl.arange(0, GROUPS_K * 16)
|
| 388 |
+
x_offs = _tl.arange(0, GROUPS_K * 32)
|
| 389 |
+
|
| 390 |
+
for g0 in range(0, n_groups, GROUPS_K):
|
| 391 |
+
g = g0 + g_offs
|
| 392 |
+
g_mask = g < n_groups
|
| 393 |
+
sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 394 |
+
su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
|
| 395 |
+
|
| 396 |
+
xc = g0 * 32 + x_offs
|
| 397 |
+
xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
|
| 398 |
+
x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2))
|
| 399 |
+
|
| 400 |
+
kb = g0 * 16 + b_offs
|
| 401 |
+
kbm = kb < pack_cols
|
| 402 |
+
pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
|
| 403 |
+
pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
|
| 404 |
+
|
| 405 |
+
vg0 = _tl.load(lut_ptr + (pg & 0x0F)); vg1 = _tl.load(lut_ptr + ((pg >> 4) & 0x0F))
|
| 406 |
+
vu0 = _tl.load(lut_ptr + (pu & 0x0F)); vu1 = _tl.load(lut_ptr + ((pu >> 4) & 0x0F))
|
| 407 |
+
dg = (vg0 * x0[None, :] + vg1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
|
| 408 |
+
du = (vu0 * x0[None, :] + vu1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
|
| 409 |
+
acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1)
|
| 410 |
+
acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1)
|
| 411 |
+
|
| 412 |
+
tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g
|
| 413 |
+
tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u
|
| 414 |
+
res = tg * _tl.sigmoid(acc_g) * tu
|
| 415 |
+
_tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask)
|
| 416 |
+
|
| 417 |
+
@_triton.jit
|
| 418 |
+
def _moe_weighted_reduce_f32_triton(
|
| 419 |
+
x_f32_ptr,
|
| 420 |
+
e_ids_ptr,
|
| 421 |
+
w_tok_ptr,
|
| 422 |
+
out_ptr,
|
| 423 |
+
rows,
|
| 424 |
+
num_experts,
|
| 425 |
+
K_EXP: _tl.constexpr,
|
| 426 |
+
BLOCK_R: _tl.constexpr,
|
| 427 |
+
):
|
| 428 |
+
"""Fused FP32 masked weighted reduction across K active experts `[K, rows] -> [1, rows]` (~1.5 us in L2)."""
|
| 429 |
+
pid = _tl.program_id(0)
|
| 430 |
+
r = pid * BLOCK_R + _tl.arange(0, BLOCK_R)
|
| 431 |
+
rm = r < rows
|
| 432 |
+
r_i64 = r.to(_tl.int64)
|
| 433 |
+
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
|
| 434 |
+
for k in range(0, K_EXP):
|
| 435 |
+
e_raw = _tl.load(e_ids_ptr + k).to(_tl.int64)
|
| 436 |
+
is_valid = (e_raw >= 0) & (e_raw < num_experts)
|
| 437 |
+
wk = _tl.where(is_valid, _tl.load(w_tok_ptr + k).to(_tl.float32), 0.0)
|
| 438 |
+
xv = _tl.load(x_f32_ptr + _tl.cast(k, _tl.int64) * rows + r_i64, mask=rm, other=0.0)
|
| 439 |
+
acc += wk * xv
|
| 440 |
+
_tl.store(out_ptr + r_i64, acc.to(out_ptr.dtype.element_ty), mask=rm)
|
| 441 |
+
|
| 442 |
+
_HAS_TRITON_UNPACK = True
|
| 443 |
+
except Exception:
|
| 444 |
+
_HAS_TRITON_UNPACK = False
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _get_triton_lut(device: torch.device, fmt: str = "p4_0") -> torch.Tensor:
|
| 448 |
+
key = (device, fmt)
|
| 449 |
+
lut = _TRITON_LUT_CACHE.get(key)
|
| 450 |
+
if lut is None:
|
| 451 |
+
if fmt == "p4_0":
|
| 452 |
+
vals = P4_LUT_LIST
|
| 453 |
+
elif fmt == "p2_0":
|
| 454 |
+
vals = P2_LUT_LIST
|
| 455 |
+
else:
|
| 456 |
+
vals = [-2.0, -1.0, 0.0, 1.0]
|
| 457 |
+
lut = torch.tensor(vals, device=device, dtype=torch.float32).contiguous()
|
| 458 |
+
_TRITON_LUT_CACHE[key] = lut
|
| 459 |
+
return lut
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _gemv_prime_g32_fast(
|
| 463 |
+
x_1d: torch.Tensor,
|
| 464 |
+
qp: torch.Tensor,
|
| 465 |
+
df: torch.Tensor,
|
| 466 |
+
bias: Optional[torch.Tensor],
|
| 467 |
+
fmt: str,
|
| 468 |
+
rows: int,
|
| 469 |
+
cols_real: int,
|
| 470 |
+
pcols: int,
|
| 471 |
+
) -> torch.Tensor:
|
| 472 |
+
"""Fused-register Triton GEMV (`y = W @ x + b`) — 64B cacheline-aligned, zero BF16 materialization."""
|
| 473 |
+
out = torch.empty((rows,), device=qp.device, dtype=x_1d.dtype)
|
| 474 |
+
x_c = x_1d.contiguous()
|
| 475 |
+
n_groups = pcols // 32
|
| 476 |
+
pack_cols = qp.shape[1]
|
| 477 |
+
has_bias = bias is not None
|
| 478 |
+
b_ptr = bias.contiguous() if has_bias else out
|
| 479 |
+
lut = _get_triton_lut(qp.device, fmt)
|
| 480 |
+
if fmt == "p4_0":
|
| 481 |
+
BLOCK_R = 8 if rows >= 256 else 4
|
| 482 |
+
grid = (_triton.cdiv(rows, BLOCK_R),)
|
| 483 |
+
_gemv_p4_g32_triton[grid](
|
| 484 |
+
x_c, qp, df, lut, b_ptr, out, out,
|
| 485 |
+
rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0,
|
| 486 |
+
IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=2,
|
| 487 |
+
)
|
| 488 |
+
else:
|
| 489 |
+
BLOCK_R = 8 if rows >= 256 else 4
|
| 490 |
+
grid = (_triton.cdiv(rows, BLOCK_R),)
|
| 491 |
+
_gemv_2bit_g32_triton[grid](
|
| 492 |
+
x_c, qp, df, lut, b_ptr, out, out,
|
| 493 |
+
rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0,
|
| 494 |
+
IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
|
| 495 |
+
)
|
| 496 |
+
return out
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _gemv_moe_g32_fast(
|
| 500 |
+
x: torch.Tensor,
|
| 501 |
+
qp_3d: torch.Tensor,
|
| 502 |
+
df_3d: torch.Tensor,
|
| 503 |
+
e_ids: torch.Tensor,
|
| 504 |
+
fmt: str,
|
| 505 |
+
rows: int,
|
| 506 |
+
cols_real: int,
|
| 507 |
+
pcols: int,
|
| 508 |
+
shared_x: bool,
|
| 509 |
+
) -> torch.Tensor:
|
| 510 |
+
"""Fused-register batched active-expert Triton GEMV (`[K, rows]`) — zero index_select, zero BF16 alloc."""
|
| 511 |
+
K = int(e_ids.shape[0])
|
| 512 |
+
num_experts = int(qp_3d.shape[0])
|
| 513 |
+
out = torch.empty((K, rows), device=qp_3d.device, dtype=x.dtype)
|
| 514 |
+
x_c = x.contiguous()
|
| 515 |
+
e_c = e_ids.contiguous()
|
| 516 |
+
n_groups = pcols // 32
|
| 517 |
+
pack_cols = int(qp_3d.shape[2])
|
| 518 |
+
stride_qe = int(qp_3d.stride(0))
|
| 519 |
+
stride_de = int(df_3d.stride(0))
|
| 520 |
+
stride_xk = 0 if shared_x else int(x_c.stride(0))
|
| 521 |
+
lut = _get_triton_lut(qp_3d.device, fmt)
|
| 522 |
+
if fmt == "p4_0":
|
| 523 |
+
BLOCK_R = 4
|
| 524 |
+
grid = (_triton.cdiv(rows, BLOCK_R), K)
|
| 525 |
+
_gemv_p4_g32_triton[grid](
|
| 526 |
+
x_c, qp_3d, df_3d, lut, out, e_c, out,
|
| 527 |
+
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
|
| 528 |
+
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
|
| 529 |
+
)
|
| 530 |
+
else:
|
| 531 |
+
BLOCK_R = 8 if rows >= 256 else 4
|
| 532 |
+
grid = (_triton.cdiv(rows, BLOCK_R), K)
|
| 533 |
+
_gemv_2bit_g32_triton[grid](
|
| 534 |
+
x_c, qp_3d, df_3d, lut, out, e_c, out,
|
| 535 |
+
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
|
| 536 |
+
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
|
| 537 |
+
)
|
| 538 |
+
return out
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _gemv_moe_gu_act_fast(
|
| 542 |
+
x_1d: torch.Tensor,
|
| 543 |
+
qp_3d: torch.Tensor,
|
| 544 |
+
df_3d: torch.Tensor,
|
| 545 |
+
e_ids: torch.Tensor,
|
| 546 |
+
fmt: str,
|
| 547 |
+
inter_dim: int,
|
| 548 |
+
cols_real: int,
|
| 549 |
+
pcols: int,
|
| 550 |
+
num_experts: int,
|
| 551 |
+
g_cap: float,
|
| 552 |
+
u_cap: float,
|
| 553 |
+
) -> torch.Tensor:
|
| 554 |
+
"""Fused paired gate+up Triton MoE GEMV + SwiGLU/SoftcappedSwiGLU -> `[K, inter_dim]` (300+ GB/s on RDNA4)."""
|
| 555 |
+
K = int(e_ids.shape[0])
|
| 556 |
+
out = torch.empty((K, inter_dim), device=qp_3d.device, dtype=x_1d.dtype)
|
| 557 |
+
x_c = x_1d.contiguous()
|
| 558 |
+
e_c = e_ids.contiguous()
|
| 559 |
+
n_groups = pcols // 32
|
| 560 |
+
pack_cols = int(qp_3d.shape[2])
|
| 561 |
+
stride_qe = int(qp_3d.stride(0))
|
| 562 |
+
stride_de = int(df_3d.stride(0))
|
| 563 |
+
lut = _get_triton_lut(qp_3d.device, fmt)
|
| 564 |
+
if fmt == "p4_0":
|
| 565 |
+
BLOCK_R = 4
|
| 566 |
+
grid = (_triton.cdiv(inter_dim, BLOCK_R), K)
|
| 567 |
+
_moe_gu_act_p4_triton[grid](
|
| 568 |
+
x_c, qp_3d, df_3d, lut, e_c, out,
|
| 569 |
+
inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de,
|
| 570 |
+
G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
|
| 571 |
+
)
|
| 572 |
+
else:
|
| 573 |
+
BLOCK_R = 8 if inter_dim >= 64 else 4
|
| 574 |
+
grid = (_triton.cdiv(inter_dim, BLOCK_R), K)
|
| 575 |
+
_moe_gu_act_2bit_triton[grid](
|
| 576 |
+
x_c, qp_3d, df_3d, lut, e_c, out,
|
| 577 |
+
inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de,
|
| 578 |
+
G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
|
| 579 |
+
)
|
| 580 |
+
return out
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _gemv_moe_dn_reduce_fast(
|
| 584 |
+
x_kh: torch.Tensor,
|
| 585 |
+
qp_3d: torch.Tensor,
|
| 586 |
+
df_3d: torch.Tensor,
|
| 587 |
+
e_ids: torch.Tensor,
|
| 588 |
+
w_tok: torch.Tensor,
|
| 589 |
+
fmt: str,
|
| 590 |
+
rows: int,
|
| 591 |
+
cols_real: int,
|
| 592 |
+
pcols: int,
|
| 593 |
+
num_experts: int,
|
| 594 |
+
) -> torch.Tensor:
|
| 595 |
+
"""Parallel-K down_proj Triton GEMV (FP32 L2 intermediate) + fused masked weighted reduce -> `[1, rows]`."""
|
| 596 |
+
K = int(e_ids.shape[0])
|
| 597 |
+
out_kh_f32 = torch.empty((K, rows), device=qp_3d.device, dtype=torch.float32)
|
| 598 |
+
out = torch.empty((1, rows), device=qp_3d.device, dtype=x_kh.dtype)
|
| 599 |
+
x_c = x_kh.contiguous()
|
| 600 |
+
e_c = e_ids.contiguous()
|
| 601 |
+
w_c = w_tok.contiguous()
|
| 602 |
+
n_groups = pcols // 32
|
| 603 |
+
pack_cols = int(qp_3d.shape[2])
|
| 604 |
+
stride_qe = int(qp_3d.stride(0))
|
| 605 |
+
stride_de = int(df_3d.stride(0))
|
| 606 |
+
stride_xk = int(x_c.stride(0))
|
| 607 |
+
lut = _get_triton_lut(qp_3d.device, fmt)
|
| 608 |
+
BLOCK_R = 4
|
| 609 |
+
grid = (_triton.cdiv(rows, BLOCK_R), K)
|
| 610 |
+
if fmt == "p4_0":
|
| 611 |
+
_gemv_p4_g32_triton[grid](
|
| 612 |
+
x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32,
|
| 613 |
+
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
|
| 614 |
+
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
_gemv_2bit_g32_triton[grid](
|
| 618 |
+
x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32,
|
| 619 |
+
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
|
| 620 |
+
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
|
| 621 |
+
)
|
| 622 |
+
_moe_weighted_reduce_f32_triton[(_triton.cdiv(rows, 256),)](
|
| 623 |
+
out_kh_f32, e_c, w_c, out, rows, num_experts, K_EXP=K, BLOCK_R=256, num_warps=4,
|
| 624 |
+
)
|
| 625 |
+
return out
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def _unpack_packed_2d_fast(
|
| 629 |
+
qp: torch.Tensor,
|
| 630 |
+
df: torch.Tensor,
|
| 631 |
+
fmt: str,
|
| 632 |
+
rows: int,
|
| 633 |
+
pcols: int,
|
| 634 |
+
group_size: int,
|
| 635 |
+
target_dtype: torch.dtype,
|
| 636 |
+
) -> torch.Tensor:
|
| 637 |
+
"""Fast Triton (G=32 on CUDA for p4_0/p2_0/q2_0) or byte-LUT fallback unpacker -> [rows, pcols]."""
|
| 638 |
+
if (
|
| 639 |
+
_HAS_TRITON_UNPACK
|
| 640 |
+
and qp.is_cuda
|
| 641 |
+
and group_size == 32
|
| 642 |
+
and fmt in ("p4_0", "p2_0", "q2_0")
|
| 643 |
+
and target_dtype in (torch.bfloat16, torch.float16, torch.float32)
|
| 644 |
+
and (pcols & 31) == 0
|
| 645 |
+
):
|
| 646 |
+
qp_c = qp.contiguous()
|
| 647 |
+
df_c = df.contiguous()
|
| 648 |
+
w2 = torch.empty((rows, pcols), device=qp.device, dtype=target_dtype)
|
| 649 |
+
nb = rows * (pcols // 32)
|
| 650 |
+
grid = (_triton.cdiv(nb, 32),)
|
| 651 |
+
if fmt == "p4_0":
|
| 652 |
+
_unpack_p4_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p4_0"), w2, nb, BLOCK_B=32)
|
| 653 |
+
elif fmt == "p2_0":
|
| 654 |
+
_unpack_p2_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p2_0"), w2, nb, BLOCK_B=32)
|
| 655 |
+
else:
|
| 656 |
+
_unpack_q2_g32_triton[grid](qp_c, df_c, w2, nb, BLOCK_B=32)
|
| 657 |
+
return w2
|
| 658 |
+
|
| 659 |
+
lut = _get_byte_lut(qp.device, torch.float32, fmt)
|
| 660 |
+
cv = F.embedding(qp.to(torch.int32), lut).view(rows, pcols // group_size, group_size)
|
| 661 |
+
return (cv * df.float().unsqueeze(-1)).to(target_dtype).view(rows, pcols)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def _get_byte_lut(device: torch.device, dtype: torch.dtype, fmt: str) -> torch.Tensor:
|
| 665 |
+
key = (device, dtype, fmt)
|
| 666 |
+
lut = _BYTE_LUT_CACHE.get(key)
|
| 667 |
+
if lut is None:
|
| 668 |
+
idx = torch.arange(256, dtype=torch.int32)
|
| 669 |
+
if fmt == "q2_0":
|
| 670 |
+
c0 = (idx & 0x03) - 2
|
| 671 |
+
c1 = ((idx >> 2) & 0x03) - 2
|
| 672 |
+
c2 = ((idx >> 4) & 0x03) - 2
|
| 673 |
+
c3 = ((idx >> 6) & 0x03) - 2
|
| 674 |
+
lut = torch.stack([c0, c1, c2, c3], dim=-1).to(device=device, dtype=dtype).contiguous()
|
| 675 |
+
elif fmt == "p2_0":
|
| 676 |
+
p2_t = torch.tensor(P2_LUT_LIST, dtype=torch.float32)
|
| 677 |
+
lut = torch.stack(
|
| 678 |
+
[p2_t[idx & 0x03], p2_t[(idx >> 2) & 0x03], p2_t[(idx >> 4) & 0x03], p2_t[(idx >> 6) & 0x03]], dim=-1
|
| 679 |
+
).to(device=device, dtype=dtype).contiguous()
|
| 680 |
+
else:
|
| 681 |
+
p4_t = torch.tensor(P4_LUT_LIST, dtype=torch.float32)
|
| 682 |
+
lut = torch.stack([p4_t[idx & 0x0F], p4_t[(idx >> 4) & 0x0F]], dim=-1).to(device=device, dtype=dtype).contiguous()
|
| 683 |
+
_BYTE_LUT_CACHE[key] = lut
|
| 684 |
+
return lut
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def weight_to_2d_tap_separated(mod: nn.Module, G: int = 32) -> Tuple[torch.Tensor, int, int, Tuple[int, ...], bool]:
|
| 688 |
+
"""
|
| 689 |
+
Maps `Linear`, `Embedding`, `Conv2d`, or `Conv3d` weights to `[rows, pcols]` (`pcols % G == 0`),
|
| 690 |
+
isolating spatial/temporal `Conv2d`/`Conv3d` kernel taps `(kT, kH, kW)` into separate rows so
|
| 691 |
+
that every `G`-element quantization block lies strictly along `C_in` without cross-tap bleeding.
|
| 692 |
+
"""
|
| 693 |
+
w = mod.weight.detach().float()
|
| 694 |
+
orig_shape = tuple(w.shape)
|
| 695 |
+
if isinstance(mod, (nn.Linear, nn.Embedding)):
|
| 696 |
+
rows, cols = w.shape
|
| 697 |
+
tap_perm = False
|
| 698 |
+
w2 = w
|
| 699 |
+
elif isinstance(mod, (nn.Conv2d, nn.Conv3d)):
|
| 700 |
+
spatial_prod = 1
|
| 701 |
+
for d in orig_shape[2:]:
|
| 702 |
+
spatial_prod *= d
|
| 703 |
+
if spatial_prod > 1 and orig_shape[1] >= G and (orig_shape[1] % G == 0):
|
| 704 |
+
perm = [0] + list(range(2, len(orig_shape))) + [1]
|
| 705 |
+
w_p = w.permute(*perm).contiguous()
|
| 706 |
+
cols = orig_shape[1]
|
| 707 |
+
rows = w.numel() // cols
|
| 708 |
+
w2 = w_p.view(rows, cols)
|
| 709 |
+
tap_perm = True
|
| 710 |
+
else:
|
| 711 |
+
rows = orig_shape[0]
|
| 712 |
+
cols = w.numel() // rows
|
| 713 |
+
w2 = w.reshape(rows, cols)
|
| 714 |
+
tap_perm = False
|
| 715 |
+
else:
|
| 716 |
+
raise TypeError(f"Unsupported module type: {type(mod)}")
|
| 717 |
+
|
| 718 |
+
pad_c = (G - (cols % G)) % G
|
| 719 |
+
if pad_c > 0:
|
| 720 |
+
w2 = F.pad(w2, (0, pad_c), value=0.0)
|
| 721 |
+
return w2, rows, cols, orig_shape, tap_perm
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def reconstruct_from_2d(w2: torch.Tensor, orig_shape: Tuple[int, ...], tap_perm: bool, dtype: torch.dtype) -> torch.Tensor:
|
| 725 |
+
if not tap_perm:
|
| 726 |
+
return w2.reshape(orig_shape).to(dtype)
|
| 727 |
+
c_out = orig_shape[0]
|
| 728 |
+
c_in = orig_shape[1]
|
| 729 |
+
sp = orig_shape[2:]
|
| 730 |
+
w_p = w2.view(c_out, *sp, c_in)
|
| 731 |
+
inv_perm = [0, len(orig_shape) - 1] + list(range(1, len(orig_shape) - 1))
|
| 732 |
+
return w_p.permute(*inv_perm).contiguous().to(dtype)
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
class PrimeLiveModule(nn.Module):
|
| 736 |
+
"""
|
| 737 |
+
In-VRAM compressed module (`p4_0`, `p2_0`, or `q2_0`, `G=32`) supporting `linear`, `embedding`,
|
| 738 |
+
`conv2d`, and `conv3d` with on-the-fly Triton unpacking and `_keep_in_fp32_modules` protection.
|
| 739 |
+
"""
|
| 740 |
+
|
| 741 |
+
def __init__(
|
| 742 |
+
self,
|
| 743 |
+
op_kind: str,
|
| 744 |
+
fmt: str,
|
| 745 |
+
orig_shape: Tuple[int, ...],
|
| 746 |
+
cols: int,
|
| 747 |
+
tap_perm: bool,
|
| 748 |
+
q_pack: torch.Tensor,
|
| 749 |
+
d_f16: torch.Tensor,
|
| 750 |
+
bias: Optional[torch.Tensor] = None,
|
| 751 |
+
compute_dtype: torch.dtype = torch.bfloat16,
|
| 752 |
+
conv_kwargs: Optional[Dict[str, Any]] = None,
|
| 753 |
+
):
|
| 754 |
+
super().__init__()
|
| 755 |
+
assert fmt in ("p4_0", "p2_0", "q2_0")
|
| 756 |
+
self.op_kind = op_kind
|
| 757 |
+
self.fmt = fmt
|
| 758 |
+
self.orig_shape = orig_shape
|
| 759 |
+
self.rows = q_pack.shape[0]
|
| 760 |
+
self.cols = cols
|
| 761 |
+
self.pcols = q_pack.shape[1] * (4 if fmt in ("q2_0", "p2_0") else 2)
|
| 762 |
+
assert d_f16.ndim == 2 and d_f16.shape[0] == self.rows and (self.pcols % d_f16.shape[1] == 0)
|
| 763 |
+
self.group_size = self.pcols // d_f16.shape[1]
|
| 764 |
+
self.tap_perm = tap_perm
|
| 765 |
+
self.compute_dtype = compute_dtype
|
| 766 |
+
self.conv_kwargs = conv_kwargs or {}
|
| 767 |
+
|
| 768 |
+
if op_kind == "linear":
|
| 769 |
+
self.in_features = orig_shape[1]
|
| 770 |
+
self.out_features = orig_shape[0]
|
| 771 |
+
elif op_kind == "embedding":
|
| 772 |
+
self.num_embeddings = orig_shape[0]
|
| 773 |
+
self.embedding_dim = orig_shape[1]
|
| 774 |
+
else:
|
| 775 |
+
self.out_channels = orig_shape[0]
|
| 776 |
+
self.in_channels = orig_shape[1] * self.conv_kwargs.get("groups", 1)
|
| 777 |
+
self.kernel_size = orig_shape[2:]
|
| 778 |
+
self.stride = self.conv_kwargs.get("stride", 1)
|
| 779 |
+
self.padding = self.conv_kwargs.get("padding", 0)
|
| 780 |
+
self.dilation = self.conv_kwargs.get("dilation", 1)
|
| 781 |
+
self.groups = self.conv_kwargs.get("groups", 1)
|
| 782 |
+
|
| 783 |
+
self.register_buffer("q_pack", q_pack.to(torch.uint8).contiguous())
|
| 784 |
+
self.register_buffer("d_f16", d_f16.to(torch.float16).contiguous())
|
| 785 |
+
self._dtype_anchor = nn.Parameter(torch.empty(0, dtype=compute_dtype), requires_grad=False)
|
| 786 |
+
if bias is not None:
|
| 787 |
+
self.register_buffer("bias", bias.to(compute_dtype).contiguous())
|
| 788 |
+
else:
|
| 789 |
+
self.bias = None
|
| 790 |
+
|
| 791 |
+
def _apply(self, fn, recurse=True):
|
| 792 |
+
# Preserve exact FP16 scale mantissa and FP32-protected bias across dtype casts
|
| 793 |
+
# (e.g., `model.to(torch.bfloat16)`), while still honoring device transfers.
|
| 794 |
+
orig_d = self.d_f16
|
| 795 |
+
orig_bias = self.bias
|
| 796 |
+
super()._apply(fn, recurse=recurse)
|
| 797 |
+
target_dev = self.q_pack.device
|
| 798 |
+
if not orig_d.is_meta and not self.d_f16.is_meta:
|
| 799 |
+
if self.d_f16.dtype != torch.float16:
|
| 800 |
+
self.d_f16 = orig_d if orig_d.device == target_dev else orig_d.to(device=target_dev, dtype=torch.float16)
|
| 801 |
+
elif self.d_f16.dtype != torch.float16:
|
| 802 |
+
self.d_f16 = self.d_f16.to(torch.float16)
|
| 803 |
+
if self.compute_dtype == torch.float32:
|
| 804 |
+
if self._dtype_anchor.dtype != torch.float32:
|
| 805 |
+
self._dtype_anchor = nn.Parameter(
|
| 806 |
+
torch.empty(0, device=target_dev, dtype=torch.float32), requires_grad=False
|
| 807 |
+
)
|
| 808 |
+
if orig_bias is not None and not orig_bias.is_meta and not self.bias.is_meta:
|
| 809 |
+
if self.bias.dtype != torch.float32:
|
| 810 |
+
self.bias = orig_bias if orig_bias.device == target_dev else orig_bias.to(device=target_dev, dtype=torch.float32)
|
| 811 |
+
elif self.bias is not None and self.bias.dtype != torch.float32:
|
| 812 |
+
self.bias = self.bias.to(torch.float32)
|
| 813 |
+
return self
|
| 814 |
+
|
| 815 |
+
@property
|
| 816 |
+
def weight(self) -> torch.Tensor:
|
| 817 |
+
return self._dtype_anchor
|
| 818 |
+
|
| 819 |
+
def unpack_weight(self, target_dtype: torch.dtype) -> torch.Tensor:
|
| 820 |
+
w2 = _unpack_packed_2d_fast(self.q_pack, self.d_f16, self.fmt, self.rows, self.pcols, self.group_size, target_dtype)
|
| 821 |
+
if self.pcols > self.cols:
|
| 822 |
+
w2 = w2[:, : self.cols]
|
| 823 |
+
return reconstruct_from_2d(w2, self.orig_shape, self.tap_perm, target_dtype)
|
| 824 |
+
|
| 825 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 826 |
+
if self.op_kind == "embedding":
|
| 827 |
+
flat = x.reshape(-1)
|
| 828 |
+
n_sel = int(flat.numel())
|
| 829 |
+
qp_s = self.q_pack.index_select(0, flat)
|
| 830 |
+
df_s = self.d_f16.index_select(0, flat)
|
| 831 |
+
w2 = _unpack_packed_2d_fast(qp_s, df_s, self.fmt, n_sel, self.pcols, self.group_size, self.compute_dtype)
|
| 832 |
+
if self.pcols > self.cols:
|
| 833 |
+
w2 = w2[:, : self.cols]
|
| 834 |
+
out = w2.view(*x.shape, self.cols)
|
| 835 |
+
embed_norm = getattr(self, "embed_norm", None)
|
| 836 |
+
if embed_norm is not None:
|
| 837 |
+
out = embed_norm(out)
|
| 838 |
+
return out
|
| 839 |
+
|
| 840 |
+
dt = x.dtype
|
| 841 |
+
if (
|
| 842 |
+
self.op_kind == "linear"
|
| 843 |
+
and _HAS_TRITON_UNPACK
|
| 844 |
+
and self.q_pack.is_cuda
|
| 845 |
+
and self.group_size == 32
|
| 846 |
+
and not self.tap_perm
|
| 847 |
+
and self.fmt in ("p4_0", "p2_0", "q2_0")
|
| 848 |
+
and dt in (torch.bfloat16, torch.float16, torch.float32)
|
| 849 |
+
and x.numel() == self.cols
|
| 850 |
+
):
|
| 851 |
+
y = _gemv_prime_g32_fast(
|
| 852 |
+
x.reshape(-1), self.q_pack, self.d_f16, self.bias, self.fmt, self.rows, self.cols, self.pcols
|
| 853 |
+
)
|
| 854 |
+
return y.view(*x.shape[:-1], self.rows)
|
| 855 |
+
|
| 856 |
+
w = self.unpack_weight(dt)
|
| 857 |
+
b = (self.bias if self.bias.dtype == dt else self.bias.to(dt)) if self.bias is not None else None
|
| 858 |
+
if self.op_kind == "linear":
|
| 859 |
+
return F.linear(x, w, b)
|
| 860 |
+
if self.op_kind == "conv2d":
|
| 861 |
+
return F.conv2d(x, w, b, self.stride, self.padding, self.dilation, self.groups)
|
| 862 |
+
return F.conv3d(x, w, b, self.stride, self.padding, self.dilation, self.groups)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
class PrimeLiveMoEExperts(nn.Module):
|
| 866 |
+
"""
|
| 867 |
+
In-VRAM compressed 3D Mixture-of-Experts bank (`gate_up_proj` + `down_proj` across `E` experts)
|
| 868 |
+
in `p2_0`, `q2_0`, or `p4_0`. At decode (`T == 1`), runs fused-register batched Triton GEMV
|
| 869 |
+
directly over the `top_k` active experts with zero weight materialization; at prefill (`T > 1`),
|
| 870 |
+
unpacks one hit expert at a time to keep peak VRAM tiny.
|
| 871 |
+
"""
|
| 872 |
+
|
| 873 |
+
def __init__(
|
| 874 |
+
self,
|
| 875 |
+
fmt: str,
|
| 876 |
+
num_experts: int,
|
| 877 |
+
hidden_dim: int,
|
| 878 |
+
intermediate_dim: int,
|
| 879 |
+
gu_q: torch.Tensor,
|
| 880 |
+
gu_d: torch.Tensor,
|
| 881 |
+
dn_q: torch.Tensor,
|
| 882 |
+
dn_d: torch.Tensor,
|
| 883 |
+
act_fn: nn.Module,
|
| 884 |
+
compute_dtype: torch.dtype = torch.bfloat16,
|
| 885 |
+
dn_fmt: Optional[str] = None,
|
| 886 |
+
):
|
| 887 |
+
super().__init__()
|
| 888 |
+
import inspect
|
| 889 |
+
|
| 890 |
+
dn_fmt_eff = fmt if dn_fmt is None else dn_fmt
|
| 891 |
+
assert fmt in ("p4_0", "p2_0", "q2_0") and dn_fmt_eff in ("p4_0", "p2_0", "q2_0")
|
| 892 |
+
self.fmt = fmt
|
| 893 |
+
self.dn_fmt = dn_fmt_eff
|
| 894 |
+
self.num_experts = int(num_experts)
|
| 895 |
+
self.hidden_dim = int(hidden_dim)
|
| 896 |
+
self.intermediate_dim = int(intermediate_dim)
|
| 897 |
+
self.compute_dtype = compute_dtype
|
| 898 |
+
self.act_fn = act_fn
|
| 899 |
+
try:
|
| 900 |
+
sig = inspect.signature(act_fn.forward)
|
| 901 |
+
self._act_two_arg = len(sig.parameters) >= 2
|
| 902 |
+
except Exception:
|
| 903 |
+
self._act_two_arg = False
|
| 904 |
+
|
| 905 |
+
if hasattr(act_fn, "gate_softcap") and hasattr(act_fn, "up_softcap"):
|
| 906 |
+
g_sc = getattr(act_fn.gate_softcap, "softcap", None)
|
| 907 |
+
u_sc = getattr(act_fn.up_softcap, "softcap", None)
|
| 908 |
+
self._fused_act: Optional[Tuple[float, float]] = (
|
| 909 |
+
float(g_sc) if g_sc is not None else 0.0,
|
| 910 |
+
float(u_sc) if u_sc is not None else 0.0,
|
| 911 |
+
)
|
| 912 |
+
elif isinstance(act_fn, nn.SiLU):
|
| 913 |
+
self._fused_act = (0.0, 0.0)
|
| 914 |
+
else:
|
| 915 |
+
self._fused_act = None
|
| 916 |
+
|
| 917 |
+
gu_pack_mul = 4 if fmt in ("q2_0", "p2_0") else 2
|
| 918 |
+
dn_pack_mul = 4 if dn_fmt_eff in ("q2_0", "p2_0") else 2
|
| 919 |
+
self.gu_rows = int(gu_q.shape[1])
|
| 920 |
+
self.gu_pcols = int(gu_q.shape[2]) * gu_pack_mul
|
| 921 |
+
self.dn_rows = int(dn_q.shape[1])
|
| 922 |
+
self.dn_pcols = int(dn_q.shape[2]) * dn_pack_mul
|
| 923 |
+
self.group_size = self.gu_pcols // int(gu_d.shape[2])
|
| 924 |
+
assert self.dn_pcols // int(dn_d.shape[2]) == self.group_size
|
| 925 |
+
|
| 926 |
+
self.register_buffer("gu_q", gu_q.to(torch.uint8).contiguous())
|
| 927 |
+
self.register_buffer("gu_d", gu_d.to(torch.float16).contiguous())
|
| 928 |
+
self.register_buffer("dn_q", dn_q.to(torch.uint8).contiguous())
|
| 929 |
+
self.register_buffer("dn_d", dn_d.to(torch.float16).contiguous())
|
| 930 |
+
|
| 931 |
+
def _apply(self, fn, recurse=True):
|
| 932 |
+
orig_gu_d = self.gu_d
|
| 933 |
+
orig_dn_d = self.dn_d
|
| 934 |
+
super()._apply(fn, recurse=recurse)
|
| 935 |
+
target_dev = self.gu_q.device
|
| 936 |
+
for attr, orig in (("gu_d", orig_gu_d), ("dn_d", orig_dn_d)):
|
| 937 |
+
cur = getattr(self, attr)
|
| 938 |
+
if not orig.is_meta and not cur.is_meta:
|
| 939 |
+
if cur.dtype != torch.float16:
|
| 940 |
+
setattr(self, attr, orig if orig.device == target_dev else orig.to(device=target_dev, dtype=torch.float16))
|
| 941 |
+
elif cur.dtype != torch.float16:
|
| 942 |
+
setattr(self, attr, cur.to(torch.float16))
|
| 943 |
+
return self
|
| 944 |
+
|
| 945 |
+
def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
|
| 946 |
+
gate, up = gate_up.chunk(2, dim=-1)
|
| 947 |
+
if self._act_two_arg:
|
| 948 |
+
return self.act_fn(gate, up)
|
| 949 |
+
return self.act_fn(gate) * up
|
| 950 |
+
|
| 951 |
+
def forward(
|
| 952 |
+
self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
|
| 953 |
+
) -> torch.Tensor:
|
| 954 |
+
T, H = hidden_states.shape
|
| 955 |
+
dt = hidden_states.dtype
|
| 956 |
+
|
| 957 |
+
if T == 1:
|
| 958 |
+
e_raw = top_k_index[0]
|
| 959 |
+
if (
|
| 960 |
+
_HAS_TRITON_UNPACK
|
| 961 |
+
and self.gu_q.is_cuda
|
| 962 |
+
and self.group_size == 32
|
| 963 |
+
and self.fmt in ("p4_0", "p2_0", "q2_0")
|
| 964 |
+
and self.dn_fmt in ("p4_0", "p2_0", "q2_0")
|
| 965 |
+
and dt in (torch.bfloat16, torch.float16, torch.float32)
|
| 966 |
+
):
|
| 967 |
+
if self._fused_act is not None and self.gu_rows == 2 * self.intermediate_dim:
|
| 968 |
+
h_mid = _gemv_moe_gu_act_fast(
|
| 969 |
+
hidden_states[0], self.gu_q, self.gu_d, e_raw, self.fmt,
|
| 970 |
+
self.intermediate_dim, H, self.gu_pcols, self.num_experts,
|
| 971 |
+
self._fused_act[0], self._fused_act[1],
|
| 972 |
+
)
|
| 973 |
+
else:
|
| 974 |
+
e_ids = e_raw.clamp(0, self.num_experts - 1)
|
| 975 |
+
gu_out = _gemv_moe_g32_fast(
|
| 976 |
+
hidden_states[0], self.gu_q, self.gu_d, e_ids, self.fmt,
|
| 977 |
+
self.gu_rows, H, self.gu_pcols, shared_x=True,
|
| 978 |
+
)
|
| 979 |
+
h_mid = self._apply_gate(gu_out)
|
| 980 |
+
return _gemv_moe_dn_reduce_fast(
|
| 981 |
+
h_mid, self.dn_q, self.dn_d, e_raw, top_k_weights[0], self.dn_fmt,
|
| 982 |
+
self.dn_rows, self.intermediate_dim, self.dn_pcols, self.num_experts,
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
valid = ((e_raw >= 0) & (e_raw < self.num_experts)).to(torch.float32)
|
| 986 |
+
e_ids = e_raw.clamp(0, self.num_experts - 1)
|
| 987 |
+
w_tok = (top_k_weights[0].float() * valid).unsqueeze(-1)
|
| 988 |
+
K = int(e_ids.shape[0])
|
| 989 |
+
gu_q_k = self.gu_q.index_select(0, e_ids).reshape(K * self.gu_rows, -1)
|
| 990 |
+
gu_d_k = self.gu_d.index_select(0, e_ids).reshape(K * self.gu_rows, -1)
|
| 991 |
+
w_gu = _unpack_packed_2d_fast(gu_q_k, gu_d_k, self.fmt, K * self.gu_rows, self.gu_pcols, self.group_size, dt)
|
| 992 |
+
if self.gu_pcols > H:
|
| 993 |
+
w_gu = w_gu[:, :H]
|
| 994 |
+
w_gu = w_gu.view(K, self.gu_rows, H)
|
| 995 |
+
gu_out = torch.bmm(hidden_states.expand(K, H).unsqueeze(1), w_gu.transpose(1, 2)).squeeze(1)
|
| 996 |
+
del w_gu
|
| 997 |
+
h_mid = self._apply_gate(gu_out)
|
| 998 |
+
|
| 999 |
+
dn_q_k = self.dn_q.index_select(0, e_ids).reshape(K * self.dn_rows, -1)
|
| 1000 |
+
dn_d_k = self.dn_d.index_select(0, e_ids).reshape(K * self.dn_rows, -1)
|
| 1001 |
+
w_dn = _unpack_packed_2d_fast(dn_q_k, dn_d_k, self.dn_fmt, K * self.dn_rows, self.dn_pcols, self.group_size, dt)
|
| 1002 |
+
if self.dn_pcols > self.intermediate_dim:
|
| 1003 |
+
w_dn = w_dn[:, : self.intermediate_dim]
|
| 1004 |
+
w_dn = w_dn.view(K, self.dn_rows, self.intermediate_dim)
|
| 1005 |
+
dn_out = torch.bmm(h_mid.unsqueeze(1), w_dn.transpose(1, 2)).squeeze(1).float()
|
| 1006 |
+
del w_dn
|
| 1007 |
+
return (dn_out * w_tok).sum(dim=0, keepdim=True).to(dt)
|
| 1008 |
+
|
| 1009 |
+
final_hidden_states = torch.zeros_like(hidden_states, dtype=torch.float32)
|
| 1010 |
+
with torch.no_grad():
|
| 1011 |
+
expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0)
|
| 1012 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 1013 |
+
|
| 1014 |
+
for expert_idx_t in expert_hit:
|
| 1015 |
+
expert_idx = int(expert_idx_t[0].item())
|
| 1016 |
+
if expert_idx >= self.num_experts:
|
| 1017 |
+
continue
|
| 1018 |
+
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
|
| 1019 |
+
current_state = hidden_states[token_idx]
|
| 1020 |
+
w_gu = _unpack_packed_2d_fast(
|
| 1021 |
+
self.gu_q[expert_idx], self.gu_d[expert_idx], self.fmt, self.gu_rows, self.gu_pcols, self.group_size, dt
|
| 1022 |
+
)
|
| 1023 |
+
if self.gu_pcols > H:
|
| 1024 |
+
w_gu = w_gu[:, :H]
|
| 1025 |
+
h_mid = self._apply_gate(F.linear(current_state, w_gu))
|
| 1026 |
+
del w_gu
|
| 1027 |
+
w_dn = _unpack_packed_2d_fast(
|
| 1028 |
+
self.dn_q[expert_idx], self.dn_d[expert_idx], self.dn_fmt, self.dn_rows, self.dn_pcols, self.group_size, dt
|
| 1029 |
+
)
|
| 1030 |
+
if self.dn_pcols > self.intermediate_dim:
|
| 1031 |
+
w_dn = w_dn[:, : self.intermediate_dim]
|
| 1032 |
+
cur_out = F.linear(h_mid, w_dn)
|
| 1033 |
+
del w_dn
|
| 1034 |
+
cur_out = cur_out * top_k_weights[token_idx, top_k_pos, None]
|
| 1035 |
+
final_hidden_states.index_add_(0, token_idx, cur_out.to(torch.float32))
|
| 1036 |
+
|
| 1037 |
+
return final_hidden_states.to(dt)
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def get_submod(root: nn.Module, path: str) -> nn.Module:
|
| 1041 |
+
cur = root
|
| 1042 |
+
for p in path.split("."):
|
| 1043 |
+
cur = cur[int(p)] if p.isdigit() else getattr(cur, p)
|
| 1044 |
+
return cur
|
| 1045 |
+
|
| 1046 |
+
|
| 1047 |
+
def set_submod(root: nn.Module, path: str, new_mod: nn.Module) -> None:
|
| 1048 |
+
parts = path.split(".")
|
| 1049 |
+
parent = root
|
| 1050 |
+
for p in parts[:-1]:
|
| 1051 |
+
parent = parent[int(p)] if p.isdigit() else getattr(parent, p)
|
| 1052 |
+
last = parts[-1]
|
| 1053 |
+
if last.isdigit():
|
| 1054 |
+
parent[int(last)] = new_mod
|
| 1055 |
+
else:
|
| 1056 |
+
setattr(parent, last, new_mod)
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
def _parse_tuple_or_int(s: str):
|
| 1060 |
+
s = s.strip()
|
| 1061 |
+
if s.startswith("(") and s.endswith(")"):
|
| 1062 |
+
return tuple(int(x.strip()) for x in s[1:-1].split(",") if x.strip())
|
| 1063 |
+
return int(s)
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
def _get_fp32_patterns(model: nn.Module) -> Tuple[str, ...]:
|
| 1067 |
+
pats: List[str] = []
|
| 1068 |
+
for attr in ("_keep_in_fp32_modules", "_keep_in_fp32_modules_strict"):
|
| 1069 |
+
val = getattr(model, attr, None)
|
| 1070 |
+
if val:
|
| 1071 |
+
pats.extend(str(v) for v in val)
|
| 1072 |
+
return tuple(dict.fromkeys(pats))
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def _is_fp32_protected(full_name: str, fp32_patterns: Tuple[str, ...]) -> bool:
|
| 1076 |
+
if not fp32_patterns:
|
| 1077 |
+
return False
|
| 1078 |
+
segs = set(full_name.split("."))
|
| 1079 |
+
for pat in fp32_patterns:
|
| 1080 |
+
if "." in pat:
|
| 1081 |
+
if (
|
| 1082 |
+
full_name == pat
|
| 1083 |
+
or full_name.endswith("." + pat)
|
| 1084 |
+
or (f".{pat}." in full_name)
|
| 1085 |
+
or full_name.startswith(f"{pat}.")
|
| 1086 |
+
):
|
| 1087 |
+
return True
|
| 1088 |
+
elif pat in segs:
|
| 1089 |
+
return True
|
| 1090 |
+
return False
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
@torch.no_grad()
|
| 1094 |
+
def load_prime_safetensors(
|
| 1095 |
+
skeleton_model: nn.Module,
|
| 1096 |
+
safetensors_path: str,
|
| 1097 |
+
device: str = "cuda",
|
| 1098 |
+
compute_dtype: torch.dtype = torch.bfloat16,
|
| 1099 |
+
) -> Dict[str, Any]:
|
| 1100 |
+
"""
|
| 1101 |
+
Hydrates a `torch.device("meta")` or CPU `skeleton_model` with in-VRAM `PrimeLiveModule` and
|
| 1102 |
+
`PrimeLiveMoEExperts` modules in `<1.5s`, honoring `_keep_in_fp32_modules[_strict]`, persistent
|
| 1103 |
+
buffers (e.g. MoE router bias), normed embeddings, and tied `shared <-> encoder.embed_tokens`.
|
| 1104 |
+
"""
|
| 1105 |
+
fp32_pats = _get_fp32_patterns(skeleton_model)
|
| 1106 |
+
n_2bit, n_4bit = 0, 0
|
| 1107 |
+
with safe_open(safetensors_path, framework="pt", device="cpu") as f:
|
| 1108 |
+
meta = f.metadata() or {}
|
| 1109 |
+
keys = set(f.keys())
|
| 1110 |
+
|
| 1111 |
+
for mk, mval in sorted(meta.items()):
|
| 1112 |
+
if not mk.startswith("mod:"):
|
| 1113 |
+
continue
|
| 1114 |
+
mname = mk[4:]
|
| 1115 |
+
op_kind, fmt, tap_s, cols_s, shape_s, conv_s = mval.split(";", 5)
|
| 1116 |
+
tap_perm = bool(int(tap_s))
|
| 1117 |
+
cols = int(cols_s)
|
| 1118 |
+
orig_shape = tuple(int(x) for x in shape_s.split(","))
|
| 1119 |
+
conv_kw = {}
|
| 1120 |
+
if conv_s:
|
| 1121 |
+
st_s, pa_s, di_s, gr_s = conv_s.split("|")
|
| 1122 |
+
conv_kw = {
|
| 1123 |
+
"stride": _parse_tuple_or_int(st_s),
|
| 1124 |
+
"padding": _parse_tuple_or_int(pa_s),
|
| 1125 |
+
"dilation": _parse_tuple_or_int(di_s),
|
| 1126 |
+
"groups": int(gr_s),
|
| 1127 |
+
}
|
| 1128 |
+
qp = f.get_tensor(f"{mname}.__q").to(device)
|
| 1129 |
+
df = f.get_tensor(f"{mname}.__d").to(device)
|
| 1130 |
+
bt = f.get_tensor(f"{mname}.__b").to(device) if f"{mname}.__b" in keys else None
|
| 1131 |
+
is_fp32_mod = _is_fp32_protected(mname, fp32_pats)
|
| 1132 |
+
eff_dt = torch.float32 if is_fp32_mod else compute_dtype
|
| 1133 |
+
|
| 1134 |
+
old_mod = get_submod(skeleton_model, mname)
|
| 1135 |
+
live_mod = PrimeLiveModule(
|
| 1136 |
+
op_kind=op_kind,
|
| 1137 |
+
fmt=fmt,
|
| 1138 |
+
orig_shape=orig_shape,
|
| 1139 |
+
cols=cols,
|
| 1140 |
+
tap_perm=tap_perm,
|
| 1141 |
+
q_pack=qp,
|
| 1142 |
+
d_f16=df,
|
| 1143 |
+
bias=bt,
|
| 1144 |
+
compute_dtype=eff_dt,
|
| 1145 |
+
conv_kwargs=conv_kw,
|
| 1146 |
+
).to(device)
|
| 1147 |
+
if op_kind == "embedding" and hasattr(old_mod, "embed_norm") and old_mod.embed_norm is not None:
|
| 1148 |
+
live_mod.embed_norm = old_mod.embed_norm
|
| 1149 |
+
set_submod(skeleton_model, mname, live_mod)
|
| 1150 |
+
if fmt in ("q2_0", "p2_0"):
|
| 1151 |
+
n_2bit += 1
|
| 1152 |
+
else:
|
| 1153 |
+
n_4bit += 1
|
| 1154 |
+
|
| 1155 |
+
for mk, mval in sorted(meta.items()):
|
| 1156 |
+
if not mk.startswith("moe:"):
|
| 1157 |
+
continue
|
| 1158 |
+
mname = mk[4:]
|
| 1159 |
+
fmt_spec, ne_s, hd_s, id_s = mval.split(";", 3)
|
| 1160 |
+
if "/" in fmt_spec:
|
| 1161 |
+
fmt, dn_fmt = fmt_spec.split("/", 1)
|
| 1162 |
+
else:
|
| 1163 |
+
fmt, dn_fmt = fmt_spec, fmt_spec
|
| 1164 |
+
old_mod = get_submod(skeleton_model, mname)
|
| 1165 |
+
act_fn = getattr(old_mod, "act_fn", nn.SiLU())
|
| 1166 |
+
live_moe = PrimeLiveMoEExperts(
|
| 1167 |
+
fmt=fmt,
|
| 1168 |
+
num_experts=int(ne_s),
|
| 1169 |
+
hidden_dim=int(hd_s),
|
| 1170 |
+
intermediate_dim=int(id_s),
|
| 1171 |
+
gu_q=f.get_tensor(f"{mname}.__gu_q").to(device),
|
| 1172 |
+
gu_d=f.get_tensor(f"{mname}.__gu_d").to(device),
|
| 1173 |
+
dn_q=f.get_tensor(f"{mname}.__dn_q").to(device),
|
| 1174 |
+
dn_d=f.get_tensor(f"{mname}.__dn_d").to(device),
|
| 1175 |
+
act_fn=act_fn,
|
| 1176 |
+
compute_dtype=compute_dtype,
|
| 1177 |
+
dn_fmt=dn_fmt,
|
| 1178 |
+
).to(device)
|
| 1179 |
+
set_submod(skeleton_model, mname, live_moe)
|
| 1180 |
+
if fmt in ("q2_0", "p2_0") or dn_fmt in ("q2_0", "p2_0"):
|
| 1181 |
+
n_2bit += 1
|
| 1182 |
+
else:
|
| 1183 |
+
n_4bit += 1
|
| 1184 |
+
|
| 1185 |
+
q_suffixes = (".__q", ".__d", ".__b", ".__gu_q", ".__gu_d", ".__dn_q", ".__dn_d")
|
| 1186 |
+
for k in keys:
|
| 1187 |
+
if k.endswith(q_suffixes):
|
| 1188 |
+
continue
|
| 1189 |
+
parts = k.split(".")
|
| 1190 |
+
parent = get_submod(skeleton_model, ".".join(parts[:-1])) if len(parts) > 1 else skeleton_model
|
| 1191 |
+
leaf = parts[-1]
|
| 1192 |
+
if hasattr(parent, "_parameters") and leaf in parent._parameters and parent._parameters[leaf] is not None:
|
| 1193 |
+
p_tgt = parent._parameters[leaf]
|
| 1194 |
+
t_src = f.get_tensor(k)
|
| 1195 |
+
is_fp32_prot = _is_fp32_protected(k, fp32_pats)
|
| 1196 |
+
tgt_dt = (
|
| 1197 |
+
(torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype)
|
| 1198 |
+
if is_fp32_prot
|
| 1199 |
+
else (compute_dtype if p_tgt.is_floating_point() else p_tgt.dtype)
|
| 1200 |
+
)
|
| 1201 |
+
parent._parameters[leaf] = nn.Parameter(t_src.to(device=device, dtype=tgt_dt), requires_grad=False)
|
| 1202 |
+
elif hasattr(parent, "_buffers") and leaf in parent._buffers:
|
| 1203 |
+
b_tgt = parent._buffers[leaf]
|
| 1204 |
+
t_src = f.get_tensor(k)
|
| 1205 |
+
is_fp32_prot = _is_fp32_protected(k, fp32_pats)
|
| 1206 |
+
if is_fp32_prot:
|
| 1207 |
+
tgt_dt = torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype
|
| 1208 |
+
elif b_tgt is not None:
|
| 1209 |
+
tgt_dt = t_src.dtype if (t_src.dtype == torch.float32 and b_tgt.dtype == torch.float32) else (compute_dtype if b_tgt.is_floating_point() else b_tgt.dtype)
|
| 1210 |
+
else:
|
| 1211 |
+
tgt_dt = t_src.dtype
|
| 1212 |
+
parent._buffers[leaf] = t_src.to(device=device, dtype=tgt_dt)
|
| 1213 |
+
|
| 1214 |
+
if hasattr(skeleton_model, "tie_weights"):
|
| 1215 |
+
try:
|
| 1216 |
+
skeleton_model.tie_weights()
|
| 1217 |
+
except Exception:
|
| 1218 |
+
pass
|
| 1219 |
+
if (
|
| 1220 |
+
hasattr(skeleton_model, "shared")
|
| 1221 |
+
and hasattr(skeleton_model, "encoder")
|
| 1222 |
+
and hasattr(skeleton_model.encoder, "embed_tokens")
|
| 1223 |
+
and isinstance(skeleton_model.shared, PrimeLiveModule)
|
| 1224 |
+
):
|
| 1225 |
+
skeleton_model.encoder.embed_tokens = skeleton_model.shared
|
| 1226 |
+
|
| 1227 |
+
vault_mods = {m for m in skeleton_model.modules() if isinstance(m, (PrimeLiveModule, PrimeLiveMoEExperts))}
|
| 1228 |
+
moved_ptrs: Dict[Tuple[int, bool], nn.Parameter] = {}
|
| 1229 |
+
for sub_path, sub in skeleton_model.named_modules():
|
| 1230 |
+
if sub in vault_mods:
|
| 1231 |
+
continue
|
| 1232 |
+
for pname, p in sub._parameters.items():
|
| 1233 |
+
if p is not None and not p.is_meta:
|
| 1234 |
+
full_n = f"{sub_path}.{pname}" if sub_path else pname
|
| 1235 |
+
is_fp32_prot = _is_fp32_protected(full_n, fp32_pats)
|
| 1236 |
+
pkey = (p.data_ptr(), is_fp32_prot)
|
| 1237 |
+
if pkey not in moved_ptrs:
|
| 1238 |
+
tgt_dt = (
|
| 1239 |
+
(torch.float32 if p.dtype in (torch.float16, torch.bfloat16) else p.dtype)
|
| 1240 |
+
if is_fp32_prot
|
| 1241 |
+
else (compute_dtype if p.is_floating_point() else p.dtype)
|
| 1242 |
+
)
|
| 1243 |
+
moved_ptrs[pkey] = nn.Parameter(p.data.to(device=device, dtype=tgt_dt), requires_grad=p.requires_grad)
|
| 1244 |
+
sub._parameters[pname] = moved_ptrs[pkey]
|
| 1245 |
+
for bname, b in sub._buffers.items():
|
| 1246 |
+
if b is not None and not b.is_meta:
|
| 1247 |
+
full_bn = f"{sub_path}.{bname}" if sub_path else bname
|
| 1248 |
+
is_fp32_prot = _is_fp32_protected(full_bn, fp32_pats)
|
| 1249 |
+
tgt_bdt = (
|
| 1250 |
+
(torch.float32 if b.dtype in (torch.float16, torch.bfloat16) else b.dtype)
|
| 1251 |
+
if is_fp32_prot
|
| 1252 |
+
else (compute_dtype if b.is_floating_point() else b.dtype)
|
| 1253 |
+
)
|
| 1254 |
+
sub._buffers[bname] = b.to(device=device, dtype=tgt_bdt)
|
| 1255 |
+
|
| 1256 |
+
skeleton_model.eval()
|
| 1257 |
+
vram_bytes = sum(b.numel() * b.element_size() for b in skeleton_model.buffers()) + sum(
|
| 1258 |
+
p.numel() * p.element_size() for p in skeleton_model.parameters()
|
| 1259 |
+
)
|
| 1260 |
+
return {
|
| 1261 |
+
"modules_2bit": n_2bit,
|
| 1262 |
+
"modules_4bit": n_4bit,
|
| 1263 |
+
"resident_vram_mb": round(vram_bytes / 1e6, 2),
|
| 1264 |
+
"file_mb": round(os.path.getsize(safetensors_path) / 1e6, 2),
|
| 1265 |
+
}
|
processor_config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"image_processor": {
|
| 3 |
+
"do_convert_rgb": true,
|
| 4 |
+
"do_normalize": true,
|
| 5 |
+
"do_rescale": true,
|
| 6 |
+
"image_mean": [
|
| 7 |
+
0.5,
|
| 8 |
+
0.5,
|
| 9 |
+
0.5
|
| 10 |
+
],
|
| 11 |
+
"image_processor_type": "Inkling2ImageProcessor",
|
| 12 |
+
"image_std": [
|
| 13 |
+
0.5,
|
| 14 |
+
0.5,
|
| 15 |
+
0.5
|
| 16 |
+
],
|
| 17 |
+
"rescale_factor": 0.00392156862745098,
|
| 18 |
+
"size": {
|
| 19 |
+
"height": 40,
|
| 20 |
+
"width": 40
|
| 21 |
+
}
|
| 22 |
+
},
|
| 23 |
+
"image_token": "<|unused_200054|>",
|
| 24 |
+
"processor_class": "Inkling2Processor"
|
| 25 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.5.0
|
| 2 |
+
transformers>=5.24.0
|
| 3 |
+
triton>=3.0.0
|
| 4 |
+
safetensors>=0.4.5
|
run_inkling2_prime.py
ADDED
|
@@ -0,0 +1,859 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright (c) 2026 Philip Bartsch (@batteryphil).
|
| 3 |
+
# Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE).
|
| 4 |
+
"""
|
| 5 |
+
PRIME-Quant Ultra-Fast HIP/CUDA-Graph Inference & Chat Runner for `Inkling-2-Mini`
|
| 6 |
+
==================================================================================
|
| 7 |
+
Hydrates `PRIME-Quant` `Inkling-2-Mini` SafeTensors v2 checkpoints (`~8.8–9.5 GB`) from
|
| 8 |
+
`torch.device("meta")` in `~5.5s` directly into 16 GB GPU VRAM and combines:
|
| 9 |
+
|
| 10 |
+
1. 64B-cacheline fused-register Triton `P2_G32`/`P4_G32` GEMV + batched active-expert MoE kernels.
|
| 11 |
+
2. Exact fused Triton decode kernels (`pipelines/inkling2_kernels.py`) for ALL 48-pass Inkling-2 ops:
|
| 12 |
+
- Static & dynamic 4-tap short convolutions (`192` calls/tok)
|
| 13 |
+
- Rank-64 looped message gates (`96` calls/tok, bypassing slow M=1 rocBLAS)
|
| 14 |
+
- Block & Message Attention Residuals (`120` calls/tok, zero rocBLAS)
|
| 15 |
+
- TopKRouter & sink projections (`96` calls/tok)
|
| 16 |
+
- Ring-buffer GQA + RelativePositionBias + Per-Head Sink decode attention (`48` calls/tok)
|
| 17 |
+
3. Single-graph HIP/CUDA-Graph replay supporting `4K..32K+` context (zero `1024`-token cap,
|
| 18 |
+
zero per-token KV cache `roll(-1)` copies).
|
| 19 |
+
4. Official Thinking Machines / Unsloth settings (`temperature=1.0, top_p=1.0, top_k=0, min_p=0.0`),
|
| 20 |
+
`--reasoning-effort`, Inkling reasoning parser, and automatic thinking-loop guard (`--loop-guard`
|
| 21 |
+
+ `--max-thinking-tokens`) to prevent Inkling-2's documented CoT repetition loops.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import gc
|
| 28 |
+
import os
|
| 29 |
+
import re
|
| 30 |
+
import sys
|
| 31 |
+
import time
|
| 32 |
+
from typing import Dict, List, Optional, Tuple
|
| 33 |
+
|
| 34 |
+
import torch
|
| 35 |
+
import torch.nn.functional as F
|
| 36 |
+
from transformers import AutoConfig, AutoTokenizer, Inkling2LoopForConditionalGeneration, StaticCache
|
| 37 |
+
import transformers.models.inkling2_loop.modeling_inkling2_loop as mik
|
| 38 |
+
|
| 39 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 40 |
+
if HERE not in sys.path:
|
| 41 |
+
sys.path.insert(0, HERE)
|
| 42 |
+
|
| 43 |
+
from prime_infer_runtime import load_prime_safetensors
|
| 44 |
+
from inkling2_kernels import (
|
| 45 |
+
attn_res_step_triton,
|
| 46 |
+
dense_gemv_triton,
|
| 47 |
+
dyn_short_conv1d_step_res_triton,
|
| 48 |
+
inkling2_decode_attn_triton,
|
| 49 |
+
message_gate_triton,
|
| 50 |
+
router_topk_triton,
|
| 51 |
+
short_conv1d_step_res_triton,
|
| 52 |
+
unweighted_rmsnorm_triton,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Special token IDs from Inkling-2-Mini tokenizer_config.json
|
| 56 |
+
TOK_MESSAGE_MODEL = 200001
|
| 57 |
+
TOK_CONTENT_TEXT = 200004
|
| 58 |
+
TOK_END_SAMPLING = 200006
|
| 59 |
+
TOK_CONTENT_THINKING = 200008
|
| 60 |
+
TOK_END_MESSAGE = 200010
|
| 61 |
+
|
| 62 |
+
_GRAPH_POS: List[Optional[torch.Tensor]] = [None]
|
| 63 |
+
_PREFILL_KV_LEN: List[Optional[int]] = [None]
|
| 64 |
+
_PATCHED = False
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def parse_inkling_output(raw_text: str) -> Tuple[str, str]:
|
| 68 |
+
"""Splits raw Inkling-2 output into `(thinking, answer)` strings."""
|
| 69 |
+
thinks = re.findall(r"<\|content_thinking\|>(.*?)(?:<\|end_message\|>|$)", raw_text, flags=re.DOTALL)
|
| 70 |
+
answers = re.findall(r"<\|content_text\|>(.*?)(?:<\|end_message\|>|<\|content_model_end_sampling\|>|$)", raw_text, flags=re.DOTALL)
|
| 71 |
+
thinking = "\n".join(t.strip() for t in thinks if t.strip())
|
| 72 |
+
answer = "\n".join(a.strip() for a in answers if a.strip())
|
| 73 |
+
if not thinking and not answer:
|
| 74 |
+
cleaned = re.sub(r"<\|[^|]+\|>", "", raw_text).strip()
|
| 75 |
+
return "", cleaned
|
| 76 |
+
return thinking, answer
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _detect_token_loop(tokens: List[int], min_period: int = 12, max_period: int = 48, min_repeats: int = 3) -> bool:
|
| 80 |
+
"""Detects exact repeating token cycles of length `p in [min_period, max_period]` repeated `>= min_repeats` times."""
|
| 81 |
+
n = len(tokens)
|
| 82 |
+
for p in range(min_period, min(max_period, n // min_repeats) + 1):
|
| 83 |
+
seg = tokens[n - p :]
|
| 84 |
+
ok = True
|
| 85 |
+
for r in range(2, min_repeats + 1):
|
| 86 |
+
if tokens[n - r * p : n - (r - 1) * p] != seg:
|
| 87 |
+
ok = False
|
| 88 |
+
break
|
| 89 |
+
if ok:
|
| 90 |
+
return True
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def install_inkling2_fast_ops() -> None:
|
| 95 |
+
"""Installs exact fused Triton + torch.compile Inkling-2 decode ops (graph-safe, zero drift)."""
|
| 96 |
+
global _PATCHED
|
| 97 |
+
if _PATCHED:
|
| 98 |
+
return
|
| 99 |
+
_PATCHED = True
|
| 100 |
+
torch._dynamo.config.recompile_limit = 64
|
| 101 |
+
|
| 102 |
+
# 1. Static ShortConvolution (176 calls/tok) -> single Triton kernel during B=1,T=1 decode
|
| 103 |
+
orig_short_conv_fwd = mik.Inkling2LoopShortConvolution.forward
|
| 104 |
+
|
| 105 |
+
def fast_short_conv_fwd(self, hidden_states, dynamic_input=None, cache=None, conv_mask=None, cache_offset=0, **kwargs):
|
| 106 |
+
if (
|
| 107 |
+
hidden_states.is_cuda
|
| 108 |
+
and hidden_states.shape[0] == 1
|
| 109 |
+
and hidden_states.shape[1] == 1
|
| 110 |
+
and conv_mask is None
|
| 111 |
+
and cache is not None
|
| 112 |
+
and self.conv_kernel_size == 4
|
| 113 |
+
and self.conv1d.bias is None
|
| 114 |
+
):
|
| 115 |
+
cli = self.layer_idx + cache_offset
|
| 116 |
+
conv_state = cache.get_conv_state(cli, state_idx=self.conv_idx)
|
| 117 |
+
if conv_state is not None and not cache.is_recording_past(cli):
|
| 118 |
+
return short_conv1d_step_res_triton(hidden_states, conv_state, self.conv1d.weight.squeeze(1))
|
| 119 |
+
return orig_short_conv_fwd(self, hidden_states, dynamic_input=dynamic_input, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 120 |
+
|
| 121 |
+
mik.Inkling2LoopShortConvolution.forward = fast_short_conv_fwd
|
| 122 |
+
|
| 123 |
+
# 2. Dynamic ShortConvolution (16 calls/tok) -> Triton GEMV + fused 4-tap conv kernel during B=1,T=1 decode
|
| 124 |
+
orig_dyn_conv_fwd = mik.Inkling2LoopDynamicShortConvolution.forward
|
| 125 |
+
|
| 126 |
+
def fast_dyn_conv_fwd(self, hidden_states, dynamic_input, cache=None, conv_mask=None, cache_offset=0, **kwargs):
|
| 127 |
+
if (
|
| 128 |
+
hidden_states.is_cuda
|
| 129 |
+
and hidden_states.shape[0] == 1
|
| 130 |
+
and hidden_states.shape[1] == 1
|
| 131 |
+
and conv_mask is None
|
| 132 |
+
and kwargs.get("seq_idx") is None
|
| 133 |
+
and cache is not None
|
| 134 |
+
and self.conv_kernel_size == 4
|
| 135 |
+
):
|
| 136 |
+
cli = self.layer_idx + cache_offset
|
| 137 |
+
conv_state = cache.get_conv_state(cli, state_idx=self.conv_idx)
|
| 138 |
+
if conv_state is not None and not cache.is_recording_past(cli):
|
| 139 |
+
return dyn_short_conv1d_step_res_triton(
|
| 140 |
+
hidden_states, dynamic_input, conv_state, self.static_weight, self.weight_proj.weight, self.num_heads
|
| 141 |
+
)
|
| 142 |
+
return orig_dyn_conv_fwd(self, hidden_states, dynamic_input, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 143 |
+
|
| 144 |
+
mik.Inkling2LoopDynamicShortConvolution.forward = fast_dyn_conv_fwd
|
| 145 |
+
|
| 146 |
+
# 3. Block & Message Attention Residuals (120 calls/tok) -> 2-kernel Triton (zero rocBLAS!)
|
| 147 |
+
@torch.compile(dynamic=True)
|
| 148 |
+
def _fused_attn_res_prefill(block_states_f: torch.Tensor, partial_f: torch.Tensor, query_f: torch.Tensor) -> torch.Tensor:
|
| 149 |
+
stacked = torch.cat([block_states_f, partial_f.unsqueeze(-2)], dim=-2)
|
| 150 |
+
normed = stacked * torch.rsqrt(stacked.square().mean(-1, keepdim=True) + 1e-6)
|
| 151 |
+
scores = torch.einsum("qh,btsh->btqs", query_f, normed) * (stacked.shape[-1] ** -0.5)
|
| 152 |
+
weights = torch.softmax(scores, dim=-1)
|
| 153 |
+
return torch.einsum("btqs,btsh->btqh", weights, normed)
|
| 154 |
+
|
| 155 |
+
def _run_attn_res_prefill(block_states: torch.Tensor, partial: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
|
| 156 |
+
T = int(partial.shape[1])
|
| 157 |
+
if T <= 512:
|
| 158 |
+
return _fused_attn_res_prefill(block_states.float(), partial.float(), q)
|
| 159 |
+
out = torch.empty((int(partial.shape[0]), T, int(q.shape[0]), int(partial.shape[-1])), device=partial.device, dtype=torch.float32)
|
| 160 |
+
for t0 in range(0, T, 512):
|
| 161 |
+
t1 = min(t0 + 512, T)
|
| 162 |
+
out[:, t0:t1] = _fused_attn_res_prefill(block_states[:, t0:t1].float(), partial[:, t0:t1].float(), q)
|
| 163 |
+
return out
|
| 164 |
+
|
| 165 |
+
def fast_block_attn_res_fwd(self, block_states, partial_block_states):
|
| 166 |
+
if partial_block_states.is_cuda and partial_block_states.shape[0] == 1 and partial_block_states.shape[1] == 1 and block_states.shape[-2] >= 1:
|
| 167 |
+
return attn_res_step_triton(block_states, partial_block_states, self.query).unbind(-2)
|
| 168 |
+
q = self.query.float().view(-1, block_states.shape[-1])
|
| 169 |
+
return _run_attn_res_prefill(block_states, partial_block_states, q).unbind(-2)
|
| 170 |
+
|
| 171 |
+
def fast_msg_attn_res_fwd(self, block_states, partial_block_states, loop_layer_idx):
|
| 172 |
+
q = self.query[loop_layer_idx]
|
| 173 |
+
if partial_block_states.is_cuda and partial_block_states.shape[0] == 1 and partial_block_states.shape[1] == 1 and block_states.shape[-2] >= 1:
|
| 174 |
+
return attn_res_step_triton(block_states, partial_block_states, q)
|
| 175 |
+
return _run_attn_res_prefill(block_states, partial_block_states, q.float())
|
| 176 |
+
|
| 177 |
+
mik.Inkling2LoopBlockAttentionResidual.forward = fast_block_attn_res_fwd
|
| 178 |
+
mik.Inkling2LoopMessageAttentionResidual.forward = fast_msg_attn_res_fwd
|
| 179 |
+
|
| 180 |
+
# 4. Looped Message Gate (96 calls/tok) -> 2-kernel Triton (bypasses slow rocBLAS M=1 fp32 mm!)
|
| 181 |
+
@torch.compile(dynamic=True)
|
| 182 |
+
def _fused_msg_gate_prefill(
|
| 183 |
+
h: torch.Tensor, m: torch.Tensor, w_dn: torch.Tensor, w_fg: torch.Tensor, w_mg: torch.Tensor, eps: float
|
| 184 |
+
) -> torch.Tensor:
|
| 185 |
+
hf, mf = h.float(), m.float()
|
| 186 |
+
hn = hf * torch.rsqrt(hf.square().mean(-1, keepdim=True) + eps)
|
| 187 |
+
mn = mf * torch.rsqrt(mf.square().mean(-1, keepdim=True) + eps)
|
| 188 |
+
g = F.linear(torch.cat([hn, mn], dim=-1).to(w_dn.dtype), w_dn).float()
|
| 189 |
+
fg = torch.tanh(F.linear(g, w_fg))
|
| 190 |
+
mg = torch.tanh(F.linear(g, w_mg))
|
| 191 |
+
return (1.0 - fg) * hf + mg * mf
|
| 192 |
+
|
| 193 |
+
def fast_msg_gate_fwd(self, h, m):
|
| 194 |
+
if h.is_cuda and h.shape[0] == 1 and h.shape[1] == 1:
|
| 195 |
+
return message_gate_triton(h, m, self.down_proj.weight, self.forget_gate_proj.weight, self.message_gate_proj.weight, self.norm.eps)
|
| 196 |
+
return _fused_msg_gate_prefill(h.contiguous(), m.contiguous(), self.down_proj.weight, self.forget_gate_proj.weight, self.message_gate_proj.weight, self.norm.eps)
|
| 197 |
+
|
| 198 |
+
mik.Inkling2LoopMessageGate.forward = fast_msg_gate_fwd
|
| 199 |
+
|
| 200 |
+
# 5. TopKRouter (48 calls/tok) -> Triton M=1 FP32 GEMV + fused sigmoid/topk/normalize
|
| 201 |
+
@torch.compile(dynamic=True)
|
| 202 |
+
def _fused_router_select(logits: torch.Tensor, bias: torch.Tensor, top_k: int, scale: float) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 203 |
+
scores = torch.sigmoid(logits)
|
| 204 |
+
indices = torch.topk(scores + bias, top_k, dim=-1, sorted=False).indices
|
| 205 |
+
weights = scores.gather(1, indices)
|
| 206 |
+
weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
|
| 207 |
+
return weights * scale, indices
|
| 208 |
+
|
| 209 |
+
orig_router_fwd = mik.Inkling2LoopTopKRouter.forward
|
| 210 |
+
|
| 211 |
+
def fast_router_fwd(self, hidden_states: torch.Tensor):
|
| 212 |
+
if hidden_states.is_cuda and hidden_states.numel() == self.hidden_dim:
|
| 213 |
+
logits = dense_gemv_triton(hidden_states.view(-1), self.weight, out_dtype=torch.float32).unsqueeze(0)
|
| 214 |
+
E = int(self.e_score_correction_bias.shape[-1])
|
| 215 |
+
if (E & (E - 1)) == 0:
|
| 216 |
+
weights, indices = router_topk_triton(logits, self.e_score_correction_bias, self.top_k, self.routed_scaling_factor)
|
| 217 |
+
else:
|
| 218 |
+
weights, indices = _fused_router_select(logits, self.e_score_correction_bias, self.top_k, self.routed_scaling_factor)
|
| 219 |
+
return logits, weights, indices
|
| 220 |
+
return orig_router_fwd(self, hidden_states)
|
| 221 |
+
|
| 222 |
+
mik.Inkling2LoopTopKRouter.forward = fast_router_fwd
|
| 223 |
+
|
| 224 |
+
# 6. Fused SoftcappedSwiGLU, RMSNorm, UnweightedRMSNorm, L2Clip, ScaledL2Clip, LogScaledL2Clip, GatedOutputProjection
|
| 225 |
+
@torch.compile(dynamic=True)
|
| 226 |
+
def _fused_softcap_swiglu(gate: torch.Tensor, up: torch.Tensor, g_cap: float, u_cap: float) -> torch.Tensor:
|
| 227 |
+
dt = gate.dtype
|
| 228 |
+
g, u = gate.float(), up.float()
|
| 229 |
+
return (torch.tanh(g / g_cap) * g_cap * torch.sigmoid(g) * torch.tanh(u / u_cap) * u_cap).to(dt)
|
| 230 |
+
|
| 231 |
+
mik.Inkling2LoopSoftcappedSwiGLU.forward = lambda self, gate, up: _fused_softcap_swiglu(
|
| 232 |
+
gate, up, self.gate_softcap.softcap, self.up_softcap.softcap
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
@torch.compile(dynamic=True)
|
| 236 |
+
def _fused_rmsnorm(x: torch.Tensor, w: torch.Tensor, eps: float) -> torch.Tensor:
|
| 237 |
+
dt = x.dtype
|
| 238 |
+
xf = x.float()
|
| 239 |
+
return (w * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps))).to(dt)
|
| 240 |
+
|
| 241 |
+
mik.Inkling2LoopRMSNorm.forward = lambda self, x: _fused_rmsnorm(x.contiguous(), self.weight, self.variance_epsilon)
|
| 242 |
+
|
| 243 |
+
orig_unw_norm_fwd = mik.Inkling2LoopUnweightedRMSNorm.forward
|
| 244 |
+
|
| 245 |
+
def fast_unw_rmsnorm_fwd(self, x: torch.Tensor) -> torch.Tensor:
|
| 246 |
+
D = int(x.shape[-1])
|
| 247 |
+
if x.is_cuda and D > 0 and (D & (D - 1)) == 0:
|
| 248 |
+
return unweighted_rmsnorm_triton(x, self.eps)
|
| 249 |
+
return orig_unw_norm_fwd(self, x)
|
| 250 |
+
|
| 251 |
+
mik.Inkling2LoopUnweightedRMSNorm.forward = fast_unw_rmsnorm_fwd
|
| 252 |
+
|
| 253 |
+
@torch.compile(dynamic=True)
|
| 254 |
+
def _fused_l2_clip(x: torch.Tensor, thr: float) -> torch.Tensor:
|
| 255 |
+
dt = x.dtype
|
| 256 |
+
xf = x.float()
|
| 257 |
+
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
|
| 258 |
+
return (xf * (thr / (n + 1e-6)).clamp(max=1.0)).to(dt)
|
| 259 |
+
|
| 260 |
+
mik.Inkling2LoopL2Clip.forward = lambda self, x: _fused_l2_clip(x.contiguous(), self.threshold)
|
| 261 |
+
|
| 262 |
+
@torch.compile(dynamic=True)
|
| 263 |
+
def _fused_scaled_l2_clip(x: torch.Tensor, scale: torch.Tensor, thr: float) -> torch.Tensor:
|
| 264 |
+
dt = x.dtype
|
| 265 |
+
xf = x.float() * scale.float()
|
| 266 |
+
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
|
| 267 |
+
return (xf * (thr / (n + 1e-6)).clamp(max=1.0)).to(dt)
|
| 268 |
+
|
| 269 |
+
mik.Inkling2LoopScaledL2Clip.forward = lambda self, x, position_ids=None: _fused_scaled_l2_clip(
|
| 270 |
+
x.contiguous(), self.scale, self.threshold
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
@torch.compile(dynamic=True)
|
| 274 |
+
def _fused_log_scaled_l2_clip(
|
| 275 |
+
x: torch.Tensor, scale: torch.Tensor, thr: float, pos: torch.Tensor, alpha: float, n_floor: float
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
dt = x.dtype
|
| 278 |
+
xf = x.float() * scale.float()
|
| 279 |
+
n = torch.linalg.vector_norm(xf, dim=-1, keepdim=True)
|
| 280 |
+
xf = xf * (thr / (n + 1e-6)).clamp(max=1.0)
|
| 281 |
+
ls = 1.0 + alpha * torch.log(((pos + 1).float() / n_floor).clamp(min=1.0))
|
| 282 |
+
return (xf * ls[..., None, None]).to(dt)
|
| 283 |
+
|
| 284 |
+
mik.Inkling2LoopLogScaledL2Clip.forward = lambda self, x, position_ids: _fused_log_scaled_l2_clip(
|
| 285 |
+
x.contiguous(),
|
| 286 |
+
self.scale,
|
| 287 |
+
self.l2_clip.threshold,
|
| 288 |
+
position_ids,
|
| 289 |
+
self.log_scale.log_scaling_alpha,
|
| 290 |
+
self.log_scale.log_scaling_n_floor,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
@torch.compile(dynamic=True)
|
| 294 |
+
def _fused_gate_mul(attn_out: torch.Tensor, gate_raw: torch.Tensor) -> torch.Tensor:
|
| 295 |
+
return (attn_out.float() * torch.sigmoid(gate_raw.float())).to(attn_out.dtype)
|
| 296 |
+
|
| 297 |
+
def fast_gated_o_proj(self, attn_output: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 298 |
+
gated = _fused_gate_mul(attn_output, self.gate_proj(hidden_states))
|
| 299 |
+
return self.linear(gated)
|
| 300 |
+
|
| 301 |
+
mik.Inkling2LoopGatedOutputProjection.forward = fast_gated_o_proj
|
| 302 |
+
|
| 303 |
+
# 7. Fused Triton GQA + RelPosBias + Per-Head Sink + Ring-Buffer Sliding/Full Decode Attention (48 calls/tok)
|
| 304 |
+
orig_slide_fwd = mik.Inkling2LoopSlidingAttention.forward
|
| 305 |
+
orig_full_fwd = mik.Inkling2LoopFullAttention.forward
|
| 306 |
+
|
| 307 |
+
def _run_fused_decode_attn(self, hidden_states, key_hidden_states, value_hidden_states, conv_mask, cache, cache_offset, kwargs):
|
| 308 |
+
pos_ids = kwargs["position_ids"]
|
| 309 |
+
query_states = self.q_proj(hidden_states, pos_ids)
|
| 310 |
+
key_states = self.k_proj(key_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 311 |
+
value_states = self.v_proj(value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 312 |
+
|
| 313 |
+
rpb = self.relative_position_bias
|
| 314 |
+
rel_lin = rpb.linear(hidden_states) if not isinstance(rpb.linear, torch.nn.Linear) else dense_gemv_triton(
|
| 315 |
+
hidden_states.view(-1), rpb.linear.weight, out_dtype=hidden_states.dtype
|
| 316 |
+
).view(1, 1, -1)
|
| 317 |
+
rel_states = rpb.norm(rel_lin.view(1, 1, self.num_heads, -1), pos_ids)
|
| 318 |
+
sinks = dense_gemv_triton(hidden_states.view(-1), self.sink_proj.weight, out_dtype=hidden_states.dtype)
|
| 319 |
+
|
| 320 |
+
cache_layer = cache.layers[self.layer_idx + cache_offset]
|
| 321 |
+
attn_out = inkling2_decode_attn_triton(
|
| 322 |
+
query_states,
|
| 323 |
+
key_states,
|
| 324 |
+
value_states,
|
| 325 |
+
cache_layer.keys,
|
| 326 |
+
cache_layer.values,
|
| 327 |
+
rel_states,
|
| 328 |
+
rpb.proj,
|
| 329 |
+
sinks,
|
| 330 |
+
_GRAPH_POS[0][0],
|
| 331 |
+
self.scaling,
|
| 332 |
+
is_sliding=self.is_sliding,
|
| 333 |
+
sliding_window=self.sliding_window if self.sliding_window is not None else 1024,
|
| 334 |
+
rel_extent=self.rel_extent,
|
| 335 |
+
)
|
| 336 |
+
return self.o_proj(attn_out.reshape(1, 1, -1), hidden_states), None
|
| 337 |
+
|
| 338 |
+
def _run_chunked_prefill_attn(
|
| 339 |
+
self, hidden_states, key_hidden_states, value_hidden_states, attention_mask, relative_distance,
|
| 340 |
+
conv_mask, cache, cache_offset, kwargs,
|
| 341 |
+
):
|
| 342 |
+
"""Exact chunked prefill attention over only valid `[:kv_valid]` KV slots (cuts 12K-ctx prefill VRAM by ~80x!)."""
|
| 343 |
+
input_shape = hidden_states.shape[:-1]
|
| 344 |
+
B, Q = int(input_shape[0]), int(input_shape[1])
|
| 345 |
+
pos_ids = kwargs["position_ids"]
|
| 346 |
+
query_states = self.q_proj(hidden_states, pos_ids)
|
| 347 |
+
key_states = self.k_proj(key_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 348 |
+
value_states = self.v_proj(value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
|
| 349 |
+
if cache is not None:
|
| 350 |
+
key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset, kwargs=kwargs)
|
| 351 |
+
|
| 352 |
+
kv_valid = min(int(key_states.shape[2]), int(_PREFILL_KV_LEN[0]))
|
| 353 |
+
k_rep = mik.repeat_kv(key_states[:, :, :kv_valid, :], self.num_key_value_groups)
|
| 354 |
+
v_rep = mik.repeat_kv(value_states[:, :, :kv_valid, :], self.num_key_value_groups)
|
| 355 |
+
sinks_all = self.sink_proj(hidden_states).transpose(1, 2).unsqueeze(-1)
|
| 356 |
+
D = int(query_states.shape[-1])
|
| 357 |
+
attn_out = torch.empty((B, Q, self.num_heads, D), device=query_states.device, dtype=query_states.dtype)
|
| 358 |
+
|
| 359 |
+
Q_CHUNK = 128
|
| 360 |
+
for q0 in range(0, Q, Q_CHUNK):
|
| 361 |
+
q1 = min(q0 + Q_CHUNK, Q)
|
| 362 |
+
rd_c = relative_distance[..., q0:q1, :kv_valid]
|
| 363 |
+
pb_c = self.relative_position_bias(hidden_states[:, q0:q1, :], rd_c, pos_ids[:, q0:q1])
|
| 364 |
+
aw = torch.matmul(query_states[:, :, q0:q1, :], k_rep.transpose(2, 3)) * self.scaling + pb_c
|
| 365 |
+
if attention_mask is not None:
|
| 366 |
+
aw = aw + attention_mask[:, :, q0:q1, :kv_valid]
|
| 367 |
+
combined = torch.cat([aw, sinks_all[:, :, q0:q1, :]], dim=-1).float()
|
| 368 |
+
probs = F.softmax(combined, dim=-1)[..., :-1].to(query_states.dtype)
|
| 369 |
+
attn_out[:, q0:q1, :, :] = torch.matmul(probs, v_rep).transpose(1, 2)
|
| 370 |
+
|
| 371 |
+
attn_out = attn_out.reshape(*input_shape, -1).contiguous()
|
| 372 |
+
return self.o_proj(attn_out, hidden_states), None
|
| 373 |
+
|
| 374 |
+
def fast_slide_attn_fwd(
|
| 375 |
+
self, hidden_states, attention_mask, relative_distance, conv_mask=None, cache=None,
|
| 376 |
+
key_hidden_states=None, value_hidden_states=None, cache_offset=0, **kwargs,
|
| 377 |
+
):
|
| 378 |
+
kh = hidden_states if key_hidden_states is None else key_hidden_states
|
| 379 |
+
vh = hidden_states if value_hidden_states is None else value_hidden_states
|
| 380 |
+
if _GRAPH_POS[0] is not None and hidden_states.is_cuda and hidden_states.shape[0] == 1 and hidden_states.shape[1] == 1 and cache is not None:
|
| 381 |
+
return _run_fused_decode_attn(self, hidden_states, kh, vh, conv_mask, cache, cache_offset, kwargs)
|
| 382 |
+
if _PREFILL_KV_LEN[0] is not None and hidden_states.is_cuda and hidden_states.shape[1] > 1 and cache is not None:
|
| 383 |
+
return _run_chunked_prefill_attn(
|
| 384 |
+
self, hidden_states, kh, vh, attention_mask, relative_distance, conv_mask, cache, cache_offset, kwargs
|
| 385 |
+
)
|
| 386 |
+
return orig_slide_fwd(
|
| 387 |
+
self, hidden_states, attention_mask, relative_distance, conv_mask=conv_mask, cache=cache,
|
| 388 |
+
key_hidden_states=key_hidden_states, value_hidden_states=value_hidden_states, cache_offset=cache_offset, **kwargs,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
def fast_full_attn_fwd(
|
| 392 |
+
self, hidden_states, key_hidden_states, value_hidden_states, attention_mask, relative_distance,
|
| 393 |
+
conv_mask=None, cache=None, cache_offset=0, **kwargs,
|
| 394 |
+
):
|
| 395 |
+
if _GRAPH_POS[0] is not None and hidden_states.is_cuda and hidden_states.shape[0] == 1 and hidden_states.shape[1] == 1 and cache is not None:
|
| 396 |
+
return _run_fused_decode_attn(self, hidden_states, key_hidden_states, value_hidden_states, conv_mask, cache, cache_offset, kwargs)
|
| 397 |
+
if _PREFILL_KV_LEN[0] is not None and hidden_states.is_cuda and hidden_states.shape[1] > 1 and cache is not None:
|
| 398 |
+
return _run_chunked_prefill_attn(
|
| 399 |
+
self, hidden_states, key_hidden_states, value_hidden_states, attention_mask, relative_distance,
|
| 400 |
+
conv_mask, cache, cache_offset, kwargs,
|
| 401 |
+
)
|
| 402 |
+
return orig_full_fwd(
|
| 403 |
+
self, hidden_states, key_hidden_states, value_hidden_states, attention_mask, relative_distance,
|
| 404 |
+
conv_mask=conv_mask, cache=cache, cache_offset=cache_offset, **kwargs,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
mik.Inkling2LoopSlidingAttention.forward = fast_slide_attn_fwd
|
| 408 |
+
mik.Inkling2LoopFullAttention.forward = fast_full_attn_fwd
|
| 409 |
+
|
| 410 |
+
orig_get_rel = mik.get_relative_distance
|
| 411 |
+
|
| 412 |
+
def graph_safe_get_rel(inputs_embeds, cache, is_sliding):
|
| 413 |
+
if _GRAPH_POS[0] is not None and inputs_embeds.shape[1] == 1:
|
| 414 |
+
return None
|
| 415 |
+
return orig_get_rel(inputs_embeds, cache, is_sliding)
|
| 416 |
+
|
| 417 |
+
mik.get_relative_distance = graph_safe_get_rel
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class Inkling2GraphEngine:
|
| 421 |
+
"""
|
| 422 |
+
Single-Graph HIP/CUDA-Graph decode engine for compressed `Inkling-2-Mini`.
|
| 423 |
+
Supports arbitrary context lengths (`1K..32K+`) via exact ring-buffer sliding KV caches
|
| 424 |
+
and implements official Thinking Machines / Unsloth sampling + anti-loop thinking guard.
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
def __init__(self, model: Inkling2LoopForConditionalGeneration, tokenizer, max_cache_len: int = 8192):
|
| 428 |
+
self.model = model
|
| 429 |
+
self.tokenizer = tokenizer
|
| 430 |
+
self.max_cache_len = int(max_cache_len)
|
| 431 |
+
self.sliding_window = int(model.config.text_config.sliding_window_size)
|
| 432 |
+
self.eos_id = int(model.config.eos_token_id)
|
| 433 |
+
self.device = "cuda"
|
| 434 |
+
self._warmed = False
|
| 435 |
+
self.last_stats: Dict[str, object] = {}
|
| 436 |
+
|
| 437 |
+
@torch.no_grad()
|
| 438 |
+
def _warmup_compile(self) -> None:
|
| 439 |
+
if self._warmed:
|
| 440 |
+
return
|
| 441 |
+
sc = StaticCache(config=self.model.config.text_config, max_cache_len=min(self.max_cache_len, 1024))
|
| 442 |
+
dummy = torch.tensor([[1, 2, 3, 4]], device=self.device, dtype=torch.long)
|
| 443 |
+
out = self.model(input_ids=dummy, cache=sc, use_cache=True, logits_to_keep=1)
|
| 444 |
+
nxt = out.logits[:, -1:].argmax(dim=-1)
|
| 445 |
+
g_pos = torch.tensor([[4]], device=self.device, dtype=torch.long)
|
| 446 |
+
_GRAPH_POS[0] = g_pos
|
| 447 |
+
try:
|
| 448 |
+
mask_none = {"full_attention": None, "sliding_attention": None, "linear_attention": None}
|
| 449 |
+
for step in range(2):
|
| 450 |
+
g_pos.fill_(4 + step)
|
| 451 |
+
out = self.model(input_ids=nxt, attention_mask=mask_none, position_ids=g_pos, cache=sc, use_cache=True, logits_to_keep=1)
|
| 452 |
+
nxt = out.logits[:, -1:].argmax(dim=-1)
|
| 453 |
+
finally:
|
| 454 |
+
_GRAPH_POS[0] = None
|
| 455 |
+
del sc, out, nxt, g_pos
|
| 456 |
+
torch.cuda.synchronize()
|
| 457 |
+
self._warmed = True
|
| 458 |
+
|
| 459 |
+
@torch.no_grad()
|
| 460 |
+
def _sample_next(
|
| 461 |
+
self,
|
| 462 |
+
logits_1d: torch.Tensor,
|
| 463 |
+
gen_ids: List[int],
|
| 464 |
+
temperature: float,
|
| 465 |
+
top_p: float,
|
| 466 |
+
top_k: int,
|
| 467 |
+
min_p: float,
|
| 468 |
+
repeat_penalty: float,
|
| 469 |
+
presence_penalty: float,
|
| 470 |
+
generator: Optional[torch.Generator],
|
| 471 |
+
) -> int:
|
| 472 |
+
if temperature <= 0.0 and repeat_penalty == 1.0 and presence_penalty == 0.0:
|
| 473 |
+
return int(logits_1d.argmax().item())
|
| 474 |
+
|
| 475 |
+
logits = logits_1d.float().clone()
|
| 476 |
+
if (repeat_penalty != 1.0 or presence_penalty != 0.0) and gen_ids:
|
| 477 |
+
uniq = torch.tensor(list(set(gen_ids)), device=logits.device, dtype=torch.long)
|
| 478 |
+
vals = logits[uniq]
|
| 479 |
+
if repeat_penalty != 1.0:
|
| 480 |
+
vals = torch.where(vals > 0.0, vals / repeat_penalty, vals * repeat_penalty)
|
| 481 |
+
if presence_penalty != 0.0:
|
| 482 |
+
vals = vals - presence_penalty
|
| 483 |
+
logits[uniq] = vals
|
| 484 |
+
|
| 485 |
+
if temperature <= 0.0:
|
| 486 |
+
return int(logits.argmax().item())
|
| 487 |
+
|
| 488 |
+
logits = logits / float(temperature)
|
| 489 |
+
probs = F.softmax(logits, dim=-1)
|
| 490 |
+
|
| 491 |
+
if min_p > 0.0:
|
| 492 |
+
p_max = probs.max()
|
| 493 |
+
probs = probs.masked_fill(probs < min_p * p_max, 0.0)
|
| 494 |
+
|
| 495 |
+
if top_k > 0 and top_k < probs.shape[-1]:
|
| 496 |
+
tk_v, tk_i = torch.topk(probs, top_k)
|
| 497 |
+
probs = torch.zeros_like(probs).scatter_(0, tk_i, tk_v)
|
| 498 |
+
|
| 499 |
+
if top_p < 1.0:
|
| 500 |
+
sp, si = torch.sort(probs, descending=True)
|
| 501 |
+
cm = torch.cumsum(sp, dim=-1)
|
| 502 |
+
sp = sp.masked_fill(cm - sp > top_p, 0.0)
|
| 503 |
+
s_sum = sp.sum()
|
| 504 |
+
if float(s_sum.item()) > 0.0:
|
| 505 |
+
return int(si[torch.multinomial(sp / s_sum, 1, generator=generator)].item())
|
| 506 |
+
|
| 507 |
+
p_sum = probs.sum()
|
| 508 |
+
if float(p_sum.item()) <= 0.0:
|
| 509 |
+
return int(logits.argmax().item())
|
| 510 |
+
return int(torch.multinomial(probs / p_sum, 1, generator=generator).item())
|
| 511 |
+
|
| 512 |
+
@torch.no_grad()
|
| 513 |
+
def generate(
|
| 514 |
+
self,
|
| 515 |
+
prompt: str | List[Dict[str, str]],
|
| 516 |
+
max_new_tokens: int = 4096,
|
| 517 |
+
reasoning_effort: str = "low",
|
| 518 |
+
temperature: float = 1.0,
|
| 519 |
+
top_p: float = 1.0,
|
| 520 |
+
top_k: int = 0,
|
| 521 |
+
min_p: float = 0.0,
|
| 522 |
+
repeat_penalty: float = 1.0,
|
| 523 |
+
presence_penalty: float = 0.0,
|
| 524 |
+
max_thinking_tokens: int = 0,
|
| 525 |
+
min_answer_tokens: int = 0,
|
| 526 |
+
loop_guard: bool = True,
|
| 527 |
+
seed: Optional[int] = None,
|
| 528 |
+
) -> Tuple[str, int, float, float]:
|
| 529 |
+
"""
|
| 530 |
+
Generates response via single-graph HIP/CUDA-Graph replay.
|
| 531 |
+
Defaults match official Thinking Machines / Unsloth settings (`temp=1.0, top_p=1.0, top_k=0, min_p=0.0`).
|
| 532 |
+
Populates `self.last_stats` with `finish_reason` (`"stop"`, `"length"`, `"cache_full"`, `"answer_loop"`),
|
| 533 |
+
`thinking_tokens`, `answer_tokens`, `thinking_capped`, and `loop_broken`.
|
| 534 |
+
Returns `(raw_text, n_tokens, decode_tok_s, prefill_ms)`.
|
| 535 |
+
"""
|
| 536 |
+
self._warmup_compile()
|
| 537 |
+
messages = [{"role": "user", "content": prompt}] if isinstance(prompt, str) else prompt
|
| 538 |
+
eff_arg: str | float = reasoning_effort
|
| 539 |
+
try:
|
| 540 |
+
if reasoning_effort not in ("none", "minimal", "low", "medium", "high", "xhigh", "max"):
|
| 541 |
+
eff_arg = float(reasoning_effort)
|
| 542 |
+
except Exception:
|
| 543 |
+
eff_arg = reasoning_effort
|
| 544 |
+
|
| 545 |
+
inp = self.tokenizer.apply_chat_template(
|
| 546 |
+
messages,
|
| 547 |
+
tokenize=True,
|
| 548 |
+
add_generation_prompt=True,
|
| 549 |
+
reasoning_effort=eff_arg,
|
| 550 |
+
return_dict=True,
|
| 551 |
+
return_tensors="pt",
|
| 552 |
+
)
|
| 553 |
+
input_ids = inp["input_ids"].to(self.device)
|
| 554 |
+
prompt_len = int(input_ids.shape[1])
|
| 555 |
+
cache_room = self.max_cache_len - prompt_len - 1
|
| 556 |
+
budget = min(int(max_new_tokens), cache_room)
|
| 557 |
+
if budget <= 1:
|
| 558 |
+
raise ValueError(f"Prompt ({prompt_len} tokens) exceeds max_cache_len={self.max_cache_len}")
|
| 559 |
+
|
| 560 |
+
eff_max_think = int(max_thinking_tokens)
|
| 561 |
+
if min_answer_tokens > 0 and budget > int(min_answer_tokens) + 64:
|
| 562 |
+
max_allowed_think = budget - int(min_answer_tokens)
|
| 563 |
+
eff_max_think = max_allowed_think if eff_max_think <= 0 else min(eff_max_think, max_allowed_think)
|
| 564 |
+
|
| 565 |
+
gen = None
|
| 566 |
+
if seed is not None:
|
| 567 |
+
gen = torch.Generator(device=self.device)
|
| 568 |
+
gen.manual_seed(int(seed))
|
| 569 |
+
|
| 570 |
+
sc = StaticCache(config=self.model.config.text_config, max_cache_len=self.max_cache_len)
|
| 571 |
+
torch.cuda.synchronize()
|
| 572 |
+
t_pre = time.time()
|
| 573 |
+
_PREFILL_KV_LEN[0] = prompt_len
|
| 574 |
+
try:
|
| 575 |
+
out = self.model(input_ids=input_ids, cache=sc, use_cache=True, logits_to_keep=1)
|
| 576 |
+
finally:
|
| 577 |
+
_PREFILL_KV_LEN[0] = None
|
| 578 |
+
# If prompt_len > sliding_window, align sliding layers into ring-buffer layout slot(t) = t & (W - 1)
|
| 579 |
+
if prompt_len > self.sliding_window:
|
| 580 |
+
shift = prompt_len & (self.sliding_window - 1)
|
| 581 |
+
if shift != 0:
|
| 582 |
+
for layer in sc.layers:
|
| 583 |
+
if getattr(layer, "is_sliding", False) and layer.keys is not None:
|
| 584 |
+
layer.keys.copy_(layer.keys.roll(shift, dims=-2))
|
| 585 |
+
layer.values.copy_(layer.values.roll(shift, dims=-2))
|
| 586 |
+
torch.cuda.synchronize()
|
| 587 |
+
prefill_ms = (time.time() - t_pre) * 1000.0
|
| 588 |
+
|
| 589 |
+
tok0 = self._sample_next(out.logits[0, -1], [], temperature, top_p, top_k, min_p, repeat_penalty, presence_penalty, gen)
|
| 590 |
+
gen_ids = [tok0]
|
| 591 |
+
if tok0 == self.eos_id:
|
| 592 |
+
self.last_stats = {
|
| 593 |
+
"finish_reason": "stop",
|
| 594 |
+
"prompt_tokens": prompt_len,
|
| 595 |
+
"total_tokens": 1,
|
| 596 |
+
"thinking_tokens": 0,
|
| 597 |
+
"answer_tokens": 0,
|
| 598 |
+
"thinking_capped": False,
|
| 599 |
+
"loop_broken": False,
|
| 600 |
+
"budget": budget,
|
| 601 |
+
"max_cache_len": self.max_cache_len,
|
| 602 |
+
}
|
| 603 |
+
return self.tokenizer.decode(gen_ids, skip_special_tokens=False), 1, 0.0, prefill_ms
|
| 604 |
+
|
| 605 |
+
in_thinking = tok0 == TOK_CONTENT_THINKING
|
| 606 |
+
in_answer = tok0 == TOK_CONTENT_TEXT
|
| 607 |
+
think_tokens: List[int] = []
|
| 608 |
+
answer_tokens: List[int] = []
|
| 609 |
+
total_think_tokens = 0
|
| 610 |
+
completed_answer_blocks = 0
|
| 611 |
+
thinking_closed_by_guard = False
|
| 612 |
+
thinking_capped = False
|
| 613 |
+
loop_broken = False
|
| 614 |
+
grace_left = -1
|
| 615 |
+
forced_queue: List[int] = []
|
| 616 |
+
finish_reason = "cache_full" if cache_room <= int(max_new_tokens) else "length"
|
| 617 |
+
|
| 618 |
+
cur_pos = prompt_len
|
| 619 |
+
g_inp = torch.tensor([[tok0]], device=self.device, dtype=torch.long)
|
| 620 |
+
g_pos_ids = torch.tensor([[cur_pos]], device=self.device, dtype=torch.long)
|
| 621 |
+
_GRAPH_POS[0] = g_pos_ids
|
| 622 |
+
|
| 623 |
+
g: Optional[torch.cuda.CUDAGraph] = torch.cuda.CUDAGraph()
|
| 624 |
+
try:
|
| 625 |
+
mask_none = {"full_attention": None, "sliding_attention": None, "linear_attention": None}
|
| 626 |
+
with torch.cuda.graph(g):
|
| 627 |
+
g_logits = self.model(
|
| 628 |
+
input_ids=g_inp,
|
| 629 |
+
attention_mask=mask_none,
|
| 630 |
+
position_ids=g_pos_ids,
|
| 631 |
+
cache=sc,
|
| 632 |
+
use_cache=True,
|
| 633 |
+
logits_to_keep=1,
|
| 634 |
+
).logits[:, -1:]
|
| 635 |
+
|
| 636 |
+
torch.cuda.synchronize()
|
| 637 |
+
t0 = time.time()
|
| 638 |
+
for _ in range(1, budget):
|
| 639 |
+
g_pos_ids.fill_(cur_pos)
|
| 640 |
+
g.replay()
|
| 641 |
+
if forced_queue:
|
| 642 |
+
nxt = forced_queue.pop(0)
|
| 643 |
+
else:
|
| 644 |
+
nxt = self._sample_next(
|
| 645 |
+
g_logits[0, 0], gen_ids, temperature, top_p, top_k, min_p, repeat_penalty, presence_penalty, gen
|
| 646 |
+
)
|
| 647 |
+
gen_ids.append(nxt)
|
| 648 |
+
if nxt == self.eos_id:
|
| 649 |
+
finish_reason = "stop"
|
| 650 |
+
break
|
| 651 |
+
|
| 652 |
+
if nxt == TOK_CONTENT_THINKING:
|
| 653 |
+
in_answer = False
|
| 654 |
+
if thinking_closed_by_guard or (eff_max_think > 0 and total_think_tokens >= eff_max_think):
|
| 655 |
+
if completed_answer_blocks > 0:
|
| 656 |
+
# Already emitted a complete <|content_text|>...<|end_message|> answer;
|
| 657 |
+
# stop cleanly rather than forcing a duplicate rewrite pass.
|
| 658 |
+
gen_ids.pop() # drop stray <|content_thinking|>
|
| 659 |
+
if gen_ids and gen_ids[-1] == TOK_MESSAGE_MODEL:
|
| 660 |
+
gen_ids.pop()
|
| 661 |
+
finish_reason = "stop"
|
| 662 |
+
break
|
| 663 |
+
# Prevent reopening a second thinking spiral before any answer is emitted.
|
| 664 |
+
in_thinking = False
|
| 665 |
+
forced_queue = [TOK_END_MESSAGE, TOK_MESSAGE_MODEL, TOK_CONTENT_TEXT]
|
| 666 |
+
else:
|
| 667 |
+
in_thinking = True
|
| 668 |
+
think_tokens.clear()
|
| 669 |
+
grace_left = -1
|
| 670 |
+
elif nxt == TOK_CONTENT_TEXT:
|
| 671 |
+
in_thinking = False
|
| 672 |
+
in_answer = True
|
| 673 |
+
grace_left = -1
|
| 674 |
+
elif nxt == TOK_END_MESSAGE:
|
| 675 |
+
if in_answer and answer_tokens:
|
| 676 |
+
completed_answer_blocks += 1
|
| 677 |
+
in_thinking = False
|
| 678 |
+
in_answer = False
|
| 679 |
+
grace_left = -1
|
| 680 |
+
elif in_thinking:
|
| 681 |
+
think_tokens.append(nxt)
|
| 682 |
+
total_think_tokens += 1
|
| 683 |
+
hit_loop = loop_guard and len(think_tokens) >= 48 and _detect_token_loop(think_tokens)
|
| 684 |
+
if hit_loop:
|
| 685 |
+
in_thinking = False
|
| 686 |
+
thinking_closed_by_guard = True
|
| 687 |
+
loop_broken = True
|
| 688 |
+
grace_left = -1
|
| 689 |
+
forced_queue = [TOK_END_MESSAGE, TOK_MESSAGE_MODEL, TOK_CONTENT_TEXT]
|
| 690 |
+
elif eff_max_think > 0 and total_think_tokens >= eff_max_think:
|
| 691 |
+
if grace_left < 0:
|
| 692 |
+
grace_left = 32
|
| 693 |
+
tok_piece = self.tokenizer.decode([nxt], skip_special_tokens=False)
|
| 694 |
+
at_boundary = any(ch in tok_piece for ch in ("\n", ".", "!", "?"))
|
| 695 |
+
if at_boundary or grace_left == 0:
|
| 696 |
+
in_thinking = False
|
| 697 |
+
thinking_closed_by_guard = True
|
| 698 |
+
thinking_capped = True
|
| 699 |
+
grace_left = -1
|
| 700 |
+
forced_queue = [TOK_END_MESSAGE, TOK_MESSAGE_MODEL, TOK_CONTENT_TEXT]
|
| 701 |
+
else:
|
| 702 |
+
grace_left -= 1
|
| 703 |
+
elif in_answer:
|
| 704 |
+
answer_tokens.append(nxt)
|
| 705 |
+
if loop_guard and len(answer_tokens) >= 160 and _detect_token_loop(answer_tokens, min_period=24, max_period=64, min_repeats=5):
|
| 706 |
+
loop_broken = True
|
| 707 |
+
finish_reason = "answer_loop"
|
| 708 |
+
break
|
| 709 |
+
|
| 710 |
+
g_inp.fill_(nxt)
|
| 711 |
+
cur_pos += 1
|
| 712 |
+
torch.cuda.synchronize()
|
| 713 |
+
dt = time.time() - t0
|
| 714 |
+
n_dec = max(1, len(gen_ids) - 1)
|
| 715 |
+
tok_s = n_dec / max(dt, 1e-6)
|
| 716 |
+
finally:
|
| 717 |
+
_GRAPH_POS[0] = None
|
| 718 |
+
if g is not None:
|
| 719 |
+
g.reset()
|
| 720 |
+
del g
|
| 721 |
+
del sc
|
| 722 |
+
gc.collect()
|
| 723 |
+
torch.cuda.synchronize()
|
| 724 |
+
|
| 725 |
+
self.last_stats = {
|
| 726 |
+
"finish_reason": finish_reason,
|
| 727 |
+
"prompt_tokens": prompt_len,
|
| 728 |
+
"total_tokens": len(gen_ids),
|
| 729 |
+
"thinking_tokens": total_think_tokens,
|
| 730 |
+
"answer_tokens": len(answer_tokens),
|
| 731 |
+
"thinking_capped": thinking_capped,
|
| 732 |
+
"loop_broken": loop_broken,
|
| 733 |
+
"budget": budget,
|
| 734 |
+
"max_cache_len": self.max_cache_len,
|
| 735 |
+
}
|
| 736 |
+
return self.tokenizer.decode(gen_ids, skip_special_tokens=False), len(gen_ids), tok_s, prefill_ms
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def main() -> None:
|
| 740 |
+
ap = argparse.ArgumentParser(description="Ultra-fast HIP/CUDA-Graph inference for PRIME-Quant Inkling-2-Mini")
|
| 741 |
+
ap.add_argument("--src-model", type=str, default=HERE, help="Path to local Inkling-2-Mini config/tokenizer directory")
|
| 742 |
+
ap.add_argument("--checkpoint", type=str, default=os.path.join(HERE, "inkling2_mini_p2_looptop8.safetensors"), help="Path to PRIME-Quant .safetensors checkpoint")
|
| 743 |
+
ap.add_argument("--max-cache-len", type=int, default=8192)
|
| 744 |
+
ap.add_argument("--max-new-tokens", type=int, default=4096)
|
| 745 |
+
ap.add_argument("--reasoning-effort", type=str, default="low", help="none|minimal|low|medium|high|xhigh|max or float [0.0, 0.99]")
|
| 746 |
+
ap.add_argument("--temperature", type=float, default=1.0, help="Official Inkling-2 default: 1.0 (avoid <0.6 to prevent reasoning loops)")
|
| 747 |
+
ap.add_argument("--top-p", type=float, default=1.0, help="Official Inkling-2 default: 1.0")
|
| 748 |
+
ap.add_argument("--top-k", type=int, default=0, help="Official Inkling-2 default: 0 (disabled)")
|
| 749 |
+
ap.add_argument("--min-p", type=float, default=0.0, help="Official Inkling-2 default: 0.0")
|
| 750 |
+
ap.add_argument("--repeat-penalty", type=float, default=1.0)
|
| 751 |
+
ap.add_argument("--presence-penalty", type=float, default=0.0)
|
| 752 |
+
ap.add_argument("--max-thinking-tokens", type=int, default=0, help="Hard cap on thinking block tokens (0 = unlimited)")
|
| 753 |
+
ap.add_argument("--min-answer-tokens", type=int, default=0, help="Guarantee at least N answer tokens by capping thinking if needed")
|
| 754 |
+
ap.add_argument("--no-loop-guard", action="store_true", help="Disable automatic CoT/answer repetition-loop breaker")
|
| 755 |
+
ap.add_argument("--greedy", action="store_true", help="Override temperature=0.0 for deterministic greedy decoding")
|
| 756 |
+
ap.add_argument("--seed", type=int, default=None)
|
| 757 |
+
ap.add_argument("--raw", action="store_true", help="Print raw Inkling-2 tokens instead of parsed thinking/answer")
|
| 758 |
+
ap.add_argument("--interactive", action="store_true", help="Launch multi-turn interactive terminal chat")
|
| 759 |
+
ap.add_argument("--prompt", type=str, action="append", default=None, help="Prompt(s) to run (repeatable)")
|
| 760 |
+
args = ap.parse_args()
|
| 761 |
+
|
| 762 |
+
temp = 0.0 if args.greedy else args.temperature
|
| 763 |
+
install_inkling2_fast_ops()
|
| 764 |
+
|
| 765 |
+
t0 = time.time()
|
| 766 |
+
tokenizer = AutoTokenizer.from_pretrained(args.src_model)
|
| 767 |
+
cfg = AutoConfig.from_pretrained(args.src_model)
|
| 768 |
+
with torch.device("meta"):
|
| 769 |
+
model = Inkling2LoopForConditionalGeneration(cfg)
|
| 770 |
+
stats = load_prime_safetensors(model, args.checkpoint, device="cuda", compute_dtype=torch.bfloat16)
|
| 771 |
+
torch.cuda.synchronize()
|
| 772 |
+
print(
|
| 773 |
+
f"[loaded] {os.path.basename(args.checkpoint)} in {time.time() - t0:.2f}s | "
|
| 774 |
+
f"VRAM={stats['resident_vram_mb'] / 1e3:.3f} GB | 2-bit={stats['modules_2bit']} | 4-bit={stats['modules_4bit']} | "
|
| 775 |
+
f"ctx={args.max_cache_len} | temp={temp} top_p={args.top_p} effort={args.reasoning_effort}",
|
| 776 |
+
flush=True,
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
engine = Inkling2GraphEngine(model, tokenizer, max_cache_len=args.max_cache_len)
|
| 780 |
+
|
| 781 |
+
if args.interactive:
|
| 782 |
+
history: List[Dict[str, str]] = []
|
| 783 |
+
print("Interactive Inkling-2-Mini chat (type 'exit' or '/reset' to clear history).", flush=True)
|
| 784 |
+
while True:
|
| 785 |
+
try:
|
| 786 |
+
user_msg = input("\nYou> ").strip()
|
| 787 |
+
except (EOFError, KeyboardInterrupt):
|
| 788 |
+
break
|
| 789 |
+
if not user_msg or user_msg.lower() in ("exit", "quit"):
|
| 790 |
+
break
|
| 791 |
+
if user_msg == "/reset":
|
| 792 |
+
history.clear()
|
| 793 |
+
print("[history cleared]")
|
| 794 |
+
continue
|
| 795 |
+
history.append({"role": "user", "content": user_msg})
|
| 796 |
+
raw, n_tok, tok_s, pre_ms = engine.generate(
|
| 797 |
+
history,
|
| 798 |
+
max_new_tokens=args.max_new_tokens,
|
| 799 |
+
reasoning_effort=args.reasoning_effort,
|
| 800 |
+
temperature=temp,
|
| 801 |
+
top_p=args.top_p,
|
| 802 |
+
top_k=args.top_k,
|
| 803 |
+
min_p=args.min_p,
|
| 804 |
+
repeat_penalty=args.repeat_penalty,
|
| 805 |
+
presence_penalty=args.presence_penalty,
|
| 806 |
+
max_thinking_tokens=args.max_thinking_tokens,
|
| 807 |
+
min_answer_tokens=args.min_answer_tokens,
|
| 808 |
+
loop_guard=not args.no_loop_guard,
|
| 809 |
+
seed=args.seed,
|
| 810 |
+
)
|
| 811 |
+
thinking, answer = parse_inkling_output(raw)
|
| 812 |
+
history.append({"role": "assistant", "content": answer})
|
| 813 |
+
fr = engine.last_stats.get("finish_reason", "unknown")
|
| 814 |
+
warn = f" | finish={fr}" if fr != "stop" else ""
|
| 815 |
+
if args.raw:
|
| 816 |
+
print(f"\n[{n_tok} toks @ {tok_s:.2f} tok/s | prefill {pre_ms:.0f} ms{warn}]\n{raw}", flush=True)
|
| 817 |
+
else:
|
| 818 |
+
if thinking:
|
| 819 |
+
print(f"\n[Thinking]\n{thinking}\n", flush=True)
|
| 820 |
+
print(f"[Assistant | {n_tok} toks @ {tok_s:.2f} tok/s | prefill {pre_ms:.0f} ms{warn}]\n{answer}", flush=True)
|
| 821 |
+
return
|
| 822 |
+
|
| 823 |
+
prompts = args.prompt or [
|
| 824 |
+
"Write a concise, bug-free Python function `merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]` with edge-case handling and a quick doctest.",
|
| 825 |
+
"Find and fix the subtle infinite-loop / boundary bug in this Python binary search and show the exact failing input:\n```python\ndef first_ge(arr, target):\n lo, hi = 0, len(arr) - 1\n while lo < hi:\n mid = (lo + hi + 1) // 2\n if arr[mid] >= target:\n hi = mid\n else:\n lo = mid + 1\n return lo\n```",
|
| 826 |
+
]
|
| 827 |
+
for i, pr in enumerate(prompts):
|
| 828 |
+
raw, n_tok, tok_s, pre_ms = engine.generate(
|
| 829 |
+
pr,
|
| 830 |
+
max_new_tokens=args.max_new_tokens,
|
| 831 |
+
reasoning_effort=args.reasoning_effort,
|
| 832 |
+
temperature=temp,
|
| 833 |
+
top_p=args.top_p,
|
| 834 |
+
top_k=args.top_k,
|
| 835 |
+
min_p=args.min_p,
|
| 836 |
+
repeat_penalty=args.repeat_penalty,
|
| 837 |
+
presence_penalty=args.presence_penalty,
|
| 838 |
+
max_thinking_tokens=args.max_thinking_tokens,
|
| 839 |
+
min_answer_tokens=args.min_answer_tokens,
|
| 840 |
+
loop_guard=not args.no_loop_guard,
|
| 841 |
+
seed=args.seed,
|
| 842 |
+
)
|
| 843 |
+
fr = engine.last_stats.get("finish_reason", "unknown")
|
| 844 |
+
warn = f" | finish={fr}" if fr != "stop" else ""
|
| 845 |
+
print(
|
| 846 |
+
f"\n{'=' * 78}\n[Prompt {i + 1}] prefill={pre_ms:.1f} ms | generated={n_tok} toks @ {tok_s:.2f} tok/s{warn}\n{'=' * 78}",
|
| 847 |
+
flush=True,
|
| 848 |
+
)
|
| 849 |
+
if args.raw:
|
| 850 |
+
print(raw, flush=True)
|
| 851 |
+
else:
|
| 852 |
+
thinking, answer = parse_inkling_output(raw)
|
| 853 |
+
if thinking:
|
| 854 |
+
print(f"[Thinking]\n{thinking}\n", flush=True)
|
| 855 |
+
print(f"[Answer]\n{answer}", flush=True)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
if __name__ == "__main__":
|
| 859 |
+
main()
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|endoftext|>",
|
| 4 |
+
"<|message_user|>",
|
| 5 |
+
"<|message_model|>",
|
| 6 |
+
"<|message_system|>",
|
| 7 |
+
"<|message_tool|>",
|
| 8 |
+
"<|content_text|>",
|
| 9 |
+
"<|content_image|>",
|
| 10 |
+
"<|content_model_end_sampling|>",
|
| 11 |
+
"<|content_thinking|>",
|
| 12 |
+
"<|end_message|>",
|
| 13 |
+
"<|content_tool_error|>",
|
| 14 |
+
"<|content_xml|>",
|
| 15 |
+
"<|begin_of_text|>",
|
| 16 |
+
"<|content_invoke_tool_json|>",
|
| 17 |
+
"<|content_invoke_tool_text|>"
|
| 18 |
+
],
|
| 19 |
+
"eos_token": "<|content_model_end_sampling|>",
|
| 20 |
+
"pad_token": "<|endoftext|>"
|
| 21 |
+
}
|
tiktoken/tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f170372dd655728909228220d77cf6b8104a59f38a91262a7d2c4027906ec0d8
|
| 3 |
+
size 3386494
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6
|
| 3 |
+
size 26178678
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"model_max_length": 1048576,
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"fix_mistral_regex": false,
|
| 6 |
+
"extra_special_tokens": {
|
| 7 |
+
"endoftext": "<|endoftext|>",
|
| 8 |
+
"message_user": "<|message_user|>",
|
| 9 |
+
"message_model": "<|message_model|>",
|
| 10 |
+
"message_system": "<|message_system|>",
|
| 11 |
+
"message_tool": "<|message_tool|>",
|
| 12 |
+
"content_text": "<|content_text|>",
|
| 13 |
+
"content_image": "<|content_image|>",
|
| 14 |
+
"content_model_end_sampling": "<|content_model_end_sampling|>",
|
| 15 |
+
"content_thinking": "<|content_thinking|>",
|
| 16 |
+
"end_message": "<|end_message|>",
|
| 17 |
+
"content_tool_error": "<|content_tool_error|>",
|
| 18 |
+
"content_xml": "<|content_xml|>",
|
| 19 |
+
"begin_of_text": "<|begin_of_text|>",
|
| 20 |
+
"content_invoke_tool_json": "<|content_invoke_tool_json|>",
|
| 21 |
+
"content_invoke_tool_text": "<|content_invoke_tool_text|>"
|
| 22 |
+
},
|
| 23 |
+
"added_tokens_decoder": {
|
| 24 |
+
"199998": {
|
| 25 |
+
"content": "<|unused|>",
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"lstrip": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"normalized": false,
|
| 30 |
+
"special": true
|
| 31 |
+
},
|
| 32 |
+
"199999": {
|
| 33 |
+
"content": "<|endoftext|>",
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"lstrip": false,
|
| 36 |
+
"rstrip": false,
|
| 37 |
+
"normalized": false,
|
| 38 |
+
"special": true
|
| 39 |
+
},
|
| 40 |
+
"200000": {
|
| 41 |
+
"content": "<|message_user|>",
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"lstrip": false,
|
| 44 |
+
"rstrip": false,
|
| 45 |
+
"normalized": false,
|
| 46 |
+
"special": true
|
| 47 |
+
},
|
| 48 |
+
"200001": {
|
| 49 |
+
"content": "<|message_model|>",
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"lstrip": false,
|
| 52 |
+
"rstrip": false,
|
| 53 |
+
"normalized": false,
|
| 54 |
+
"special": true
|
| 55 |
+
},
|
| 56 |
+
"200002": {
|
| 57 |
+
"content": "<|message_system|>",
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"lstrip": false,
|
| 60 |
+
"rstrip": false,
|
| 61 |
+
"normalized": false,
|
| 62 |
+
"special": true
|
| 63 |
+
},
|
| 64 |
+
"200003": {
|
| 65 |
+
"content": "<|message_tool|>",
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"lstrip": false,
|
| 68 |
+
"rstrip": false,
|
| 69 |
+
"normalized": false,
|
| 70 |
+
"special": true
|
| 71 |
+
},
|
| 72 |
+
"200004": {
|
| 73 |
+
"content": "<|content_text|>",
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"lstrip": false,
|
| 76 |
+
"rstrip": false,
|
| 77 |
+
"normalized": false,
|
| 78 |
+
"special": true
|
| 79 |
+
},
|
| 80 |
+
"200005": {
|
| 81 |
+
"content": "<|content_image|>",
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"lstrip": false,
|
| 84 |
+
"rstrip": false,
|
| 85 |
+
"normalized": false,
|
| 86 |
+
"special": true
|
| 87 |
+
},
|
| 88 |
+
"200006": {
|
| 89 |
+
"content": "<|content_model_end_sampling|>",
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"lstrip": false,
|
| 92 |
+
"rstrip": false,
|
| 93 |
+
"normalized": false,
|
| 94 |
+
"special": true
|
| 95 |
+
},
|
| 96 |
+
"200007": {
|
| 97 |
+
"content": "<|unused_200007|>",
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"lstrip": false,
|
| 100 |
+
"rstrip": false,
|
| 101 |
+
"normalized": false,
|
| 102 |
+
"special": true
|
| 103 |
+
},
|
| 104 |
+
"200008": {
|
| 105 |
+
"content": "<|content_thinking|>",
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"lstrip": false,
|
| 108 |
+
"rstrip": false,
|
| 109 |
+
"normalized": false,
|
| 110 |
+
"special": true
|
| 111 |
+
},
|
| 112 |
+
"200009": {
|
| 113 |
+
"content": "<|unused_200009|>",
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"lstrip": false,
|
| 116 |
+
"rstrip": false,
|
| 117 |
+
"normalized": false,
|
| 118 |
+
"special": true
|
| 119 |
+
},
|
| 120 |
+
"200010": {
|
| 121 |
+
"content": "<|end_message|>",
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"lstrip": false,
|
| 124 |
+
"rstrip": false,
|
| 125 |
+
"normalized": false,
|
| 126 |
+
"special": true
|
| 127 |
+
},
|
| 128 |
+
"200011": {
|
| 129 |
+
"content": "<|unused_200011|>",
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"lstrip": false,
|
| 132 |
+
"rstrip": false,
|
| 133 |
+
"normalized": false,
|
| 134 |
+
"special": true
|
| 135 |
+
},
|
| 136 |
+
"200012": {
|
| 137 |
+
"content": "<|unused_200012|>",
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"lstrip": false,
|
| 140 |
+
"rstrip": false,
|
| 141 |
+
"normalized": false,
|
| 142 |
+
"special": true
|
| 143 |
+
},
|
| 144 |
+
"200013": {
|
| 145 |
+
"content": "<|unused_200013|>",
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"lstrip": false,
|
| 148 |
+
"rstrip": false,
|
| 149 |
+
"normalized": false,
|
| 150 |
+
"special": true
|
| 151 |
+
},
|
| 152 |
+
"200014": {
|
| 153 |
+
"content": "<|unused_200014|>",
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"lstrip": false,
|
| 156 |
+
"rstrip": false,
|
| 157 |
+
"normalized": false,
|
| 158 |
+
"special": true
|
| 159 |
+
},
|
| 160 |
+
"200015": {
|
| 161 |
+
"content": "<|unused_200015|>",
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"lstrip": false,
|
| 164 |
+
"rstrip": false,
|
| 165 |
+
"normalized": false,
|
| 166 |
+
"special": true
|
| 167 |
+
},
|
| 168 |
+
"200016": {
|
| 169 |
+
"content": "<|unused_200016|>",
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"lstrip": false,
|
| 172 |
+
"rstrip": false,
|
| 173 |
+
"normalized": false,
|
| 174 |
+
"special": true
|
| 175 |
+
},
|
| 176 |
+
"200017": {
|
| 177 |
+
"content": "<|unused_200017|>",
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"lstrip": false,
|
| 180 |
+
"rstrip": false,
|
| 181 |
+
"normalized": false,
|
| 182 |
+
"special": true
|
| 183 |
+
},
|
| 184 |
+
"200018": {
|
| 185 |
+
"content": "<|unused_200018|>",
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"lstrip": false,
|
| 188 |
+
"rstrip": false,
|
| 189 |
+
"normalized": false,
|
| 190 |
+
"special": true
|
| 191 |
+
},
|
| 192 |
+
"200019": {
|
| 193 |
+
"content": "<|unused_200019|>",
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"lstrip": false,
|
| 196 |
+
"rstrip": false,
|
| 197 |
+
"normalized": false,
|
| 198 |
+
"special": true
|
| 199 |
+
},
|
| 200 |
+
"200020": {
|
| 201 |
+
"content": "<|unused_200020|>",
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"lstrip": false,
|
| 204 |
+
"rstrip": false,
|
| 205 |
+
"normalized": false,
|
| 206 |
+
"special": true
|
| 207 |
+
},
|
| 208 |
+
"200021": {
|
| 209 |
+
"content": "<|unused_200021|>",
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"lstrip": false,
|
| 212 |
+
"rstrip": false,
|
| 213 |
+
"normalized": false,
|
| 214 |
+
"special": true
|
| 215 |
+
},
|
| 216 |
+
"200022": {
|
| 217 |
+
"content": "<|content_tool_error|>",
|
| 218 |
+
"single_word": false,
|
| 219 |
+
"lstrip": false,
|
| 220 |
+
"rstrip": false,
|
| 221 |
+
"normalized": false,
|
| 222 |
+
"special": true
|
| 223 |
+
},
|
| 224 |
+
"200023": {
|
| 225 |
+
"content": "<|unused_200023|>",
|
| 226 |
+
"single_word": false,
|
| 227 |
+
"lstrip": false,
|
| 228 |
+
"rstrip": false,
|
| 229 |
+
"normalized": false,
|
| 230 |
+
"special": true
|
| 231 |
+
},
|
| 232 |
+
"200024": {
|
| 233 |
+
"content": "<|content_xml|>",
|
| 234 |
+
"single_word": false,
|
| 235 |
+
"lstrip": false,
|
| 236 |
+
"rstrip": false,
|
| 237 |
+
"normalized": false,
|
| 238 |
+
"special": true
|
| 239 |
+
},
|
| 240 |
+
"200025": {
|
| 241 |
+
"content": "<|unused_200025|>",
|
| 242 |
+
"single_word": false,
|
| 243 |
+
"lstrip": false,
|
| 244 |
+
"rstrip": false,
|
| 245 |
+
"normalized": false,
|
| 246 |
+
"special": true
|
| 247 |
+
},
|
| 248 |
+
"200026": {
|
| 249 |
+
"content": "<|unused_200026|>",
|
| 250 |
+
"single_word": false,
|
| 251 |
+
"lstrip": false,
|
| 252 |
+
"rstrip": false,
|
| 253 |
+
"normalized": false,
|
| 254 |
+
"special": true
|
| 255 |
+
},
|
| 256 |
+
"200027": {
|
| 257 |
+
"content": "<|unused_200027|>",
|
| 258 |
+
"single_word": false,
|
| 259 |
+
"lstrip": false,
|
| 260 |
+
"rstrip": false,
|
| 261 |
+
"normalized": false,
|
| 262 |
+
"special": true
|
| 263 |
+
},
|
| 264 |
+
"200028": {
|
| 265 |
+
"content": "<|begin_of_text|>",
|
| 266 |
+
"single_word": false,
|
| 267 |
+
"lstrip": false,
|
| 268 |
+
"rstrip": false,
|
| 269 |
+
"normalized": false,
|
| 270 |
+
"special": true
|
| 271 |
+
},
|
| 272 |
+
"200029": {
|
| 273 |
+
"content": "<|unused_200029|>",
|
| 274 |
+
"single_word": false,
|
| 275 |
+
"lstrip": false,
|
| 276 |
+
"rstrip": false,
|
| 277 |
+
"normalized": false,
|
| 278 |
+
"special": true
|
| 279 |
+
},
|
| 280 |
+
"200030": {
|
| 281 |
+
"content": "<|unused_200030|>",
|
| 282 |
+
"single_word": false,
|
| 283 |
+
"lstrip": false,
|
| 284 |
+
"rstrip": false,
|
| 285 |
+
"normalized": false,
|
| 286 |
+
"special": true
|
| 287 |
+
},
|
| 288 |
+
"200031": {
|
| 289 |
+
"content": "<|unused_200031|>",
|
| 290 |
+
"single_word": false,
|
| 291 |
+
"lstrip": false,
|
| 292 |
+
"rstrip": false,
|
| 293 |
+
"normalized": false,
|
| 294 |
+
"special": true
|
| 295 |
+
},
|
| 296 |
+
"200032": {
|
| 297 |
+
"content": "<|unused_200032|>",
|
| 298 |
+
"single_word": false,
|
| 299 |
+
"lstrip": false,
|
| 300 |
+
"rstrip": false,
|
| 301 |
+
"normalized": false,
|
| 302 |
+
"special": true
|
| 303 |
+
},
|
| 304 |
+
"200033": {
|
| 305 |
+
"content": "<|unused_200033|>",
|
| 306 |
+
"single_word": false,
|
| 307 |
+
"lstrip": false,
|
| 308 |
+
"rstrip": false,
|
| 309 |
+
"normalized": false,
|
| 310 |
+
"special": true
|
| 311 |
+
},
|
| 312 |
+
"200034": {
|
| 313 |
+
"content": "<|unused_200034|>",
|
| 314 |
+
"single_word": false,
|
| 315 |
+
"lstrip": false,
|
| 316 |
+
"rstrip": false,
|
| 317 |
+
"normalized": false,
|
| 318 |
+
"special": true
|
| 319 |
+
},
|
| 320 |
+
"200035": {
|
| 321 |
+
"content": "<|unused_200035|>",
|
| 322 |
+
"single_word": false,
|
| 323 |
+
"lstrip": false,
|
| 324 |
+
"rstrip": false,
|
| 325 |
+
"normalized": false,
|
| 326 |
+
"special": true
|
| 327 |
+
},
|
| 328 |
+
"200036": {
|
| 329 |
+
"content": "<|unused_200036|>",
|
| 330 |
+
"single_word": false,
|
| 331 |
+
"lstrip": false,
|
| 332 |
+
"rstrip": false,
|
| 333 |
+
"normalized": false,
|
| 334 |
+
"special": true
|
| 335 |
+
},
|
| 336 |
+
"200037": {
|
| 337 |
+
"content": "<|unused_200037|>",
|
| 338 |
+
"single_word": false,
|
| 339 |
+
"lstrip": false,
|
| 340 |
+
"rstrip": false,
|
| 341 |
+
"normalized": false,
|
| 342 |
+
"special": true
|
| 343 |
+
},
|
| 344 |
+
"200038": {
|
| 345 |
+
"content": "<|unused_200038|>",
|
| 346 |
+
"single_word": false,
|
| 347 |
+
"lstrip": false,
|
| 348 |
+
"rstrip": false,
|
| 349 |
+
"normalized": false,
|
| 350 |
+
"special": true
|
| 351 |
+
},
|
| 352 |
+
"200039": {
|
| 353 |
+
"content": "<|unused_200039|>",
|
| 354 |
+
"single_word": false,
|
| 355 |
+
"lstrip": false,
|
| 356 |
+
"rstrip": false,
|
| 357 |
+
"normalized": false,
|
| 358 |
+
"special": true
|
| 359 |
+
},
|
| 360 |
+
"200040": {
|
| 361 |
+
"content": "<|unused_200040|>",
|
| 362 |
+
"single_word": false,
|
| 363 |
+
"lstrip": false,
|
| 364 |
+
"rstrip": false,
|
| 365 |
+
"normalized": false,
|
| 366 |
+
"special": true
|
| 367 |
+
},
|
| 368 |
+
"200041": {
|
| 369 |
+
"content": "<|unused_200041|>",
|
| 370 |
+
"single_word": false,
|
| 371 |
+
"lstrip": false,
|
| 372 |
+
"rstrip": false,
|
| 373 |
+
"normalized": false,
|
| 374 |
+
"special": true
|
| 375 |
+
},
|
| 376 |
+
"200042": {
|
| 377 |
+
"content": "<|unused_200042|>",
|
| 378 |
+
"single_word": false,
|
| 379 |
+
"lstrip": false,
|
| 380 |
+
"rstrip": false,
|
| 381 |
+
"normalized": false,
|
| 382 |
+
"special": true
|
| 383 |
+
},
|
| 384 |
+
"200043": {
|
| 385 |
+
"content": "<|unused_200043|>",
|
| 386 |
+
"single_word": false,
|
| 387 |
+
"lstrip": false,
|
| 388 |
+
"rstrip": false,
|
| 389 |
+
"normalized": false,
|
| 390 |
+
"special": true
|
| 391 |
+
},
|
| 392 |
+
"200044": {
|
| 393 |
+
"content": "<|unused_200044|>",
|
| 394 |
+
"single_word": false,
|
| 395 |
+
"lstrip": false,
|
| 396 |
+
"rstrip": false,
|
| 397 |
+
"normalized": false,
|
| 398 |
+
"special": true
|
| 399 |
+
},
|
| 400 |
+
"200045": {
|
| 401 |
+
"content": "<|unused_200045|>",
|
| 402 |
+
"single_word": false,
|
| 403 |
+
"lstrip": false,
|
| 404 |
+
"rstrip": false,
|
| 405 |
+
"normalized": false,
|
| 406 |
+
"special": true
|
| 407 |
+
},
|
| 408 |
+
"200046": {
|
| 409 |
+
"content": "<|unused_200046|>",
|
| 410 |
+
"single_word": false,
|
| 411 |
+
"lstrip": false,
|
| 412 |
+
"rstrip": false,
|
| 413 |
+
"normalized": false,
|
| 414 |
+
"special": true
|
| 415 |
+
},
|
| 416 |
+
"200047": {
|
| 417 |
+
"content": "<|unused_200047|>",
|
| 418 |
+
"single_word": false,
|
| 419 |
+
"lstrip": false,
|
| 420 |
+
"rstrip": false,
|
| 421 |
+
"normalized": false,
|
| 422 |
+
"special": true
|
| 423 |
+
},
|
| 424 |
+
"200048": {
|
| 425 |
+
"content": "<|unused_200048|>",
|
| 426 |
+
"single_word": false,
|
| 427 |
+
"lstrip": false,
|
| 428 |
+
"rstrip": false,
|
| 429 |
+
"normalized": false,
|
| 430 |
+
"special": true
|
| 431 |
+
},
|
| 432 |
+
"200049": {
|
| 433 |
+
"content": "<|content_invoke_tool_json|>",
|
| 434 |
+
"single_word": false,
|
| 435 |
+
"lstrip": false,
|
| 436 |
+
"rstrip": false,
|
| 437 |
+
"normalized": false,
|
| 438 |
+
"special": true
|
| 439 |
+
},
|
| 440 |
+
"200050": {
|
| 441 |
+
"content": "<|unused_200050|>",
|
| 442 |
+
"single_word": false,
|
| 443 |
+
"lstrip": false,
|
| 444 |
+
"rstrip": false,
|
| 445 |
+
"normalized": false,
|
| 446 |
+
"special": true
|
| 447 |
+
},
|
| 448 |
+
"200051": {
|
| 449 |
+
"content": "<|unused_200051|>",
|
| 450 |
+
"single_word": false,
|
| 451 |
+
"lstrip": false,
|
| 452 |
+
"rstrip": false,
|
| 453 |
+
"normalized": false,
|
| 454 |
+
"special": true
|
| 455 |
+
},
|
| 456 |
+
"200052": {
|
| 457 |
+
"content": "<|unused_200052|>",
|
| 458 |
+
"single_word": false,
|
| 459 |
+
"lstrip": false,
|
| 460 |
+
"rstrip": false,
|
| 461 |
+
"normalized": false,
|
| 462 |
+
"special": true
|
| 463 |
+
},
|
| 464 |
+
"200053": {
|
| 465 |
+
"content": "<|unused_200053|>",
|
| 466 |
+
"single_word": false,
|
| 467 |
+
"lstrip": false,
|
| 468 |
+
"rstrip": false,
|
| 469 |
+
"normalized": false,
|
| 470 |
+
"special": true
|
| 471 |
+
},
|
| 472 |
+
"200054": {
|
| 473 |
+
"content": "<|unused_200054|>",
|
| 474 |
+
"single_word": false,
|
| 475 |
+
"lstrip": false,
|
| 476 |
+
"rstrip": false,
|
| 477 |
+
"normalized": false,
|
| 478 |
+
"special": true
|
| 479 |
+
},
|
| 480 |
+
"200055": {
|
| 481 |
+
"content": "<|unused_200055|>",
|
| 482 |
+
"single_word": false,
|
| 483 |
+
"lstrip": false,
|
| 484 |
+
"rstrip": false,
|
| 485 |
+
"normalized": false,
|
| 486 |
+
"special": true
|
| 487 |
+
},
|
| 488 |
+
"200056": {
|
| 489 |
+
"content": "<|unused_200056|>",
|
| 490 |
+
"single_word": false,
|
| 491 |
+
"lstrip": false,
|
| 492 |
+
"rstrip": false,
|
| 493 |
+
"normalized": false,
|
| 494 |
+
"special": true
|
| 495 |
+
},
|
| 496 |
+
"200057": {
|
| 497 |
+
"content": "<|content_invoke_tool_text|>",
|
| 498 |
+
"single_word": false,
|
| 499 |
+
"lstrip": false,
|
| 500 |
+
"rstrip": false,
|
| 501 |
+
"normalized": false,
|
| 502 |
+
"special": true
|
| 503 |
+
}
|
| 504 |
+
},
|
| 505 |
+
"response_template": {
|
| 506 |
+
"defaults": {
|
| 507 |
+
"role": "assistant"
|
| 508 |
+
},
|
| 509 |
+
"start_anchor_pattern": "<\\|end_message\\|>|<\\|content_model_end_sampling\\|>",
|
| 510 |
+
"fields": {
|
| 511 |
+
"reasoning_content": {
|
| 512 |
+
"open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_thinking\\|>",
|
| 513 |
+
"close": "<|end_message|>",
|
| 514 |
+
"repeats": true,
|
| 515 |
+
"join": "",
|
| 516 |
+
"content": "text",
|
| 517 |
+
"content_args": {
|
| 518 |
+
"strip": false
|
| 519 |
+
}
|
| 520 |
+
},
|
| 521 |
+
"content": {
|
| 522 |
+
"open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_(?:text|tool_error|invoke_tool_text)\\|>",
|
| 523 |
+
"close": "<|end_message|>",
|
| 524 |
+
"repeats": true,
|
| 525 |
+
"join": "",
|
| 526 |
+
"content": "text",
|
| 527 |
+
"content_args": {
|
| 528 |
+
"strip": false
|
| 529 |
+
}
|
| 530 |
+
},
|
| 531 |
+
"tool_calls": {
|
| 532 |
+
"open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_invoke_tool_json\\|>",
|
| 533 |
+
"close": "<|end_message|>",
|
| 534 |
+
"repeats": true,
|
| 535 |
+
"content": "json",
|
| 536 |
+
"transform": {
|
| 537 |
+
"type": "function",
|
| 538 |
+
"function": {
|
| 539 |
+
"name": "{content.name}",
|
| 540 |
+
"arguments": "{content.args}"
|
| 541 |
+
}
|
| 542 |
+
}
|
| 543 |
+
}
|
| 544 |
+
}
|
| 545 |
+
},
|
| 546 |
+
"eos_token": "<|content_model_end_sampling|>",
|
| 547 |
+
"pad_token": "<|endoftext|>"
|
| 548 |
+
}
|