SKILL.md 6.24 KB

name: android-ml-inference description: Run ML/AI inference locally on Android/Termux ARM64 — embedding models, ONNX Runtime, NLP pipelines. Covers library compatibility constraints (no torch wheels), working alternatives (ONNX, numpy, transformers tokenizer), model conversion recipes, and known dead-ends. Load when installing ML libraries on Termux, running embedding/LLM inference on-device, or debugging pip install failures for ML packages on Android. category: android triggers:

  • "pip install torch 失败"
  • "Termux 装 ML 库"
  • "本地 embedding 模型"
  • "ONNX Runtime Android"
  • "sentence-transformers 装不上"
  • "BGE/bge-small 本地跑"
  • "向量模型 Termux"

- "ARM64 pip 依赖冲突"

Android ML Inference — Termux ARM64

核心约束

Termux ARM64 不是标准 Linux x86_64。以下事实决定了所有技术选型:

约束 影响
无 torch 预编译包 pip install torch / sentence-transformers 必定失败
无 Docker Milvus、Qdrant 等容器化方案不可用
C++ 编译环境残缺 FAISS、hnswlib 等含 C++ 扩展的包可能编译失败
存储有限 ChromaDB (300MB+) 等重量方案不适用

可用方案矩阵

✅ 已验证可用的

库 版本 用途 安装
onnxruntime 1.27.1 通用模型推理引擎 pip install onnxruntime
numpy 系统自带 向量存储 + 余弦检索 已安装
transformers - BERT tokenizer(文本→token) pip install transformers
optimum - HuggingFace → ONNX 模型转换 pip install optimum[onnxruntime]

❌ 已知不可用

库 失败原因
torch / pytorch ARM64 无预编译 wheel,pip 报 ResolutionImpossible
sentence-transformers 依赖 torch → 连锁失败
ChromaDB pip 安装 300MB+,依赖复杂
FAISS 需要 C++ 编译,ARM64 交叉编译麻烦
LanceDB 依赖 Rust 编译
Milvus 需要 Docker

标准路径:HuggingFace 模型 → ONNX → 本地推理

Step 1: 确认 ONNX Runtime 可用

python -c "import onnxruntime; print(onnxruntime.__version__)"
# 预期:1.27.1+

若未安装:

pip install onnxruntime

Step 2: 安装 transformers(仅需 tokenizer)

pip install transformers

Step 3: 获取 ONNX 模型

方式 A — 用 optimum-cli 从 HuggingFace 直接导出:

pip install optimum[onnxruntime]
optimum-cli export onnx --model BAAI/bge-small-zh-v1.5 bge-small-onnx/

方式 B — 从 HuggingFace Hub 下载已转换的 ONNX 模型:

# 有些模型在 Hub 上有预导出的 ONNX 版本
# 检查 https://huggingface.co/BAAI/bge-small-zh-v1.5 的 Files 标签

方式 C — 在另一台有 torch 的机器上转换,然后传到 Termux:

# 在有 GPU/x86 的机器上
from optimum.onnxruntime import ORTModelForFeatureExtraction
model = ORTModelForFeatureExtraction.from_pretrained(
    "BAAI/bge-small-zh-v1.5", export=True
)
model.save_pretrained("bge-small-onnx/")
# 再把 bge-small-onnx/ 目录 scp 到 Termux

Step 4: 推理代码

import numpy as np
import onnxruntime as ort
from transformers import AutoTokenizer

# 加载 tokenizer 和 ONNX 模型
tokenizer = AutoTokenizer.from_pretrained("bge-small-onnx/")
session = ort.InferenceSession("bge-small-onnx/model.onnx")

def embed(text: str) -> np.ndarray:
    inputs = tokenizer(text, padding=True, truncation=True, 
                       max_length=512, return_tensors="np")
    outputs = session.run(None, dict(inputs))
    # BGE 模型用 last_hidden_state 的 [CLS] token + 归一化
    vec = outputs[0][:, 0]
    return vec / np.linalg.norm(vec)

# 测试
vec = embed("你好世界")
print(vec.shape)  # (384,) for bge-small-zh-v1.5

Step 5: 余弦检索(numpy,零额外依赖)

def cosine_search(query_vec, vectors, top_k=5):
    sims = np.dot(vectors, query_vec)  # 向量已归一化
    top_indices = np.argsort(sims)[-top_k:][::-1]
    return [(i, sims[i]) for i in top_indices]

模型选型参考

模型 维度 大小 中文 备注
BAAI/bge-small-zh-v1.5 384 ~95MB ✅ SOTA 推荐首选
BAAI/bge-base-zh-v1.5 768 ~400MB ✅ 更准 更慢更大
shibing624/text2vec-base-chinese 768 ~400MB ✅ 备选
intfloat/multilingual-e5-small 384 ~120MB ✅ 多语言 需前缀 "query:"

端侧LLM模型选型

Embedding 只是端侧AI的一半。以下模型可直接在 Android/Termux 上做文章分类、摘要等 LLM 任务:

模型 参数量 亮点 端侧可行性
MiniCPM5-1B 1B 超越多款更大模型,3800万下载 ✅ ARM64可跑(GGUF/ONNX)
MiniCPM-2B 2B 更高质量,面壁旗舰 ⚠️ 需量化后可用
BGE-small-zh (已有) 33M (embedding) 向量检索最佳 ✅ 已验证通过ONNX

选型建议:

  • 文章分类/摘要/关键词提取 → MiniCPM5-1B(1B参数,手机可跑)
  • 向量检索/RAG → BGE-small-zh-v1.5(已在上面验证)
  • 质量优先 → MiniCPM-2B + 1.58-bit量化

来源:面壁智能(估值200亿),端侧AI已进入长安/上汽/吉利量产车,赛道商业已验证。 GitHub: https://github.com/OpenBMB/MiniCPM

极致量化方案

Hermes 已知 llama.cpp 的 Q2-Q8/IQ/AWQ/GPTQ/FP8 量化。面壁智能推出了更极致的方案:

方案 位深 内存节省 来源
BitCPM-CANN 1.58-bit(三值) ~6x 面壁智能,华为昇腾训练
Q2_K / IQ2 2-bit ~4x llama.cpp GGUF
Q4_K_M(基准) 4-bit ~2x llama.cpp 默认推荐
AWQ / GPTQ 4-bit ~2x 服务器端主流

关键洞察:1.58-bit 三值量化是端侧部署的极限方向。Q4_K_M 仍是当前最稳定的选择(质量/体积平衡),但 1.58-bit 为「1B模型在512MB内存手机上跑」打开了可能性。Densing Law 指出能力密度每3.5月翻倍 → 端侧模型选型应预留量化空间。

参考

  • references/pip-failure-transcript.md — sentence-transformers 安装失败的完整 pip 输出
  • references/termux-ml-constraints.md — 各方案排除原因详录