Instructions to use anjomj/NanoTeX-3B-128k with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use anjomj/NanoTeX-3B-128k with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="anjomj/NanoTeX-3B-128k") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("anjomj/NanoTeX-3B-128k") model = AutoModelForCausalLM.from_pretrained("anjomj/NanoTeX-3B-128k", device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use anjomj/NanoTeX-3B-128k with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "anjomj/NanoTeX-3B-128k" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "anjomj/NanoTeX-3B-128k", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/anjomj/NanoTeX-3B-128k
- SGLang
How to use anjomj/NanoTeX-3B-128k 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 "anjomj/NanoTeX-3B-128k" \ --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": "anjomj/NanoTeX-3B-128k", "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 "anjomj/NanoTeX-3B-128k" \ --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": "anjomj/NanoTeX-3B-128k", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use anjomj/NanoTeX-3B-128k with Docker Model Runner:
docker model run hf.co/anjomj/NanoTeX-3B-128k
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)
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 withpython 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%) inQwen/Qwen2.5-Coder-3B-Instructvia surgical Weight-Space Programming (L1_mit_antiloop):
model.layers.25.mlp.down_proj.weightmodel.layers.26.mlp.down_proj.weightmodel.layers.27.mlp.down_proj.weightFull parameter delta and audit metrics are included in
wsp/wsp_edit_report.json,LICENSE, andNOTICE.
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"]
- Zero-Gradient Weight-Space Programming (
WSP L1_mit_antiloop): Targeted contrastive steering on late MLP down-projections (layers 25โ27, only2.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. - Mixed-Precision Weight-Only INT4 ONNX + Zero-Copy Pyramid Graph: Exported to
2.80 GBINT4 weights while preserving 8-bit precision on sensitive projections (L0andL1gate_projplus allmlp.down_proj), then structurally mutated intoonnx/model_pyramid.onnxsharingmodel.onnx.datawith zero duplicate weight storage. - 128K YaRN NTK-by-Parts RoPE + 3-Tier Query-Aware PyramidKV: Extends effective context to
131,072tokens 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 to11.30xKV compression (57.0โ60.0 MBat 24K). - Multi-File LaTeX Workspace Indexer & Tier-0B Recap: Indexes cross-file
\label,\ref,\eqref,\cite,\input,\include, custom macros, and.bibkeys, pinning a compact query-matched recap inside the zero-eviction recent token tail (384tokens). - 16-Gram Anti-Loop Guard & Monotonic Surgical Self-Repair (
max_repairs=2): Combines 16-gram cycle blocking, 4-identical-line termination, line-numberedpdflatex-style static diagnostics, source-preservation constraints, and conservative Levenshtein or unique-prefix repair for misspelled\ref/\citekeys. - 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 /health200,GET /v1/modelsreturningid="NanoTeX-3B-128k",POST /v1/chat/completions200withprism_validation.valid=true).
Use Cases
- Offline Academic Writing & Grants: Draft sections, lemmas, proofs, equations, and
booktabstables locally without uploading unpublished research to cloud APIs. - Multi-File Thesis, Book & Paper Repositories: Maintain consistent
\label,\ref,\eqref,\cite,.bibkeys, and custom macros across\input{...}and\include{...}trees at up to 128K context. - Diagrams & Presentations: Generate
TikZ,PGFPlots,algorithm2e, andBeamerslides with automated environment and delimiter checks. - Automated LaTeX Bug Repair: Fix unmatched braces, unclosed math delimiters, mismatched tabular columns, unwrapped
axisblocks, 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) to87.5%(93.8%held-out) with0.0%repetition loops and100.0%on multi-file and table benchmarks. - Runs on Standard CPU Laptops:
2.80 GBONNX INT4 weights +57โ60 MBPyramidKV cache keep 24K workspace inference inside consumer laptop memory (>= 1,412 MBfree 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.07sprefill 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
pdflatexorlatexmkfor pixel-level layout inspection. - Relies on Runtime Stack for Peak Accuracy: Without QLoRA fine-tuning,
Pass-0raw generation matches base pass rate (60.0%); the jump to85.0%โ87.5%comes from pairing WSP-steered weights with thePrismAgentV2verification 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):
- 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 GBdisk foronnx/+runtime/). - FP16 SafeTensors (
*.safetensors):~6.0 GBweights (~8.76 GBfull repo),>= 8 GBGPU VRAM or16 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
- License: Qwen RESEARCH LICENSE AGREEMENT (Non-Commercial Research Use Only; Copyright (c) Alibaba Cloud).
- Mandatory Attribution:
Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved.(seeNOTICE). - Base Model:
Qwen/Qwen2.5-Coder-3B-Instruct.
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
- -