NanoTeX-3B-128k

Offline 128K-Context LaTeX AI Model & Local Inference Engine for CPU Laptops โ€” No GPU Required

Built with Qwen โ€” Improved using Qwen (Qwen/Qwen2.5-Coder-3B-Instruct)

Open In Colab License: Qwen Research Base Model Context Window Held-Out Accuracy Overall Accuracy Multi-File Formats


NanoTeX-3B-128k is a specialized LaTeX, scientific writing, math proof, TikZ/PGFPlots, Beamer, BibTeX, and multi-file repository LLM and verified inference stack engineered from Qwen/Qwen2.5-Coder-3B-Instruct to run 100% locally on consumer CPU laptops without cloud APIs or GPU hardware.

At-a-Glance Highlights

Metric Verified Result Notes
Held-Out LaTeX Accuracy 93.8% +31.3 pp gain over untouched base (62.5%)
Overall LaTeX Accuracy 87.5% FullStack (+27.5 pp over base 60.0%); PureLLM 85.0%
Multi-File Projects & Tables 100.0% Across Dev, Held-Out Test, and Unseen Hard suites
Repetition Loop Rate 0.0% Reduced from base loops to zero on PureLLM & FullStack
24K Workspace Retrieval 100.0% 60.0 MB peak KV cache with 1,712.8 MB min free RAM
24K KV Compression 11.30x 57.0 MB KV cache via 3-Tier Query-Aware PyramidKV + YaRN
Base Perplexity Preservation +0.066% delta 3.4923 -> 3.4946 FP32 PPL (2.1917% parameters modified)
Deployment 100% Offline Zero API cost ($0); OpenAI-compatible HTTP server & CLI included

Try it for Free on T4 GPU: Launch the 1-click Google Colab Gradio Demo (NanoTeX_3B_128k_Colab_Demo.ipynb) or run the simple Prompt -> Output Gradio UI locally with python runtime/gradio_app.py.

Modification Notice (Qwen Research License Compliance): This derivative release modifies 67,633,152 of 3,085,938,688 total parameters (2.1917%) in Qwen/Qwen2.5-Coder-3B-Instruct via surgical Weight-Space Programming (L1_mit_antiloop):

  • model.layers.25.mlp.down_proj.weight
  • model.layers.26.mlp.down_proj.weight
  • model.layers.27.mlp.down_proj.weight

Full parameter delta and audit metrics are included in wsp/wsp_edit_report.json, LICENSE, and NOTICE.


How It Was Built โ€” Techniques & Architecture

NanoTeX-3B-128k was engineered entirely on a consumer laptop CPU with zero backpropagation or cloud GPU fine-tuning, combining six composable optimization and verification layers:

flowchart LR
    A["Qwen2.5-Coder-3B-Instruct"] --> B["WSP Weight Steering\n(L25-L27 mlp.down_proj, 2.1917%)"]
    B --> C["Mixed-Precision INT4 ONNX\n+ Zero-Copy model_pyramid.onnx"]
    C --> D["128K YaRN RoPE +\n3-Tier Query-Aware PyramidKV"]
    D --> E["Multi-File Workspace Indexer\n+ Tier-0B Recap Tail"]
    E --> F["16-Gram Anti-Loop Guard +\nSurgical Self-Repair (<= 2 rounds)"]
    F --> G["Verified LaTeX Output\n& OpenAI Local Server / CLI"]
  1. Zero-Gradient Weight-Space Programming (WSP L1_mit_antiloop): Targeted contrastive steering on late MLP down-projections (layers 25โ€“27, only 2.1917% of model weights) eliminates degenerate LaTeX repetition loops while keeping untouched attention heads and general language perplexity (3.4923 -> 3.4946, +0.066%) virtually unchanged.
  2. Mixed-Precision Weight-Only INT4 ONNX + Zero-Copy Pyramid Graph: Exported to 2.80 GB INT4 weights while preserving 8-bit precision on sensitive projections (L0 and L1 gate_proj plus all mlp.down_proj), then structurally mutated into onnx/model_pyramid.onnx sharing model.onnx.data with zero duplicate weight storage.
  3. 128K YaRN NTK-by-Parts RoPE + 3-Tier Query-Aware PyramidKV: Extends effective context to 131,072 tokens using 512-token chunked prefill and independent per-tier KV budgets (Low L0..L11: 2048, Mid L12..L23: 1280, High L24..L35: 768), retaining attention sinks, structural LaTeX definitions (\newcommand, \label, \bibitem), and query-matched observation windows at up to 11.30x KV compression (57.0โ€“60.0 MB at 24K).
  4. Multi-File LaTeX Workspace Indexer & Tier-0B Recap: Indexes cross-file \label, \ref, \eqref, \cite, \input, \include, custom macros, and .bib keys, pinning a compact query-matched recap inside the zero-eviction recent token tail (384 tokens).
  5. 16-Gram Anti-Loop Guard & Monotonic Surgical Self-Repair (max_repairs=2): Combines 16-gram cycle blocking, 4-identical-line termination, line-numbered pdflatex-style static diagnostics, source-preservation constraints, and conservative Levenshtein or unique-prefix repair for misspelled \ref/\cite keys.
  6. Drop-In OpenAI-Compatible Local Server & CLI (runtime/prism/): Ready-to-run HTTP endpoints (/health, /v1/models, /v1/chat/completions) plus structured JSON CLI output (valid, repairs, KV telemetry) with strict RAM and thread safety watchdogs.

Verified Benchmark Results

All benchmarks below were executed offline on consumer CPU hardware and scored with the unchanged evaluate_latex_task verifier (0 relaxed assertions). Every score is reported as an exact pass rate percentage.

1. Head-to-Head: Base Model (Qwen2.5-Coder-3B-Instruct) vs. NanoTeX-3B-128k

Evaluation Suite / Metric Untouched Base (base_int4) NanoTeX-3B-128k (FullStack) Improvement (Base -> NanoTeX)
latex_dev Suite 58.3% 91.7% +33.4 pp
latex_test Held-Out Suite 62.5% 93.8% +31.3 pp
latex_hard_eval Stress Suite 58.3% 75.0% (66.7% PureLLM) +16.7 pp
Overall Combined Accuracy 60.0% 87.5% (85.0% PureLLM) +27.5 pp
Multi-File Projects (multifile) 40.0% 100.0% +60.0 pp
Tables (table) 85.7% 100.0% +14.3 pp
Infinite Repetition Loop Rate 5.0% 0.0% (PureLLM & FullStack) Eliminated (-5.0 pp)
Long-Context Retrieval (NIAH + Workspace) 44.4% 77.8% (100.0% Workspace) +33.4 pp
FP32 Perplexity (510 tokens) 3.4923 3.4946 +0.066% (preserved)

2. Per-Suite & Per-Category Accuracy Breakdown

Suite Category Untouched Base NanoTeX-3B-128k (PureLLM) NanoTeX-3B-128k (FullStack)
latex_dev math_proof 33.3% 66.7% 66.7%
latex_dev table 100.0% 100.0% 100.0%
latex_dev tikz 50.0% 100.0% 100.0%
latex_dev error_fix 66.7% 100.0% 100.0%
latex_dev multifile 50.0% 100.0% 100.0%
latex_dev Total All Categories 58.3% 91.7% 91.7%
latex_test (Held-Out) math_proof 25.0% 75.0% 75.0%
latex_test (Held-Out) table 100.0% 100.0% 100.0%
latex_test (Held-Out) tikz 100.0% 100.0% 100.0%
latex_test (Held-Out) error_fix 66.7% 100.0% 100.0%
latex_test (Held-Out) multifile 0.0% 100.0% 100.0%
latex_test (Held-Out) long_form 100.0% 100.0% 100.0%
latex_test Total All Categories 62.5% 93.8% 93.8%
latex_hard_eval (Unseen) algorithm 100.0% 100.0% 100.0%
latex_hard_eval (Unseen) composite 100.0% 100.0% 100.0%
latex_hard_eval (Unseen) error_fix 0.0% 50.0% 50.0%
latex_hard_eval (Unseen) math_proof 50.0% 50.0% 50.0%
latex_hard_eval (Unseen) minimal_edit 100.0% 100.0% 100.0%
latex_hard_eval (Unseen) multifile 100.0% 100.0% 100.0%
latex_hard_eval (Unseen) table 50.0% 50.0% 100.0%
latex_hard_eval (Unseen) tikz 50.0% 50.0% 50.0%
latex_hard_eval Total All Categories 58.3% 66.7% 75.0%
Combined Overall Total All 3 Suites 60.0% 85.0% 87.5%

Deterministic Auto-Fix Save: On lhard_table_01, PureLLM hit an 8-column row vs. 6-column header spec (lccccr), and auto_fix_safe_latex deterministically expanded the spec ('lccccr' -> 'lccccrrr') to pass under FullStack.

Remaining 12.5% Edge-Case Breakdown (Formatting-Preference Differences, Zero Syntax Crashes)

None of the remaining misses involve broken braces, missing packages, broken cross-file keys, or repetition loops โ€” all five are strict environment or option style preferences:

Task ID Suite Category Verifier Reason Observed Root Cause
ldev_math_01 latex_dev math_proof missing_pattern: \begin{align Valid lemma + proof with \label{lem:cauchy_schwarz}, used \[...\] instead of \begin{align*}.
ltest_math_01 latex_test math_proof missing_pattern: \begin{align Valid syntax and \label{thm:triangle} after repair, used \[...\] instead of \begin{align*}.
lhard_math_01 latex_hard_eval math_proof missing_pattern: \begin{cases} Valid KKT conditions formatted with \begin{align} + \tag{...} instead of \begin{cases}.
lhard_tikz_01 latex_hard_eval tikz missing_pattern: \legend Placed legend={Baseline,Prism-v2} as an axis option instead of \legend{Baseline,Prism-v2}.
lhard_fix_02 latex_hard_eval error_fix missing_pattern: \begin{tabular}{lcc Expanded {lc} column spec to {ccc} instead of {lcc}.

3. Long-Context Compressed Memory & Latency Telemetry

Benchmark Prompt Tokens YaRN Active Peak KV Cache KV Compression Accuracy Prefill & Decode Min Free RAM
Short-Context Parity (model_pyramid vs model) 29 False 1.62 MB 0.63x 100.0% Match 2.57s (5.71 tok/s) 1692.4 MB
niah_8000 5,812 False 57.0 MB 4.07x 66.7% 208.84s (1.89 tok/s) 1412.0 MB
niah_24000 16,102 True 57.0 MB 11.30x 66.7% 530.40s (2.23 tok/s) 1469.5 MB
prism_workspace_24000 2,063 False 60.0 MB 1.44x 100.0% 64.07s (2.16 tok/s) 1712.8 MB
Evaluation Run Total Wall Time Average Decode Speed Minimum Free Physical RAM (450 MB floor)
nanotex_dev.json 2020.8s 1.91 tok/s 1542.6 MB
nanotex_test.json 2247.8s 2.70 tok/s 2360.1 MB
nanotex_hard.json 2565.6s 2.01 tok/s 1563.9 MB
  • Unit & Live End-to-End Verification: test_prism_v2.py (100.0% pass rate across all test groups), CLI --json (valid=true, peak_kv_mb=32.91), and OpenAI-compatible HTTP server (GET /health 200, GET /v1/models returning id="NanoTeX-3B-128k", POST /v1/chat/completions 200 with prism_validation.valid=true).

Use Cases

  • Offline Academic Writing & Grants: Draft sections, lemmas, proofs, equations, and booktabs tables locally without uploading unpublished research to cloud APIs.
  • Multi-File Thesis, Book & Paper Repositories: Maintain consistent \label, \ref, \eqref, \cite, .bib keys, and custom macros across \input{...} and \include{...} trees at up to 128K context.
  • Diagrams & Presentations: Generate TikZ, PGFPlots, algorithm2e, and Beamer slides with automated environment and delimiter checks.
  • Automated LaTeX Bug Repair: Fix unmatched braces, unclosed math delimiters, mismatched tabular columns, unwrapped axis blocks, and missing semicolons.
  • Drop-In Editor Backend: Point VS Code, Vim/Neovim, or local LaTeX scripts at http://127.0.0.1:8080/v1 (model: NanoTeX-3B-128k).

Pros & Cons

Pros

  • High Specialist Accuracy at 3B CPU Scale: Lifts overall accuracy from 60.0% (base_int4) to 87.5% (93.8% held-out) with 0.0% repetition loops and 100.0% on multi-file and table benchmarks.
  • Runs on Standard CPU Laptops: 2.80 GB ONNX INT4 weights + 57โ€“60 MB PyramidKV cache keep 24K workspace inference inside consumer laptop memory (>= 1,412 MB free RAM headroom).
  • Complete Self-Contained Release: Ships FP16 Hugging Face SafeTensors, ONNX INT4 PyramidKV graphs, exact WSP weight delta (wsp/wsp_delta.safetensors), and full verification/server source (runtime/).
  • 100% Private & Free to Run: Zero API fees ($0), offline execution, and 1-click Free T4 GPU Gradio Demo on Google Colab.

Cons & Limitations

  • Non-Commercial Research License Only: Governed by the Qwen Research License Agreement (no commercial production deployment without separate authorization from Alibaba Cloud).
  • CPU Inference Latency: Laptop CPU generation runs at ~1.91โ€“2.70 tok/s (64.07s prefill at 24K workspace context); multi-round repair prioritizes correctness over instant streaming.
  • Static Verification Scope: Verifier validates LaTeX syntax, structure, packages, and cross-file references deterministically without compiling PDFs; pair with pdflatex or latexmk for pixel-level layout inspection.
  • Relies on Runtime Stack for Peak Accuracy: Without QLoRA fine-tuning, Pass-0 raw generation matches base pass rate (60.0%); the jump to 85.0%โ€“87.5% comes from pairing WSP-steered weights with the PrismAgentV2 verification and self-repair stack.

Quick Start

1. Simple Prompt & Output Gradio Demo (Free Colab T4 GPU or Local)

  • 1-Click Google Colab Gradio UI (Free T4 GPU): Open In Colab
  • Local CPU Gradio UI (runtime/gradio_app.py):
    pip install -r runtime/requirements.txt gradio
    python runtime/gradio_app.py
    

2. PyTorch & transformers (FP16 Hugging Face Weights)

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "anjomj/NanoTeX-3B-128k"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto",
)

messages = [
    {"role": "system", "content": "You are NanoTeX-3B-128k, a precise LaTeX assistant."},
    {"role": "user", "content": "Write a clean booktabs table comparing precision, recall, and F1."},
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=512, do_sample=False)
print(tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True))

3. Local ONNX INT4 + 128K PyramidKV CLI & OpenAI Server (runtime/)

pip install -r runtime/requirements.txt

# One-shot LaTeX generation with structural verification JSON
python runtime/prism/prism_cli.py \
  --model-dir ./onnx \
  --prompt "Write an align* derivation of Bayes' theorem." \
  --json

# Start local OpenAI-compatible server (/health, /v1/models, /v1/chat/completions)
python runtime/prism/prism_server.py --model-dir ./onnx --port 8080

Hardware Requirements & Repository Layout

  • ONNX INT4 + PyramidKV (onnx/): x86_64 or ARM64 CPU, 8 GB+ system RAM recommended (~3.0 GB disk for onnx/ + runtime/).
  • FP16 SafeTensors (*.safetensors): ~6.0 GB weights (~8.76 GB full repo), >= 8 GB GPU VRAM or 16 GB+ system RAM for FP16 loading.
Click to expand full repository structure
.
โ”œโ”€โ”€ config.json / generation_config.json / tokenizer*.json / vocab.json / merges.txt
โ”œโ”€โ”€ model-00001-of-00007.safetensors ... model-00007-of-00007.safetensors   # FP16 HF weights (WSP applied)
โ”œโ”€โ”€ model.safetensors.index.json
โ”œโ”€โ”€ release_manifest.json                                                  # Full verified metrics & metadata
โ”œโ”€โ”€ LICENSE                                                                # Qwen Research License Agreement
โ”œโ”€โ”€ NOTICE                                                                 # Required attribution notice
โ”œโ”€โ”€ README.md                                                              # This model card
โ”œโ”€โ”€ NanoTeX_3B_128k_Colab_Demo.ipynb                                       # Free T4 GPU Gradio Prompt -> Output notebook
โ”œโ”€โ”€ wsp/
โ”‚   โ”œโ”€โ”€ wsp_delta.safetensors                                              # Exact L25-L27 mlp.down_proj delta (258 MB)
โ”‚   โ””โ”€โ”€ wsp_edit_report.json                                               # Parameter & PPL audit
โ”œโ”€โ”€ onnx/
โ”‚   โ”œโ”€โ”€ model.onnx / model_pyramid.onnx / model.onnx.data                  # Mixed-precision INT4 ONNX graphs (2.80 GB)
โ”‚   โ”œโ”€โ”€ int4_meta.json / tensor_offsets.json
โ”‚   โ””โ”€โ”€ config.json / generation_config.json / tokenizer*.json
โ””โ”€โ”€ runtime/
    โ”œโ”€โ”€ prism/                                                             # CLI, OpenAI server, 128K PyramidKV engine, verifier, workspace, RAG
    โ”œโ”€โ”€ gradio_app.py                                                      # Local or PRO Gradio Studio UI
    โ”œโ”€โ”€ src/safety.py                                                      # Cross-platform RAM & CPU thread guardrails
    โ”œโ”€โ”€ bench/latex_eval_runner.py                                         # Verification & benchmark harness
    โ”œโ”€โ”€ run_nanotex.ps1                                                    # Windows launcher
    โ””โ”€โ”€ requirements.txt

License & Attribution

BibTeX Citation
@misc{nanotex3b128k2026,
  title={NanoTeX-3B-128k: Zero-Gradient Weight Steering and 128K PyramidKV Verified LaTeX Inference for Consumer CPUs},
  author={anjomj},
  year={2026},
  howpublished={\url{https://huggingface.co/anjomj/NanoTeX-3B-128k}},
  note={Built with Qwen (derived from Qwen/Qwen2.5-Coder-3B-Instruct under the Qwen Research License Agreement)}
}
Downloads last month
-
Safetensors
Model size
3B params
Tensor type
BF16
ยท
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Model tree for anjomj/NanoTeX-3B-128k

Base model

Qwen/Qwen2.5-3B
Quantized
(160)
this model