Skip to main content
Acorn Framework Logo

🌰 Acorn Framework

Big models. Tiny footprint. —— 芥子纳须弥,把大模型装进口袋。

PyPI Python Deps License Tests

以小搏大的 AI 运行与训练框架:INT4 压缩态常驻 + 原生 AVX2 内核 + KV int8 + 层流式 + 投机解码 + LoRA + AutoBit + 能效治理,零依赖核心,全部自研。


⚡ 60 秒看到它跑真模型

pip install acorn-llm          # 零依赖;有 gcc 会自动编译 AVX2 内核
acorn chat                     # ← 打开本地 AI 聊天 TUI
============================================================
  Acorn 本地聊天室 | Qwen3-8B | eco=whisper | CPU
  /exit 退出 · /new 新对话 · /eco 切档 · /spec 投机 · /raw 渲染开关
============================================================

你> 1+1等于几?

AI> thinking...
    嗯,用户问的是 1+1 等于几。这是最基础的算术……

    think done

    1+1 等于 2。这是整数加法的基本运算……

实测数据(本机:16 核 CPU / 16.5GB RAM / 无 GPU / 一块 P620)

模型 原始体积 Acorn INT4 常驻内存 decode 备注
Qwen3-8B 16.38 GB (bf16) 4.10 GB (7.99×) 4.10 GB 2.4–3.1 tok/s 36 层/32 头/8 KV,纯 CPU 跑通中文思维链
Qwen2.5-0.5B 0.99 GB 0.25 GB (4×) 0.25 GB 10–15.7 tok/s 静音档 2 线程仍同速
7B 规格(合成) 18.5 GB (fp32) 2.91 GB 154 MB(层流式) 4.7 tok/s 省内存 19×
int4 GEMV (4096×11008) 12.3 ms (fp32 BLAS) 1.95 ms 0.5 B/参数 18.6 GB/s 自研 AVX2,机器带宽上限的 72%

🧠 这个框架到底做了什么(不是 PPT,全部实测)

能力 实现 实测/验证
INT4 压缩态常驻 权重以 int4 留在内存,推理时在线解包参与 GEMM,绝不物化 fp 矩阵 7.99× 压缩;数值与参考实现 rel=1.5e-7
原生 AVX2 内核 C 手写:nibble 在线解包 + 256-bit FMA 点积 + 常驻线程池 比 fp32 BLAS 快 6.3×;18.6 GB/s(硬件上限 26 GB/s 的 72%)
真实模型接入 零依赖 safetensors 读写(单文件/多分片)、LLaMA/Qwen2/Qwen3 架构、BPE 分词器 Qwen3-8B 实跑,中文思维链正确
AutoBit 混合位宽 逐层 KL 敏感度实测 → 字节预算下贪心分配 int4/int8/fp32 同预算质量 KL ↓87%
投机解码 n-gram 草稿 + 批量验证 + cache 回退 ×1.3–1.7,且与常规贪心输出逐字一致(金标准)
KV Cache int8 逐 token absmax 量化 内存 28%,输出偏差 0.4%
层流式加载 按层惰性读取 + LRU 驱逐 7B 常驻 154 MB(4GB 内存设备可跑)
结构化剪枝 + 稀疏内核 FFN 神经元幅度剪枝 + 位图跳零 + 紧凑存储 50% 剪枝:字节 50%、加速 ×1.6、loss 仅 ×1.08
LoRA 轻训练 冻结基座 + 低秩适配器 + 合并回稠密 25.3% 参数学新语料
能效治理 (eco) whisper/balanced/turbo + race-to-idle + 进程优先级 2 线程与 16 线程同速,CPU 时间更少 → 风扇不转
CUDA Graph 后端 自研 GPU 解码图(捕获+回放) 数值正确;P620 上仍不及 CPU int4 内核(诚实数据)

📦 安装

pip install acorn-llm              # 零依赖核心(推荐)
pip install acorn-llm[fast]        # + NumPy(BLAS + 向量化,约 50× 提速)
pip install acorn-llm[gpu]         # + PyTorch(CUDA Graph 后端)

要求 Python ≥ 3.9。有 gcc/cl 时首次运行自动编译原生内核(缓存到 ~/.cache/acorn);没有编译器也不影响使用(自动回退 NumPy 路径,功能一致、速度较低)。


💬 TUI 聊天(装完就能用)

acorn chat                                  # 自动搜索本地模型
acorn chat --model-dir ./models/Qwen3-8B    # 指定模型目录
acorn chat --model-dir ./qwen --auto-convert  # 目录里是 safetensors 就地转换
acorn chat --system "你是一个简洁的技术助手"   # 设定人设
acorn chat --gpu                            # 用 CUDA 后端(若有)
acorn chat --eco turbo                      # 全速(风扇起飞)

模型从哪来?(三种方式)

① 直接下载已转换的模型? —— 没有官方分发,但转换只需一次(10 分钟内完成)。

② 从 ModelScope / HuggingFace 下载原始权重 → 自动转换(推荐)

# ModelScope(国内直连,无需梯子)
mkdir -p models/Qwen2.5-0.5B
curl -L -o models/Qwen2.5-0.5B/model.safetensors \
  "https://modelscope.cn/api/v1/models/Qwen/Qwen2.5-0.5B-Instruct/repo?FilePath=model.safetensors"
curl -L -o models/Qwen2.5-0.5B/tokenizer.json \
  "https://modelscope.cn/api/v1/models/Qwen/Qwen2.5-0.5B-Instruct/repo?FilePath=tokenizer.json"
curl -L -o models/Qwen2.5-0.5B/config.json \
  "https://modelscope.cn/api/v1/models/Qwen/Qwen2.5-0.5B-Instruct/repo?FilePath=config.json"

# 然后二选一:
acorn chat --model-dir models/Qwen2.5-0.5B --auto-convert   # 自动转 + 直接聊

手动转换(可复用、参数自动读 config.json,rope_theta 等超参不会手填错):

python -m acorn convert --src models/Qwen2.5-0.5B/model.safetensors \
                        --out models/Qwen2.5-0.5B/qwen.acorn

自动从 config.json 读取:层数 / 维度 / 头数 / KV 头 / FFN / 词表 / rope_theta(Qwen2/3 是 1e6!)/ tie_word_embeddings / qk_norm(Qwen3)。 转换是流式的:RAM 峰值 ≈ 单个张量,16GB 内存机器可转 16GB 模型(多分片自动走流式路径)。

HuggingFace 同理,把 URL 换成 https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct/resolve/main/...。

③ 已有的第三方 .acorn / GGUF? —— GGUF 暂不支持,请先用 acorn convert(支持 safetensors 系)。

模型目录长什么样

models/Qwen2.5-0.5B/
├── model.safetensors     # 原始权重(可选,--auto-convert 用)
├── config.json           # HF 配置(--auto-convert / convert 自动读它)
├── tokenizer.json        # 必需
└── qwen.acorn            # 转换产物(必需,或由 --auto-convert 生成)

该下载哪个模型?(已验证可跑)

模型 规格 下载量 Acorn INT4 后 速度(实测) 备注
Qwen2.5-0.5B-Instruct 0.49B · 24L · d896 · 14Q/2KV 0.99 GB 0.25 GB 14–16 tok/s 首选,秒级响应
Qwen2.5-1.5B-Instruct 1.54B · 28L · d1536 3.1 GB ~0.8 GB ~7 tok/s 中文更好
Qwen3-8B 8.2B · 36L · d4096 · 32Q/8KV · QK-Norm 16.4 GB 4.10 GB 2.4–3.1 tok/s 思维链最强,本机 16GB 可跑
Qwen3-1.7B 1.7B · 28L · d2048 3.4 GB ~0.9 GB ~6 tok/s 质量/体积最佳平衡

Qwen3 用 QK-Norm 架构,Acorn 已支持(数值 vs 独立参考实现 rel=3.8e-7); Qwen2/3 的 rope_theta=1e6 会在转换时自动从 config.json 读取(手填 10000 会得到乱码)。

TUI 里的命令

命令 作用
/new 开新对话(清空上下文与 KV)
/eco whisper|balanced|turbo 能效档位:静音 / 甜点 / 全速
/spec 投机解码开关(重复文本/代码可提速)
/raw 关闭 Markdown 渲染(看原始输出)
/info 当前档位、线程数、轮次、上下文长度
/exit 退出

界面说明

  • 思考流:模型的 thinking 内容以深灰逐字显示,头部 thinking...,结束切 think done
  • 正文:正常色逐字符流式,标题/列表/代码块自动着色(Markdown)
  • 跨轮复用 KV:每轮只前向增量,历史不重算

🧪 30 秒训一个自己的模型

import acorn

model = acorn.train(corpus=open("my_novel.txt", encoding="utf-8").read(),
                    steps=300, batch_size=12, ctx=64)
acorn.pack(model, "mymodel.acorn")     # INT4 打包
m = acorn.load("mymodel.acorn")
print(m.generate("第一章", 200, temperature=0.8))

训练栈全是自研:矩阵级 autograd(13 个可微节点)· AdamW · warmup + 余弦调度 · 全局范数梯度裁剪 · 数值对拍测试(44+9 位置有限差分)。

LoRA 轻量微调

import acorn
from acorn import lora

model = acorn.train(steps=100)
lora.inject_lora(model, rank=8)          # 冻结基座 + 注入低秩适配器
acorn.train(model=model, corpus="新领域文本…", steps=60)
lora.merge_lora(model)                   # 合并回稠密权重
acorn.pack(model, "tuned.acorn")

真实模型微调(诚实说明)

  • 0.5B 级:本机可行(acorn.to_trainable(acorn.load(...)) → LoRA 流程同上)
  • 8B 级:fp32 反量化需 32GB 内存,本机不可行;且 LLaMA 路径目前是数值推理路径,尚未接入 autograd 图——这是路线图 M2 项

🖥️ CLI 全表

acorn chat                             # ★ 交互式 TUI 聊天
acorn train  --steps 200 --out m.acorn # 训练 + INT4 打包
acorn run    --model m.acorn --stream  # TinyGPT 推理
acorn convert --src X.safetensors --out X.acorn   # 真实模型转换(自动读 config.json)
acorn run-llama --model X.acorn --tokenizer tok.json --prompt "你好" --stream
acorn bench  --model m.acorn           # 基准(吞吐/带宽/规模外推/内核状态)
acorn lora   --model m.acorn --corpus my.txt --steps 150   # LoRA 微调

🧰 Python API 速查

API 用途
acorn.train(steps=, corpus=, lr=, batch_size=, ctx=) 训练
acorn.pack(model, path) INT4 量化打包(投影融合 + 嵌入表 gather 布局)
acorn.load(path, tokenizer_path=, kv_cache_kind="int8", ctx=, eco=, device=) 加载(自动按架构分派)
m.generate_chat(prompt, …, repetition=, speculative=) 对话式生成(自动模板 + 重复惩罚 + 停止序列)
m.generate_stream(...) / m.generate(...) 生成(token 级流式)
ChatSession(m).send(text) 多轮对话(跨轮 KV 复用)
m.set_eco("whisper") 能效档位切换
acorn.load_streaming(path, max_resident_layers=2) 层流式加载(内存省 19×)
acorn.bench(m) 性能基准
acorn.autobit / acorn.prune 混合位宽量化 / 结构化剪枝
acorn.llama.convert_safetensors(...) / acorn.shard.convert_sharded(...) 真实模型转换器
acorn._kernels.info() 内核状态(AVX2/线程/编译器)

🎛️ 调优菜单(按需叠加,互不冲突)

手段 效果 怎么用
INT4 量化 权重 ÷8 默认开启
KV int8 长上下文 KV ÷4 load(..., kv_cache_kind="int8")
能效静音 同速、省电、风扇不转 load(..., eco="whisper") 或 m.set_eco()
层流式 常驻 ÷19(吞吐换空间) acorn.load_streaming(path)
AutoBit 同体积质量 ↑87% convert(..., autobit={...}, model=...)
剪枝 + 稀疏 字节 ÷2、加速 ×1.6 acorn.prune.prune_ffn(...)
投机解码 有效 tok/s ×1.3–1.7 generate_chat(..., speculative=True)
CUDA Graph GPU 解码零发射开销 load(..., device="cuda")

🏗️ 架构

L5 用户 API      acorn chat / train / pack / load / generate_chat / bench
L4 编排层       AutoBit · LoRA · 剪枝 · 转换器 · 能效治理
L3 运行时        AcornPack 容器 · 层流式调度 · 分页/int8 KV Cache · 投机解码
L2 计算层        微型 autograd(13 节点) · RoPE · SwiGLU · GQA
L1 内核后端      AVX2 int4 GEMM(在线解包+FMA) · 常驻线程池 · CUDA Graph
L0 算子层        NumPy 加速 + 纯 Python 回退(零依赖)

📁 项目结构

acorn-framework/
├── PLAN.md                 # 总体项目计划(里程碑/风险/验收标准)
├── RUNTIME_PLAN.md         # 运行模型详细计划(格式/内存/量化/API)
├── USAGE.md                # 使用手册
├── assets/                 # Logo(主/深色/favicon/横版字标)
├── acorn/
│   ├── _kernels/           # 原生内核:acorn_int4.c + 自动编译/ctypes 绑定
│   ├── _ops.py             # 张量算子(NumPy 加速 + 纯 Python 回退)
│   ├── _autograd.py        # 微型自动微分(requires_grad 冻结机制)
│   ├── model.py            # TinyGPT(RoPE/因果注意力/MLP)
│   ├── llama.py            # LLaMA/Qwen 架构 + 转换器
│   ├── shard.py            # 多分片流式转换(RAM 峰值 < 1GB)
│   ├── safetensors.py      # 零依赖 safetensors 读写
│   ├── tokenizer.py        # BPE 分词器(字节级 + 增量解码)
│   ├── pack.py             # INT4 量化 + .acorn 容器(mmap 加载)
│   ├── stream.py           # 层流式加载
│   ├── kvcache.py          # fp32 / int8 KV 缓存
│   ├── runtime.py          # 运行时主循环
│   ├── session.py          # 多轮对话(跨轮 KV 复用)
│   ├── chat.py             # 模板/惩罚/停止序列
│   ├── chat_cli.py         # TUI 入口(acorn chat)
│   ├── tui.py              # 终端 UI(思考流 + 流式 Markdown)
│   ├── speculative.py      # 投机解码(Prompt-Lookup)
│   ├── autobit.py          # 动态混合位宽
│   ├── prune.py            # 结构化剪枝
│   ├── lora.py             # LoRA
│   ├── train.py            # 训练引擎(AdamW/裁剪/调度)
│   ├── bench.py            # 性能基准
│   ├── eco.py              # 能效治理
│   ├── gpu.py              # CUDA Graph 后端
│   └── __main__.py         # CLI
├── examples/               # 演示脚本(hello_acorn / run_qwen3 / bench_*)
└── tests/                  # 58 项自测

🧪 测试与质量保证

python tests/test_seed.py     # 基础(autograd 数值对拍 / 量化 round-trip)
python tests/test_v02.py      # 框架(RoPE/KV Cache/LoRA/CLI)
python tests/test_v03.py      # 内核(AVX2 数值 / 压缩态 / 性能)
python tests/test_v04.py      # 真实模型(LLaMA 数值 / Qwen bias / BPE)
python tests/test_v04b.py     # 端到端流水线
python tests/test_v06.py      # AutoBit
python tests/test_v07.py      # 层流式
python tests/test_v08.py      # KV int8
python tests/test_v09.py      # 真实模型回归(Qwen2.5)
python tests/test_v10.py      # 剪枝 / 稀疏内核
python tests/test_v11.py      # Chat 层 / 投机解码金标准
python tests/test_v12.py      # Qwen3 QK-Norm / 分片转换
python tests/test_v13.py      # 能效治理

质量红线(均有测试守护):

  • LLaMA/Qwen 前向 vs 独立参考实现:rel ≤ 3.8e-7
  • 投机解码 vs 常规贪心:逐字一致
  • 稀疏内核 vs 稠密:diff = 0
  • AutoBit 同预算:质量 ↓87% 误差

🗺️ 路线图

阶段 内容 状态
M0 种子内核:autograd / INT4 / 内核 / 训练 / 容器 ✅
M1.0 原生 AVX2 内核 + 常驻线程池 + 压缩态常驻 ✅
M1.1 真实模型接入(safetensors / LLaMA / BPE / 转换器) ✅
M1.2 Qwen3-8B 上机 + QK-Norm + 多分片流式转换 ✅
M2.0 投机解码 + Chat 层 + 能效治理 + 剪枝稀疏 + KV int8 ✅
M2.1 GPU int4 内核(需 CUDA Toolkit:把 acorn/_kernels/acorn_int4.c 移植到 CUDA) 🔜
M2.2 LLaMA 路径接入 autograd → 真实模型 LoRA 训练 🔜
M2.3 连续批处理 / 多用户服务 / Hub 分发 🔜

⚠️ 已知限制(诚实清单)

  • int3 量化已实现但很慢(3-bit 无法 SIMD 化,实测比 int4 慢 4 个数量级),默认不用
  • CUDA 后端在 P620 上仍不及 CPU int4 内核(Pascal 算力弱 + eager 开销);CUDA Graph 已解决发射开销,int4 GPU 内核是下一步
  • 8B 训练在本机不可行(fp32 反量化 32GB);且 LLaMA 路径尚未接入 autograd
  • 不支持 GGUF / AWQ / GPTQ 权重,只支持 safetensors 系
  • 单机单卡,无分布式训练
  • TensorFlow 2 对比:在算子库/编译器/分布式/生态上 Acorn 落后几个数量级;Acorn 的主张限定在「小内存 CPU 推理 + 训推一体 + 零依赖 + 能效治理」这条窄道

🤝 参与

git clone <your-fork> && cd acorn-framework
pip install -e .[fast,dev]
python tests/test_seed.py && python tests/test_v04.py

欢迎提交 PR:新模型架构适配、新内核、基准数据、文档。

📄 License

MIT


🌍 English summary (for PyPI visitors)

Acorn is a from-scratch AI runtime & training framework built on one idea: big models should not require big machines.

  • INT4 compressed-resident inference — weights stay int4 in memory and are unpacked on the fly inside a hand-written AVX2 SIMD kernel (never materialized as fp32). 7.99× smaller; numerically identical to an independent reference implementation (rel ≤ 3.8e-7).
  • Real models, zero dependencies — ships its own safetensors reader (single-file & sharded, streaming), BPE tokenizer, LLaMA/Qwen2/Qwen3 architectures (RoPE-rotate_half, GQA, SwiGLU, QK-Norm), and converters. Runs Qwen3-8B on a 16 GB, GPU-less laptop.
  • Memory & speed arsenal — KV cache int8 (28% memory), layer streaming (19× less resident memory), speculative decoding (1.3–1.7×, bit-identical to greedy), AutoBit mixed-precision (87% better quality at equal bytes), structured pruning + sparse kernels, and a performance-per-watt governor that keeps the fan quiet while matching full-core speed.
  • Training too — own autodiff (13 differentiable ops, numerically checked by finite differences), AdamW, warmup+cosine, gradient clipping, LoRA.
pip install acorn-llm
acorn chat            # interactive TUI with a local model

Big models. Tiny footprint.

一颗橡子,长成参天大树。 🌰

Metadata

Release files for acorn-llm 0.9.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for acorn-llm 0.9.5
File Size Uploaded Provenance Actions
acorn_llm-0.9.5.tar.gz 120.5 kB Without provenance Details for acorn_llm-0.9.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for acorn-llm 0.9.5
File Interpreter ABI Platform Actions
acorn_llm-0.9.5-py3-none-any.whl Python 3 none any Details for acorn_llm-0.9.5-py3-none-any.whl

Total release size: 224.9 kB

Release files / acorn_llm-0.9.5.tar.gz

Download URL acorn_llm-0.9.5.tar.gz
Size 120.5 kB
Tags Source
SHA-256 checksum
How to use checksums
bb8c0df058d49d58ef0c5764101e4eb6423156a7be70e3198a8aa6aff5e7986a
BLAKE2b-256 checksum
How to use checksums
d3598e1405edf408ba84bc3ec8b96f8d3a84eb0547cf1ab26f1debed1ee4049b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.6

Release files / acorn_llm-0.9.5-py3-none-any.whl

Download URL acorn_llm-0.9.5-py3-none-any.whl
Size 104.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
36be7488a619cb18c7de126f82f8919d7e0a26b425eda13444e7b9d3a063db0f
BLAKE2b-256 checksum
How to use checksums
9a4a9efeb263c8611ccc7c8a8180acb65da0154b37b2fc3bb3d65e5fd38a873a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.6

Security for acorn-llm 0.9.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page