中文 English

15B 模型只要 3GB 内存、数学还拿 CMO 金牌?MiniCPM5-15B-A2.5B 深度拆解:预取路由真相、MLX/LiteRT 翻车实录与三端一键排障脚本

发布时间: 2026-12-06 · 阅读量 --
AI 大模型 LLM MiniCPM MiniCPM5 MoE AI Agent 本地大模型 Local LLM Benchmark 架构 Architecture 故障排查 Troubleshooting 避坑指南 深度评测 自动化 Automation Windows 11 Ubuntu 26.04 macOS 27

先说一句大实话:2026 年 12 月开源的 MiniCPM5-15B-A2.5B,可能是今年端侧大模型圈里「纸面体积最唬人、实战踩坑最反直觉」的一匹黑马。看它的公开战绩,几乎像开了外挂:总参数 15B、每步只激活 2.5B,正式参加 2026 年中国数学奥林匹克(CMO 2026)决赛拿下 123 / 126 官方金牌认证,IMO 2026 自测拿到 32 分(跨过 29 分金牌线),在 36 项公开基准里拿下 64.4 平均分(在参与对比的 MoE 中拿下 22 项第一,综合成绩压过体积翻倍的 Qwen3.6-35B-A3B),甚至官方演示里还能塞进 iPhone 18 Pro Max,只用约 3.1 GB 内存跑出 30 tok/s(不限内存模式 52 tok/s)。

可很多同学兴冲冲地把模型拉回自己电脑,第一天就直接撞了一鼻子灰:有人照着 3GB 内存的宣传在 16GB 笔记本上跑 LiteRT int8 结果卡成幻灯片,或者选了 int4 结果模型智商直接断崖下跌;有人在 Mac 上习惯性打开 mlx-lm 结果完全认不出模型;有人用新版 GGUF 跑 ollama run 直接弹出 unknown model architecture: 'minicpm5_moe';还有人把思考模式一关,模型就像坏掉的磁带一样开始无限复读,甚至接入 Claude Code 或 Codex 后频频触发 HTTP 400。

把 openbmb/MiniCPM5-15B-A2.5B 的官方 config.json、GitHub 各后端部署 Cookbook(llama_cpp.md、ollama.md、mlx.md、litert.md、minicpm5_on_ios.md、tool_usage.md)逐行交叉拆解后,每一条坑的底层逻辑都无比清晰。今天这篇深度文章,我们用 12 张真实浏览器截图与花叔风格原创图解、小学生都能听懂 70% 以上的日常大比方,以及开箱即用的 Windows 11 / Ubuntu 26.04 / macOS 27 三端零依赖排障与自动配置脚本,帮你一次性绕开全部暗坑。

原创全景封面:MiniCPM5-15B-A2.5B 深度拆解、预取路由真相与三端避坑导航

图 1:本文原创全景封面。浓缩 MiniCPM5-15B-A2.5B 的核心规格(15B 总参 / 2.5B 激活、CMO 123/126 金牌、52 tok/s 端侧预取、524,288 上下文)与四大实战避坑主题。


一、问题背景:这颗「面壁小钢炮」凭什么把 30B 级前辈拉下马?

由 OpenBMB(面壁智能与清华 NLP 实验室联合发起)推出的 MiniCPM5-15B-A2.5B,走了一条与「云端堆参数」完全相反的路线——把推理密度做到极致,让真正的智能体(Agent)完全留在手机和个人电脑本地跑,并且采用极其干脆的 Apache 2.0 开源协议。

真实浏览器截图:Hugging Face openbmb/MiniCPM5-15B-A2.5B 模型主页显示 Apache 2.0 协议与 15B 参数规模

图 2:真实浏览器截图(huggingface.co/openbmb/MiniCPM5-15B-A2.5B)。主页标注 minicpm5_moe 架构、Apache 2.0 开源协议,并关联了 GGUF、MLX、LiteRT、DSpark 等 34 个衍生量化仓库。

从官方发布的 36 项权威基准对比来看,这颗 15B 总参、2.5B 激活的小钢炮并不是靠单一单项刷榜,而是在数学、代码、工具调用和 Agent 工作流上全面开花:

真实浏览器截图:MiniCPM5-15B-A2.5B 官方 36 项基准完整对比表,平均分 64.4 领先多款 30B 级模型

图 3:真实截图(截取自官方模型卡 SVG 评测总表)。MiniCPM5-15B-A2.5B 综合均分 64.4,高于 Qwen3.6-35B-A3B(59.9)和 Qwen3.5-27B(63.2),但也能清晰看到它在 LongBench v2 128K(51.1)与 IFBench(64.3)上的真实取舍。

真实浏览器截图:GitHub OpenBMB/MiniCPM 官方仓库首页展示 12k Star、eval/imo-harness 与 docs/skills 目录

图 4:真实浏览器截图(github.com/OpenBMB/MiniCPM)。官方在仓库内一次性放出了完整的部署 Cookbook、微调脚本、Agent Skills 以及 eval/imo-harness 复现指南。


二、问题表现:本地上手第一天,最常撞上的四大「诡异翻车现场」

模型本身很强,但生态适配刚刚在 2026 年 11 月底至 12 月初落地,各个推理框架的暗坑几乎全集中在本地部署的第一步。社区反馈和官方 Issue 里最频繁出现的翻车表现如下:

真实浏览器截图:Hugging Face openbmb/MiniCPM5-15B-A2.5B-GGUF 文件列表显示 BF16(30GB)、Q8_0(16GB) 与 Q4_K_M(9.12GB)

图 5:真实浏览器截图(huggingface.co/openbmb/MiniCPM5-15B-A2.5B-GGUF)。标准桌面端 GGUF 文件体积分别为 BF16(27.97 GiB / ~30GB)、Q8_0(14.87 GiB / ~16GB)和 Q4_K_M(8.49 GiB / ~9.12GB),和手机专用的 LCO-GGUF 是两套完全不同的加载机制。


三、小学生都能听懂 70%+ 的底层原理:为什么它能「小机身装大智商」?

要彻底搞懂上面四个坑为什么会发生,不需要背神经网络公式,我们用日常生活里最熟悉的「大医院分诊 + 图书管理员提前抽书 + 两本极简速记本」三个场景,把 MiniCPM5-15B-A2.5B 的全部家底拆给你看。

原创日常大比方图解:用门诊接待员、160位专科老师傅、预取小助手与双份速记本解释 MiniCPM5 预取路由

图 6:本文原创大比方图解。为什么手机内存只有小小的桌面,却能跑得动 15B 知识库?关键就在第 1–27 层的「16/160 稀疏会诊」和「LES 1.0 预取小助手」。

3.1 15B 知识库每次只动 2.5B:1 位门卫 + 160 位专科老师傅

传统的 15B 稠密模型,就像一所只有 1 位全能博士的诊所——不管你是来问「1+1 等于几」还是「怎么证明奥数不等式」,这位博士都必须动用全身 100% 的脑细胞算一遍,既费电又慢。

而 MiniCPM5-15B-A2.5B 把整座大楼拆成了 28 层(严格对应官方 config.json):

所以,整栋大楼虽然存了 150 亿(15B) 的知识储备,但每吐一个字真正上桌干活的脑细胞只有大约 25 亿(2.5B)。这正是它推理速度快得像 3B 小模型、解题实力却能碰瓷 30B 大佬的根本原因。

3.2 手机 3GB 内存能跑 15B 的秘密:LES 1.0「预取小助手」提前抽书

既然 160 位老师傅平时大部分都在休息,那能不能只把正在干活的那 16 位老师傅请上小小的手机内存桌面上,剩下的先留在身后的闪存大书柜里?

普通按需加载的痛点在于「干等」:算完第 5 层才知道第 6 层要找哪 16 位师傅,再去闪存里翻书搬上桌,CPU 和 GPU 只能原地罚站。而 OpenBMB 在 LES 1.0 的基础上给 MiniCPM5 做了原生预取路由训练(Native Prefetch-Routing)——相当于在每个老师傅旁边配了一位神机妙算的「预取小助手」。当第 5 层还在做计算时,小助手就已经提前猜中第 6 层大概率要叫哪几号师傅,专家预取预测准确率平均提升了约 11%,趁着计算间隙提前从闪存把权重悄悄搬进内存!

配合专为端侧流式读取打造的 Q3_gud-LCO-GGUF(路由专家压缩成 3-bit Q3_K,其余关键层保留 4-bit/6-bit Q4_K/Q6_K,文件约 6.8 GB)和魔改版 llama.cpp-omni,iPhone 18 Pro Max 在省流模式下把常驻内存压到 约 3.1 GB 依然能维持 30 tok/s 的流畅输出!

3.3 524,288 字超长记忆靠什么?「32 个人共用 2 本速记本」(32Q : 2KV)

聊天越长越占内存,罪魁祸首是草稿纸(KV Cache)。常规模型为了记住上下文,每个注意力头都要配草稿纸。而 MiniCPM5-15B-A2.5B 在 config.json 里采用了一个非常狠的设计:Gated GQA(门控分组查询注意力),配置为 32 个查询头(num_attention_heads=32)只配 2 个键值头(num_key_value_heads=2),head_dim=128,开启门控注意力(use_gated_attention=true),旋转位置编码基数 rope_theta=5,000,000。

打个比方:32 位负责读题提问的小组长,不需要每人发一本厚草稿本,而是大家共用 2 本提炼得极干净的共用速记本,同时每道门还加了一道「过滤闸门」(Gated Attention)把废话噪音挡在外面。KV 缓存一下子缩小到常规结构的十六分之一,这才让它原生支持高达 524,288 Token 的超长上下文窗口。

3.4 22 位专精老师教出一个学生:JustRL-II + 多教师在线蒸馏(MOPD)

至于为什么区区 2.5B 激活参数能在奥数和编程上同时封神,秘密在后训练配方:OpenBMB 先搭建了数百万个交互环境,用长程强化学习 JustRL-II 分别练出了 22 位各有所长的专科 RL 老师模型(专门管数学的、管写代码的、管调工具的、管写作的),然后通过多教师在线策略蒸馏(MOPD),按每个生成位置计算反向 KL 散度,把 22 位名师的绝学全部压缩灌进同一个 MiniCPM5-15B-A2.5B 学生身上——实测让 Agent 基准成绩比纯 SFT 基线平均暴涨 7.85 分。

技术架构蓝图:严格对照 config.json 的 MiniCPM5MoEForCausalLM 28 层网络结构与 Gated GQA 32Q:2KV 参数

图 7:严格对照官方 config.json 绘制的 MiniCPM5MoEForCausalLM 28 层架构全图。注意第 0 层是 8,192 维 Dense MLP,第 1–27 层才是 160 选 16 的 MoE 层。


四、问题分析与根因定位:四大翻车现场背后的硬核真相

理解了架构之后,再回头看前面四个让人抓狂的报错,每一条都能精准定位到源代码和参数层面:

根因 1:minicpm5_moe 架构过新,且 Mac 端侧适配故意放进了 mlx-vlm

因为 MiniCPM5 同时用到了「第 0 层 Dense + 后 27 层 160 专家 MoE + 门控 GQA(Q/G 分裂)」这套全新算子组合,任何早于 2026 年 11 月底合并补丁的软件都会当场罢工:

根因 2:把手机「闪存流式卸载」误当成电脑「低内存魔法」,以及 LiteRT int4 精度悬崖

很多人混淆了「模型总体积」和「iOS 省流版运行占用」:

真实浏览器截图:GitHub OpenBMB/MiniCPM litert.md 官方文档记录 mixed(8.28GB)、int8(15.08GB) 与 int4(7.58GB) 规格差异

图 8:真实浏览器截图(OpenBMB/MiniCPM/docs/deployment/minicpm5-15b-a2.5b/litert.md)。官方白纸黑字标注了 mixed、int8、int4 三种捆绑包在 NLL 精度与 16GB 内存换页崩溃上的巨大差异。

真实浏览器截图:minicpm5_on_ios.md 记录 iPhone 18 Pro Max 在 Memory saver(3.1GB, 30 tok/s) 与 Fastest(52 tok/s) 实测数据

图 9:真实浏览器截图(minicpm5_on_ios.md)。iPhone 18 Pro Max(12 GB)在 Memory saver 模式下峰值内存仅 3.1 GB、解码 ~30 tok/s,而在 Fastest 模式下映射 6.8 GB 权重可达 ~52 tok/s。

原创量化与硬件选型矩阵:对比 GGUF BF16/Q8_0/Q4_K_M、LCO-GGUF、MLX 4-bit 与 LiteRT mixed/int4/int8

图 10:本文原创全端量化与硬件对照矩阵。一眼看清 16GB / 24GB / 32GB+ 电脑以及手机端应该选哪个包、避开哪个雷。

根因 3:llama.cpp 默认 min_p=0.05 剪掉「逃生词」 + DSpark 步数贪心

为什么一关思考模式或者在 llama.cpp 里跑久了就开始复读?因为 llama.cpp 的默认参数里藏着一个 min_p=0.05——它会无情砍掉概率低于最高概率 Token 5% 的所有候选词。但在大模型快要陷入重复句式时,恰恰需要那些概率偏低的转折词来「跳出死循环」。因此官方在 llama_cpp.md 里专门加粗要求:必须传入 --min-p 0!此外,关闭思考模式(enable_thinking=False)时,必须配齐 temperature=0.7, top_p=0.80, top_k=20, min_p=0.0, presence_penalty=1.5,靠 presence_penalty=1.5 强行惩罚已经出现过的词。

而 DSpark 投机采样变慢的原因同样很直白:官方草稿模型 MiniCPM5-15B-A2.5B-DSpark 最多支持一轮猜 7 个 Token(--spec-draft-n-max 7)。在 BF16 原版模型上命中率极高;可一旦主模型换成了 Q4_K_M 等量化权重,两者输出分布出现轻微偏差,一口气猜 7 个词频频被打回重算,反而浪费算力。这时候只需要把 --spec-draft-n-max 降到 2(或 MLX-VLM 里把 --draft-block-size 从 8 降到 4),吞吐立刻回到正收益。

根因 4:Agent 协议里的「空行刺客」、网关版本与思考截断

最后是把模型接进 Claude Code、Codex CLI、DeepSeek Harness 时最容易撞上的四颗工程钉子(均已由官方 tool_usage.md 证实):

原创协议流图:MiniCPM5-15B-A2.5B 接入 Claude Code / Codex / DeepSeek Harness 的双解析器、思考保留与 400 修复

图 11:本文原创 Agent 协议链路图。记住三个关键数字:解析器用 minicpm5 + qwen3、编程 max_tokens >= 16384、关闭思考配 presence_penalty=1.5。


五、如何解决问题:全自动三端脚本 + 人工与 Agent 双模式落地

光讲原理不够,下面直接给出一套从「硬件体检 → 避坑拦截 → 启动器生成 → Agent 档案脚手架」的完整解决方案。我们准备了完全不依赖任何第三方服务或 Python 依赖包的三端原生脚本(Windows 11 / Ubuntu 26.04 / macOS 27),同时提供方法一(人工手动执行)与方法二(AI Agent 全自动配置)两种用法。

原创排障矩阵:现象、根因与精准修复一一对应的 MiniCPM5-15B-A2.5B 四大排障链路

图 12:MiniCPM5-15B-A2.5B 本地部署四大排障总览图(现象 → 根因 → 精准修复)。

5.1 方法一:人工手动部署与一键脚本执行

在运行脚本前,先记住各推理后端的黄金人工启动命令(按需选用):

为了省去每次手动算内存、查环境版本和拼启动参数的麻烦,下面给出三大操作系统的零依赖一键体检与自动生成脚本。脚本会自动扫描你的内存/显存/硬盘余量、检测 mlx-lm 误装陷阱、Ollama KV 缓存膨胀风险、transformers >= 5.25.0 就绪度与陈旧环境变量,并在 ~/.minicpm5-local 下自动写好防复读启动器与采样预设。

1. Windows 11 专版(原生 PowerShell:minicpm5_local_toolkit_windows11.ps1)

# ==============================================================================
# MiniCPM5-15B-A2.5B Local Diagnostic, Backend Guard & Auto-Config — Windows 11
# Zero third-party dependencies (native PowerShell 5.1 / 7+ only)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: powershell -ExecutionPolicy Bypass -File .\minicpm5_local_toolkit_windows11.ps1
#   Agent Automated:   powershell -ExecutionPolicy Bypass -File .\minicpm5_local_toolkit_windows11.ps1 -Auto -Json -Apply -ScaffoldAgent -Target .
# ==============================================================================
[CmdletBinding()]
param(
    [switch]$Auto,
    [switch]$Json,
    [ValidateSet("thinking", "fast")][string]$Mode = "thinking",
    [switch]$Apply,
    [switch]$ApplyOllama,
    [switch]$ScaffoldAgent,
    [string]$Target = "."
)

$ErrorActionPreference = "Stop"

# 1. Hardware & Storage Detection (Sanitized — no hostname or raw IP)
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
$totalRamGB = [math]::Round($cs.TotalPhysicalMemory / 1GB, 1)

$gpuName = "none"
$vramGB = 0.0
$nvidiaSmi = Get-Command nvidia-smi -ErrorAction SilentlyContinue
if ($nvidiaSmi) {
    try {
        $smiOut = (& nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits 2>$null | Select-Object -First 1)
        if ($smiOut) {
            $parts = $smiOut -split ","
            $gpuName = $parts[0].Trim()
            $vramGB = [math]::Round(([double]$parts[1].Trim()) / 1024, 1)
        }
    } catch {}
}
if ($vramGB -eq 0) {
    $vc = Get-CimInstance -ClassName Win32_VideoController | Sort-Object AdapterRAM -Descending | Select-Object -First 1
    if ($vc) {
        $gpuName = $vc.Name
        if ($vc.AdapterRAM -gt 0) {
            $vramGB = [math]::Round($vc.AdapterRAM / 1GB, 1)
        }
    }
}

$targetResolved = (Resolve-Path -Path $Target -ErrorAction SilentlyContinue)
if (-not $targetResolved) { $targetResolved = Get-Location }
$driveLetter = ($targetResolved.Path.Substring(0, 1))
$psDrive = Get-PSDrive -Name $driveLetter -ErrorAction SilentlyContinue
$freeDiskGB = if ($psDrive) { [math]::Round($psDrive.Free / 1GB, 1) } else { 0.0 }

$effectiveBudgetGB = if ($vramGB -ge 12) { $vramGB } else { [math]::Round($totalRamGB * 0.75 + $vramGB, 1) }

if ($effectiveBudgetGB -ge 32) {
    $tier = "Tier-A (32GB+)"
    $recGguf = "MiniCPM5-15B-A2.5B-BF16.gguf (27.97 GiB) or Q8_0"
    $recLitert = "MiniCPM5-15B-A2.5B_int8.litertlm (15.08 GB) or _mixed"
    $downloadGB = 27.97
} elseif ($effectiveBudgetGB -ge 22) {
    $tier = "Tier-B (24GB)"
    $recGguf = "MiniCPM5-15B-A2.5B-Q8_0.gguf (14.87 GiB)"
    $recLitert = "MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB)"
    $downloadGB = 14.87
} elseif ($effectiveBudgetGB -ge 15) {
    $tier = "Tier-C (16GB)"
    $recGguf = "MiniCPM5-15B-A2.5B-Q4_K_M.gguf (8.49 GiB)"
    $recLitert = "MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB; NEVER int8 or int4)"
    $downloadGB = 8.49
} else {
    $tier = "Tier-D (<16GB Tight)"
    $recGguf = "MiniCPM5-15B-A2.5B-Q4_K_M.gguf (tight; offload fewer layers or try MiniCPM5-2B)"
    $recLitert = "MiniCPM5-15B-A2.5B_mixed.litertlm (tight)"
    $downloadGB = 8.49
}

$diskSpaceWarning = ($freeDiskGB -lt 25.0)

# 2. Local Runtime & Day-1 Trap Scan
$llamaServerCmd = Get-Command llama-server -ErrorAction SilentlyContinue
$ollamaCmd = Get-Command ollama -ErrorAction SilentlyContinue
$litertCmd = Get-Command litert-lm -ErrorAction SilentlyContinue
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue

$transformersOk = $false
if ($pythonCmd) {
    try {
        & python -c "import transformers, packaging.version as v; exit(0 if v.parse(transformers.__version__) >= v.parse('5.25.0') else 1)" 2>$null
        if ($LASTEXITCODE -eq 0) { $transformersOk = $true }
    } catch {}
}

$ollamaFlashAttn = [Environment]::GetEnvironmentVariable("OLLAMA_FLASH_ATTENTION", "User")
if (-not $ollamaFlashAttn) { $ollamaFlashAttn = $env:OLLAMA_FLASH_ATTENTION }
$ollamaKvType = [Environment]::GetEnvironmentVariable("OLLAMA_KV_CACHE_TYPE", "User")
if (-not $ollamaKvType) { $ollamaKvType = $env:OLLAMA_KV_CACHE_TYPE }

$ollamaKvBloatTrap = ($null -ne $ollamaCmd) -and (($ollamaFlashAttn -ne "1") -or ([string]::IsNullOrWhiteSpace($ollamaKvType)))
$staleBaseUrlTrap = (-not [string]::IsNullOrWhiteSpace($env:OPENAI_BASE_URL)) -and ($env:OPENAI_BASE_URL -notmatch "localhost") -and ($env:OPENAI_BASE_URL -notmatch "127\.0\.0\.1")

# 3. Interactive Human Prompt if not -Auto
if (-not $Auto) {
    Write-Host "=== MiniCPM5-15B-A2.5B Windows 11 Local Triage ===" -ForegroundColor Cyan
    Write-Host "Hardware Tier: $tier | RAM: $totalRamGB GB | VRAM: $vramGB GB ($gpuName)"
    Write-Host "GGUF Pick:     $recGguf"
    Write-Host "LiteRT-LM:     $recLitert"
    if (-not $Apply) {
        $ansApply = Read-Host "Generate local MiniCPM5 launchers & presets under ~\.minicpm5-local? [Y/n]"
        if ($ansApply -eq "" -or $ansApply -match "^[Yy]") { $Apply = $true }
    }
    if ($ollamaCmd -and -not $ApplyOllama) {
        $ansOllama = Read-Host "Persist Ollama FlashAttention + q8_0 KV cache env vars? [y/N]"
        if ($ansOllama -match "^[Yy]") { $ApplyOllama = $true }
    }
    if (-not $ScaffoldAgent) {
        $ansAgent = Read-Host "Scaffold local MiniCPM5 agent profile in Target directory? [y/N]"
        if ($ansAgent -match "^[Yy]") { $ScaffoldAgent = $true }
    }
}

# 4. Apply Launchers & Sampling Presets Safely
$cpmDir = Join-Path $HOME ".minicpm5-local"
$launcherCreated = $false
$presetsCreated = $false
$ollamaEnvApplied = $false
$agentScaffolded = $false
$backupFile = "none"

if ($Apply) {
    if (-not (Test-Path $cpmDir)) { New-Item -ItemType Directory -Path $cpmDir -Force | Out-Null }

    $thinkingScript = @'
# Auto-generated MiniCPM5-15B-A2.5B Thinking Launcher (anti-loop --min-p 0)
param([string]$GgufPath = "$HOME\models\MiniCPM5-15B-A2.5B-Q4_K_M.gguf")
$ErrorActionPreference = "Stop"
llama-server -m $GgufPath -a MiniCPM5-15B-A2.5B `
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja `
  --temp 1.0 --top-p 0.95 --min-p 0.0 --repeat-penalty 1.0
'@
    $fastScript = @'
# Auto-generated MiniCPM5-15B-A2.5B Non-Thinking Fast Launcher (presence_penalty=1.5)
param([string]$GgufPath = "$HOME\models\MiniCPM5-15B-A2.5B-Q4_K_M.gguf")
$ErrorActionPreference = "Stop"
llama-server -m $GgufPath -a MiniCPM5-15B-A2.5B `
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja `
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p 0.0 --presence-penalty 1.5 --repeat-penalty 1.0
'@
    $thinkPath = Join-Path $cpmDir "launch-minicpm5-thinking.ps1"
    $fastPath = Join-Path $cpmDir "launch-minicpm5-fast.ps1"
    if (Test-Path $thinkPath) {
        $backupFile = "$thinkPath.bak.$(Get-Date -Format 'yyyyMMddHHmmss')"
        Copy-Item $thinkPath $backupFile -Force
    }
    Set-Content -Path $thinkPath -Value $thinkingScript -Encoding UTF8
    Set-Content -Path $fastPath -Value $fastScript -Encoding UTF8
    $launcherCreated = $true

    $presetsJson = @{
        model = "MiniCPM5-15B-A2.5B"
        thinking_general = @{ temperature = 1.0; top_p = 0.95; min_p = 0.0; repetition_penalty_if_loop = 1.05 }
        non_thinking_general = @{ temperature = 0.7; top_p = 0.80; top_k = 20; min_p = 0.0; presence_penalty = 1.5; repetition_penalty = 1.0 }
        dspark_quantized_safe = @{ spec_type = "draft-dspark"; spec_draft_n_max = 2; spec_draft_p_min = 0 }
        agent_protocol_guards = @{
            vllm_sglang_parsers = "--tool-call-parser minicpm5 --reasoning-parser qwen3"
            coding_min_max_tokens = 16384
        }
    } | ConvertTo-Json -Depth 4
    Set-Content -Path (Join-Path $cpmDir "sampling-presets.json") -Value $presetsJson -Encoding UTF8
    $presetsCreated = $true
}

if ($ApplyOllama) {
    [Environment]::SetEnvironmentVariable("OLLAMA_FLASH_ATTENTION", "1", "User")
    [Environment]::SetEnvironmentVariable("OLLAMA_KV_CACHE_TYPE", "q8_0", "User")
    $env:OLLAMA_FLASH_ATTENTION = "1"
    $env:OLLAMA_KV_CACHE_TYPE = "q8_0"
    $ollamaEnvApplied = $true
    $ollamaKvBloatTrap = $false
}

if ($ScaffoldAgent) {
    $agentDir = Join-Path $targetResolved.Path ".claude\agents"
    if (-not (Test-Path $agentDir)) { New-Item -ItemType Directory -Path $agentDir -Force | Out-Null }
    $agentProfile = @"
---
name: minicpm5-local-worker
description: Local MiniCPM5-15B-A2.5B Windows 11 execution & protocol guard profile
---
- Local endpoint: ``http://localhost:8080/v1``
- Requires llama.cpp build >= b12847 (PR #32644) for ``minicpm5_moe``.
- Always pass ``--min-p 0``; use ``presence_penalty=1.5`` when thinking is off.
- Set ``max_tokens >= 16384`` for coding tasks and preserve historical thinking blocks.
"@
    Set-Content -Path (Join-Path $agentDir "minicpm5-local-worker.md") -Value $agentProfile -Encoding UTF8
    $agentScaffolded = $true
}

# 5. Output
$result = [ordered]@{
    os = "Windows 11"
    ram_gb = $totalRamGB
    gpu = $gpuName
    vram_gb = $vramGB
    free_disk_gb = $freeDiskGB
    tier = $tier
    recommended_gguf = $recGguf
    recommended_litert = $recLitert
    estimated_download_gb = $downloadGB
    traps = [ordered]@{
        disk_space_warning = $diskSpaceWarning
        llama_server_found = ($null -ne $llamaServerCmd)
        ollama_found = ($null -ne $ollamaCmd)
        litert_lm_found = ($null -ne $litertCmd)
        transformers_5_25_ready = $transformersOk
        ollama_kv_bloat_trap = $ollamaKvBloatTrap
        stale_base_url_trap = $staleBaseUrlTrap
    }
    actions = [ordered]@{
        launcher_created = $launcherCreated
        presets_created = $presetsCreated
        ollama_env_applied = $ollamaEnvApplied
        agent_scaffolded = $agentScaffolded
        backup_file = $backupFile
    }
}

if ($Json) {
    $result | ConvertTo-Json -Depth 5
} else {
    Write-Host ""
    Write-Host "=== Summary & Next Steps ===" -ForegroundColor Green
    Write-Host "Tier          : $tier"
    Write-Host "Launchers Dir : $cpmDir"
    Write-Host "Remember      : Always pass --min-p 0 to llama-server; never run LiteRT int4."
}

人工手动执行命令(Windows PowerShell 终端运行):

powershell -ExecutionPolicy Bypass -File .\minicpm5_local_toolkit_windows11.ps1

2. Ubuntu 26.04 专版(原生 Bash:minicpm5_local_toolkit_ubuntu2604.sh)

#!/usr/bin/env bash
# ==============================================================================
# MiniCPM5-15B-A2.5B Local Diagnostic, Backend Guard & Auto-Config — Ubuntu 26.04
# Zero third-party dependencies (GNU bash, awk, grep, sed, free, df, tr)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: bash ./minicpm5_local_toolkit_ubuntu2604.sh
#   Agent Automated:   bash ./minicpm5_local_toolkit_ubuntu2604.sh --auto --json --apply --scaffold-agent --target .
# ==============================================================================
set -euo pipefail

AUTO=0
JSON_MODE=0
APPLY=0
APPLY_OLLAMA=0
SCAFFOLD_AGENT=0
TARGET_DIR="."

while [[ $# -gt 0 ]]; do
  case "$1" in
    --auto) AUTO=1; shift ;;
    --json) JSON_MODE=1; shift ;;
    --apply) APPLY=1; shift ;;
    --apply-ollama) APPLY_OLLAMA=1; shift ;;
    --scaffold-agent) SCAFFOLD_AGENT=1; shift ;;
    --target) TARGET_DIR="${2:-.}"; shift 2 ;;
    -h|--help)
      cat <<'EOF'
Usage: bash minicpm5_local_toolkit_ubuntu2604.sh [options]
  --auto            Non-interactive mode for AI Agents
  --json            Emit sanitized JSON output
  --apply           Generate ~/.minicpm5-local launchers & sampling presets
  --apply-ollama    Write ~/.minicpm5-local/ollama-override.conf for systemd
  --scaffold-agent  Write .claude/agents/minicpm5-local-worker.md in --target
  --target <dir>    Target workspace directory (default: .)
EOF
      exit 0
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

# 1. Hardware & Disk Detection (Sanitized)
RAM_KB="$(awk '/MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || echo 0)"
RAM_GB="$(awk -v k="${RAM_KB:-0}" 'BEGIN {printf "%.1f", k/1024/1024}')"

GPU_NAME="none"
VRAM_GB="0.0"
if command -v nvidia-smi >/dev/null 2>&1; then
  SMI_LINE="$(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits 2>/dev/null | head -n 1 || true)"
  if [[ -n "$SMI_LINE" ]]; then
    GPU_NAME="$(echo "$SMI_LINE" | awk -F',' '{gsub(/^[ \t]+|[ \t]+$/, "", $1); print $1}')"
    VRAM_MB="$(echo "$SMI_LINE" | awk -F',' '{gsub(/^[ \t]+|[ \t]+$/, "", $2); print $2}')"
    VRAM_GB="$(awk -v m="${VRAM_MB:-0}" 'BEGIN {printf "%.1f", m/1024}')"
  fi
fi

mkdir -p "$TARGET_DIR" 2>/dev/null || true
FREE_DISK_KB="$(df -Pk "$TARGET_DIR" | awk 'NR==2 {print $4}')"
FREE_DISK_GB="$(awk -v k="${FREE_DISK_KB:-0}" 'BEGIN {printf "%.1f", k/1024/1024}')"

BUDGET_GB="$(awk -v v="$VRAM_GB" -v r="$RAM_GB" 'BEGIN {if (v >= 12) printf "%.1f", v; else printf "%.1f", r*0.75 + v}')"

TIER="Tier-D (<16GB Tight)"
REC_GGUF="MiniCPM5-15B-A2.5B-Q4_K_M.gguf (tight; offload partial layers or use MiniCPM5-2B)"
REC_VLLM="GPTQ 4-bit (cap --max-model-len 32768)"
REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB)"
DL_GB="8.49"

if awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 32)}'; then
  TIER="Tier-A (32GB+)"
  REC_GGUF="MiniCPM5-15B-A2.5B-BF16.gguf (27.97 GiB) or Q8_0"
  REC_VLLM="openbmb/MiniCPM5-15B-A2.5B (BF16 + DSpark)"
  REC_LITERT="MiniCPM5-15B-A2.5B_int8.litertlm (15.08 GB) or _mixed"
  DL_GB="27.97"
elif awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 22)}'; then
  TIER="Tier-B (24GB)"
  REC_GGUF="MiniCPM5-15B-A2.5B-Q8_0.gguf (14.87 GiB)"
  REC_VLLM="openbmb/MiniCPM5-15B-A2.5B-GPTQ (4-bit + DSpark)"
  REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB)"
  DL_GB="14.87"
elif awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 15)}'; then
  TIER="Tier-C (16GB)"
  REC_GGUF="MiniCPM5-15B-A2.5B-Q4_K_M.gguf (8.49 GiB)"
  REC_VLLM="openbmb/MiniCPM5-15B-A2.5B-GPTQ (cap --max-model-len 16384)"
  REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB; NEVER int8/int4)"
  DL_GB="8.49"
fi

DISK_WARN="false"
if awk -v d="$FREE_DISK_GB" 'BEGIN {exit !(d < 25)}'; then
  DISK_WARN="true"
fi

# 2. Local Runtime & Day-1 Trap Scan
LLAMA_FOUND="false"; command -v llama-server >/dev/null 2>&1 && LLAMA_FOUND="true"
OLLAMA_FOUND="false"; command -v ollama >/dev/null 2>&1 && OLLAMA_FOUND="true"
LITERT_FOUND="false"; command -v litert-lm >/dev/null 2>&1 && LITERT_FOUND="true"
TRANSFORMERS_OK="false"
if command -v python3 >/dev/null 2>&1; then
  python3 -c "import transformers, packaging.version as v; exit(0 if v.parse(transformers.__version__) >= v.parse('5.25.0') else 1)" >/dev/null 2>&1 && TRANSFORMERS_OK="true"
fi

OLLAMA_KV_BLOAT_TRAP="false"
if [[ "$OLLAMA_FOUND" == "true" ]]; then
  if [[ "${OLLAMA_FLASH_ATTENTION:-}" != "1" || -z "${OLLAMA_KV_CACHE_TYPE:-}" ]]; then
    OLLAMA_KV_BLOAT_TRAP="true"
  fi
fi

STALE_BASE_URL_TRAP="false"
if [[ -n "${OPENAI_BASE_URL:-}" && ! "${OPENAI_BASE_URL}" =~ localhost && ! "${OPENAI_BASE_URL}" =~ 127\.0\.0\.1 ]]; then
  STALE_BASE_URL_TRAP="true"
fi

# 3. Interactive Human Prompt
if (( AUTO == 0 )); then
  echo "=== MiniCPM5-15B-A2.5B Ubuntu 26.04 Local Triage ==="
  echo "Hardware Tier: ${TIER} | RAM: ${RAM_GB} GB | VRAM: ${VRAM_GB} GB (${GPU_NAME})"
  echo "GGUF Pick:     ${REC_GGUF}"
  echo "vLLM/SGLang:   ${REC_VLLM}"
  echo "LiteRT-LM:     ${REC_LITERT}"
  if (( APPLY == 0 )); then
    read -r -p "Generate local MiniCPM5 launchers & presets in ~/.minicpm5-local? [Y/n] " ans_apply
    if [[ -z "$ans_apply" || "$ans_apply" =~ ^[Yy]$ ]]; then APPLY=1; fi
  fi
  if [[ "$OLLAMA_FOUND" == "true" && $APPLY_OLLAMA -eq 0 ]]; then
    read -r -p "Generate Ollama systemd override snippet (~/.minicpm5-local/ollama-override.conf)? [y/N] " ans_ol
    if [[ "$ans_ol" =~ ^[Yy]$ ]]; then APPLY_OLLAMA=1; fi
  fi
  if (( SCAFFOLD_AGENT == 0 )); then
    read -r -p "Scaffold local MiniCPM5 worker profile in target directory? [y/N] " ans_ag
    if [[ "$ans_ag" =~ ^[Yy]$ ]]; then SCAFFOLD_AGENT=1; fi
  fi
fi

# 4. Apply Configs Safely
CPM_DIR="${HOME}/.minicpm5-local"
LAUNCHER_CREATED="false"
PRESETS_CREATED="false"
OLLAMA_CONF_CREATED="false"
AGENT_SCAFFOLDED="false"
BACKUP_FILE="none"

if (( APPLY == 1 )); then
  mkdir -p "$CPM_DIR"
  THINK_SH="${CPM_DIR}/launch-minicpm5-thinking.sh"
  FAST_SH="${CPM_DIR}/launch-minicpm5-fast.sh"
  VLLM_SH="${CPM_DIR}/launch-minicpm5-vllm.sh"
  MODELFILE_PATH="${CPM_DIR}/Modelfile.minicpm5-q4km"
  if [[ -f "$THINK_SH" ]]; then
    BACKUP_FILE="${THINK_SH}.bak.$(date +%Y%m%d%H%M%S)"
    cp "$THINK_SH" "$BACKUP_FILE"
  fi

  cat > "$THINK_SH" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
GGUF_PATH="${1:-$HOME/models/MiniCPM5-15B-A2.5B-Q4_K_M.gguf}"
exec llama-server -m "$GGUF_PATH" -a MiniCPM5-15B-A2.5B \
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja \
  --temp 1.0 --top-p 0.95 --min-p 0.0 --repeat-penalty 1.0
EOF
  chmod +x "$THINK_SH"

  cat > "$FAST_SH" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
GGUF_PATH="${1:-$HOME/models/MiniCPM5-15B-A2.5B-Q4_K_M.gguf}"
exec llama-server -m "$GGUF_PATH" -a MiniCPM5-15B-A2.5B \
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja \
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p 0.0 --presence-penalty 1.5 --repeat-penalty 1.0
EOF
  chmod +x "$FAST_SH"

  cat > "$VLLM_SH" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
MODEL_ID="${1:-openbmb/MiniCPM5-15B-A2.5B-GPTQ}"
exec vllm serve "$MODEL_ID" --served-model-name MiniCPM5-15B-A2.5B \
  --host localhost --port 8000 --max-model-len 32768 \
  --enable-auto-tool-choice --tool-call-parser minicpm5 --reasoning-parser qwen3
EOF
  chmod +x "$VLLM_SH"

  cat > "$MODELFILE_PATH" <<'EOF'
FROM ./MiniCPM5-15B-A2.5B-Q4_K_M.gguf

TEMPLATE """{{- if .Messages -}}
{{- range .Messages -}}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end -}}
<|im_start|>assistant
{{ end -}}"""

PARAMETER stop "<|im_end|>"
PARAMETER stop "</s>"
PARAMETER temperature 1.0
PARAMETER top_p 0.95
PARAMETER num_ctx 8192
EOF

  cat > "${CPM_DIR}/sampling-presets.json" <<'EOF'
{
  "model": "MiniCPM5-15B-A2.5B",
  "thinking_general": {"temperature": 1.0, "top_p": 0.95, "min_p": 0.0, "repetition_penalty_if_loop": 1.05},
  "non_thinking_general": {"temperature": 0.7, "top_p": 0.80, "top_k": 20, "min_p": 0.0, "presence_penalty": 1.5, "repetition_penalty": 1.0},
  "thinking_creative": {"temperature": 0.7, "top_p": 0.95, "min_p": 0.0, "repetition_penalty": 1.05},
  "dspark_quantized_safe": {"spec_type": "draft-dspark", "spec_draft_n_max": 2, "spec_draft_p_min": 0},
  "agent_protocol_guards": {
    "vllm_sglang_parsers": "--tool-call-parser minicpm5 --reasoning-parser qwen3",
    "coding_min_max_tokens": 16384,
    "anthropic_echo_rule": "Strip whitespace-only text blocks while preserving thinking and tool_use blocks"
  }
}
EOF
  LAUNCHER_CREATED="true"
  PRESETS_CREATED="true"
fi

if (( APPLY_OLLAMA == 1 )); then
  mkdir -p "$CPM_DIR"
  cat > "${CPM_DIR}/ollama-override.conf" <<'EOF'
[Service]
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_KV_CACHE_TYPE=q8_0"
EOF
  OLLAMA_CONF_CREATED="true"
fi

if (( SCAFFOLD_AGENT == 1 )); then
  AGENT_DIR="${TARGET_DIR}/.claude/agents"
  mkdir -p "$AGENT_DIR"
  cat > "${AGENT_DIR}/minicpm5-local-worker.md" <<EOF
---
name: minicpm5-local-worker
description: Local MiniCPM5-15B-A2.5B Ubuntu 26.04 execution & protocol guard profile
---
- Local endpoint: \`http://localhost:8080/v1\` (llama.cpp) or \`http://localhost:8000/v1\` (vLLM/SGLang)
- Always launch vLLM/SGLang with \`--tool-call-parser minicpm5 --reasoning-parser qwen3\`.
- Always pass \`--min-p 0\` to \`llama-server\`; use \`presence_penalty=1.5\` when thinking is disabled.
- Set \`max_tokens >= 16384\` for coding tasks and preserve historical thinking blocks.
EOF
  AGENT_SCAFFOLDED="true"
fi

# 5. Output
if (( JSON_MODE == 1 )); then
  cat <<EOF
{
  "os": "Ubuntu 26.04",
  "ram_gb": ${RAM_GB},
  "gpu": "${GPU_NAME}",
  "vram_gb": ${VRAM_GB},
  "free_disk_gb": ${FREE_DISK_GB},
  "tier": "${TIER}",
  "recommended_gguf": "${REC_GGUF}",
  "recommended_vllm": "${REC_VLLM}",
  "recommended_litert": "${REC_LITERT}",
  "estimated_download_gb": ${DL_GB},
  "traps": {
    "disk_space_warning": ${DISK_WARN},
    "llama_server_found": ${LLAMA_FOUND},
    "ollama_found": ${OLLAMA_FOUND},
    "litert_lm_found": ${LITERT_FOUND},
    "transformers_5_25_ready": ${TRANSFORMERS_OK},
    "ollama_kv_bloat_trap": ${OLLAMA_KV_BLOAT_TRAP},
    "stale_base_url_trap": ${STALE_BASE_URL_TRAP}
  },
  "actions": {
    "launcher_created": ${LAUNCHER_CREATED},
    "presets_created": ${PRESETS_CREATED},
    "ollama_override_created": ${OLLAMA_CONF_CREATED},
    "agent_scaffolded": ${AGENT_SCAFFOLDED},
    "backup_file": "${BACKUP_FILE}"
  }
}
EOF
else
  echo ""
  echo "=== Summary & Next Steps ==="
  echo "Hardware Tier  : ${TIER} (RAM ${RAM_GB} GB / VRAM ${VRAM_GB} GB)"
  echo "Traps Detected : ollama_kv_bloat=${OLLAMA_KV_BLOAT_TRAP}, transformers_ok=${TRANSFORMERS_OK}"
  echo "Launchers      : ${CPM_DIR}/launch-minicpm5-{thinking,fast,vllm}.sh"
fi

人工手动执行命令(Ubuntu 终端运行):

chmod +x ./minicpm5_local_toolkit_ubuntu2604.sh && bash ./minicpm5_local_toolkit_ubuntu2604.sh

3. macOS 27 专版(原生 Zsh:minicpm5_local_toolkit_macos27.zsh)

#!/usr/bin/env zsh
# ==============================================================================
# MiniCPM5-15B-A2.5B Local Diagnostic, MLX-VLM / LiteRT Guard & Auto-Config — macOS 27
# Zero third-party dependencies (macOS built-in zsh, sysctl, df, awk, grep, sed)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: zsh ./minicpm5_local_toolkit_macos27.zsh
#   Agent Automated:   zsh ./minicpm5_local_toolkit_macos27.zsh --auto --json --apply --scaffold-agent --target .
# ==============================================================================
set -euo pipefail

AUTO=0
JSON_MODE=0
APPLY=0
APPLY_OLLAMA=0
SCAFFOLD_AGENT=0
TARGET_DIR="."

while [[ $# -gt 0 ]]; do
  case "$1" in
    --auto) AUTO=1; shift ;;
    --json) JSON_MODE=1; shift ;;
    --apply) APPLY=1; shift ;;
    --apply-ollama) APPLY_OLLAMA=1; shift ;;
    --scaffold-agent) SCAFFOLD_AGENT=1; shift ;;
    --target) TARGET_DIR="${2:-.}"; shift 2 ;;
    -h|--help)
      cat <<'EOF'
Usage: zsh minicpm5_local_toolkit_macos27.zsh [options]
  --auto            Non-interactive mode for AI Agents
  --json            Emit sanitized JSON output
  --apply           Generate ~/.minicpm5-local launchers & sampling presets
  --apply-ollama    Export Ollama FlashAttention + q8_0 KV cache into ~/.zshrc
  --scaffold-agent  Write .claude/agents/minicpm5-local-worker.md in --target
  --target <dir>    Target workspace directory (default: .)
EOF
      exit 0
      ;;
    *) print -u2 -- "Unknown option: $1"; exit 1 ;;
  esac
done

# 1. Apple Silicon Unified Memory & Disk Detection (Sanitized)
ARCH="$(uname -m)"
MEM_BYTES="$(sysctl -n hw.memsize 2>/dev/null || echo 0)"
RAM_GB="$(awk -v b="$MEM_BYTES" 'BEGIN {printf "%.1f", b/1024/1024/1024}')"
CHIP_NAME="$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo 'Apple Silicon')"

mkdir -p "$TARGET_DIR" 2>/dev/null || true
FREE_DISK_KB="$(df -Pk "$TARGET_DIR" | awk 'NR==2 {print $4}')"
FREE_DISK_GB="$(awk -v k="${FREE_DISK_KB:-0}" 'BEGIN {printf "%.1f", k/1024/1024}')"

TIER="Tier-D (<16GB Tight)"
REC_GGUF="MiniCPM5-15B-A2.5B-Q4_K_M.gguf (tight; consider MiniCPM5-2B)"
REC_MLX="none (insufficient unified memory for 15B MLX + KV)"
REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (tight; free swap first)"
DL_GB="8.49"

if awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 32)}'; then
  TIER="Tier-A (32GB+ Unified)"
  REC_GGUF="MiniCPM5-15B-A2.5B-Q8_0.gguf (or BF16 27.97 GiB)"
  REC_MLX="openbmb/MiniCPM5-15B-A2.5B-MLX + DSpark"
  REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm or _int8.litertlm (Metal GPU)"
  DL_GB="14.87"
elif awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 22)}'; then
  TIER="Tier-B (24GB Unified)"
  REC_GGUF="MiniCPM5-15B-A2.5B-Q8_0.gguf (14.87 GiB) or Q4_K_M"
  REC_MLX="openbmb/MiniCPM5-15B-A2.5B-MLX (via mlx-vlm@main)"
  REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB, Metal GPU)"
  DL_GB="14.87"
elif awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 15)}'; then
  TIER="Tier-C (16GB Unified)"
  REC_GGUF="MiniCPM5-15B-A2.5B-Q4_K_M.gguf (8.49 GiB, num_ctx 8192)"
  REC_MLX="openbmb/MiniCPM5-15B-A2.5B-MLX (target only, skip DSpark)"
  REC_LITERT="MiniCPM5-15B-A2.5B_mixed.litertlm (8.28 GB GPU only; NEVER int8/int4)"
  DL_GB="8.49"
fi

DISK_WARN="false"
if awk -v d="$FREE_DISK_GB" 'BEGIN {exit !(d < 25)}'; then
  DISK_WARN="true"
fi

# 2. Local Runtime & Day-1 Trap Scan
LLAMA_FOUND="false"; command -v llama-server >/dev/null 2>&1 && LLAMA_FOUND="true"
OLLAMA_FOUND="false"; command -v ollama >/dev/null 2>&1 && OLLAMA_FOUND="true"
LITERT_FOUND="false"; command -v litert-lm >/dev/null 2>&1 && LITERT_FOUND="true"

MLX_VLM_READY="false"
MLX_LM_TRAP="false"
TRANSFORMERS_OK="false"
if command -v python3 >/dev/null 2>&1; then
  python3 -c "from mlx_vlm.models.minicpm5_moe import Model" >/dev/null 2>&1 && MLX_VLM_READY="true"
  python3 -c "import mlx_lm" >/dev/null 2>&1 && [[ "$MLX_VLM_READY" == "false" ]] && MLX_LM_TRAP="true"
  python3 -c "import transformers, packaging.version as v; exit(0 if v.parse(transformers.__version__) >= v.parse('5.25.0') else 1)" >/dev/null 2>&1 && TRANSFORMERS_OK="true"
fi

OLLAMA_KV_BLOAT_TRAP="false"
if [[ "$OLLAMA_FOUND" == "true" ]]; then
  if [[ "${OLLAMA_FLASH_ATTENTION:-}" != "1" || -z "${OLLAMA_KV_CACHE_TYPE:-}" ]]; then
    OLLAMA_KV_BLOAT_TRAP="true"
  fi
fi

STALE_BASE_URL_TRAP="false"
if [[ -n "${OPENAI_BASE_URL:-}" && ! "${OPENAI_BASE_URL}" =~ localhost && ! "${OPENAI_BASE_URL}" =~ 127\.0\.0\.1 ]]; then
  STALE_BASE_URL_TRAP="true"
fi

# 3. Interactive Human Prompt
if (( AUTO == 0 )); then
  print -P "%B=== MiniCPM5-15B-A2.5B macOS 27 Local Triage ===%b"
  print -r -- "Unified Memory Tier: ${TIER} (${RAM_GB} GB) | Free Disk: ${FREE_DISK_GB} GB"
  print -r -- "GGUF Pick:           ${REC_GGUF}"
  print -r -- "Apple Silicon MLX:   ${REC_MLX} (requires mlx-vlm@main, NOT mlx-lm!)"
  print -r -- "LiteRT-LM Pick:      ${REC_LITERT}"
  if (( APPLY == 0 )); then
    read -r "ans_apply?Generate local MiniCPM5 launchers & presets in ~/.minicpm5-local? [Y/n] "
    if [[ -z "$ans_apply" || "$ans_apply" == [Yy]* ]]; then APPLY=1; fi
  fi
  if [[ "$OLLAMA_FOUND" == "true" && $APPLY_OLLAMA -eq 0 ]]; then
    read -r "ans_ol?Append Ollama FlashAttention + q8_0 KV cache exports to ~/.zshrc? [y/N] "
    if [[ "$ans_ol" == [Yy]* ]]; then APPLY_OLLAMA=1; fi
  fi
  if (( SCAFFOLD_AGENT == 0 )); then
    read -r "ans_ag?Scaffold local MiniCPM5 worker profile in target directory? [y/N] "
    if [[ "$ans_ag" == [Yy]* ]]; then SCAFFOLD_AGENT=1; fi
  fi
fi

# 4. Apply Configs Safely
CPM_DIR="${HOME}/.minicpm5-local"
LAUNCHER_CREATED="false"
PRESETS_CREATED="false"
OLLAMA_ENV_APPLIED="false"
AGENT_SCAFFOLDED="false"
BACKUP_FILE="none"

if (( APPLY == 1 )); then
  mkdir -p "$CPM_DIR"
  THINK_ZSH="${CPM_DIR}/launch-minicpm5-thinking.zsh"
  FAST_ZSH="${CPM_DIR}/launch-minicpm5-fast.zsh"
  MLX_ZSH="${CPM_DIR}/launch-minicpm5-mlxvlm.zsh"
  MODELFILE_PATH="${CPM_DIR}/Modelfile.minicpm5-q4km"
  if [[ -f "$THINK_ZSH" ]]; then
    BACKUP_FILE="${THINK_ZSH}.bak.$(date +%Y%m%d%H%M%S)"
    cp "$THINK_ZSH" "$BACKUP_FILE"
  fi

  cat > "$THINK_ZSH" <<'EOF'
#!/usr/bin/env zsh
set -euo pipefail
GGUF_PATH="${1:-$HOME/models/MiniCPM5-15B-A2.5B-Q4_K_M.gguf}"
exec llama-server -m "$GGUF_PATH" -a MiniCPM5-15B-A2.5B \
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja \
  --temp 1.0 --top-p 0.95 --min-p 0.0 --repeat-penalty 1.0
EOF
  chmod +x "$THINK_ZSH"

  cat > "$FAST_ZSH" <<'EOF'
#!/usr/bin/env zsh
set -euo pipefail
GGUF_PATH="${1:-$HOME/models/MiniCPM5-15B-A2.5B-Q4_K_M.gguf}"
exec llama-server -m "$GGUF_PATH" -a MiniCPM5-15B-A2.5B \
  --host localhost --port 8080 -ngl 99 -fa on -c 8192 --jinja \
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p 0.0 --presence-penalty 1.5 --repeat-penalty 1.0
EOF
  chmod +x "$FAST_ZSH"

  cat > "$MLX_ZSH" <<'EOF'
#!/usr/bin/env zsh
set -euo pipefail
# Must use mlx-vlm@main (PR #2866 + PR #2870), NOT mlx-lm!
export MODEL="${1:-openbmb/MiniCPM5-15B-A2.5B-MLX}"
exec python3 -m mlx_vlm.server --model "$MODEL" --port 8080
EOF
  chmod +x "$MLX_ZSH"

  cat > "$MODELFILE_PATH" <<'EOF'
FROM ./MiniCPM5-15B-A2.5B-Q4_K_M.gguf

TEMPLATE """{{- if .Messages -}}
{{- range .Messages -}}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end -}}
<|im_start|>assistant
{{ end -}}"""

PARAMETER stop "<|im_end|>"
PARAMETER stop "</s>"
PARAMETER temperature 1.0
PARAMETER top_p 0.95
PARAMETER num_ctx 8192
EOF

  cat > "${CPM_DIR}/sampling-presets.json" <<'EOF'
{
  "model": "MiniCPM5-15B-A2.5B",
  "thinking_general": {"temperature": 1.0, "top_p": 0.95, "min_p": 0.0, "repetition_penalty_if_loop": 1.05},
  "non_thinking_general": {"temperature": 0.7, "top_p": 0.80, "top_k": 20, "min_p": 0.0, "presence_penalty": 1.5, "repetition_penalty": 1.0},
  "thinking_creative": {"temperature": 0.7, "top_p": 0.95, "min_p": 0.0, "repetition_penalty": 1.05},
  "dspark_quantized_safe": {"spec_type": "draft-dspark", "spec_draft_n_max": 2, "spec_draft_p_min": 0},
  "agent_protocol_guards": {
    "vllm_sglang_parsers": "--tool-call-parser minicpm5 --reasoning-parser qwen3",
    "coding_min_max_tokens": 16384,
    "anthropic_echo_rule": "Strip whitespace-only text blocks while preserving thinking and tool_use blocks"
  }
}
EOF
  LAUNCHER_CREATED="true"
  PRESETS_CREATED="true"
fi

if (( APPLY_OLLAMA == 1 )); then
  ZSHRC="${HOME}/.zshrc"
  touch "$ZSHRC"
  if ! grep -q "OLLAMA_FLASH_ATTENTION" "$ZSHRC"; then
    cat >> "$ZSHRC" <<'EOF'

# MiniCPM5-15B-A2.5B Metal KV Cache Guard
export OLLAMA_FLASH_ATTENTION=1
export OLLAMA_KV_CACHE_TYPE=q8_0
EOF
  fi
  export OLLAMA_FLASH_ATTENTION=1
  export OLLAMA_KV_CACHE_TYPE=q8_0
  OLLAMA_ENV_APPLIED="true"
  OLLAMA_KV_BLOAT_TRAP="false"
fi

if (( SCAFFOLD_AGENT == 1 )); then
  AGENT_DIR="${TARGET_DIR}/.claude/agents"
  mkdir -p "$AGENT_DIR"
  cat > "${AGENT_DIR}/minicpm5-local-worker.md" <<EOF
---
name: minicpm5-local-worker
description: Local MiniCPM5-15B-A2.5B Apple Silicon execution & protocol guard profile
---
- Local endpoint: \`http://localhost:8080/v1\`
- Apple Silicon MLX runtime: use \`mlx-vlm\` main branch (PR #2866/#2870), never \`mlx-lm\`.
- LiteRT-LM runtime: use \`MiniCPM5-15B-A2.5B_mixed.litertlm\` on Metal GPU (never \`int4\` or Mac CPU \`mixed\`).
- Coding agent budget: set \`max_tokens >= 16384\`, keep \`--min-p 0\`, and echo historical thinking blocks.
EOF
  AGENT_SCAFFOLDED="true"
fi

# 5. Output
if (( JSON_MODE == 1 )); then
  cat <<EOF
{
  "os": "macOS 27",
  "arch": "${ARCH}",
  "chip": "${CHIP_NAME}",
  "unified_memory_gb": ${RAM_GB},
  "free_disk_gb": ${FREE_DISK_GB},
  "tier": "${TIER}",
  "recommended_gguf": "${REC_GGUF}",
  "recommended_mlx": "${REC_MLX}",
  "recommended_litert": "${REC_LITERT}",
  "estimated_download_gb": ${DL_GB},
  "traps": {
    "disk_space_warning": ${DISK_WARN},
    "llama_server_found": ${LLAMA_FOUND},
    "ollama_found": ${OLLAMA_FOUND},
    "litert_lm_found": ${LITERT_FOUND},
    "mlx_vlm_minicpm5_ready": ${MLX_VLM_READY},
    "mlx_lm_without_mlx_vlm_trap": ${MLX_LM_TRAP},
    "transformers_5_25_ready": ${TRANSFORMERS_OK},
    "ollama_kv_bloat_trap": ${OLLAMA_KV_BLOAT_TRAP},
    "stale_base_url_trap": ${STALE_BASE_URL_TRAP}
  },
  "actions": {
    "launcher_created": ${LAUNCHER_CREATED},
    "presets_created": ${PRESETS_CREATED},
    "ollama_env_applied": ${OLLAMA_ENV_APPLIED},
    "agent_scaffolded": ${AGENT_SCAFFOLDED},
    "backup_file": "${BACKUP_FILE}"
  }
}
EOF
else
  print -r -- ""
  print -P "%B=== Summary & Next Steps ===%b"
  print -r -- "Unified Memory : ${RAM_GB} GB (${CHIP_NAME}) -> ${TIER}"
  print -r -- "Traps Detected : mlx_lm_trap=${MLX_LM_TRAP}, ollama_kv_bloat=${OLLAMA_KV_BLOAT_TRAP}, transformers_ok=${TRANSFORMERS_OK}"
  print -r -- "Launchers      : ${CPM_DIR}/launch-minicpm5-{thinking,fast,mlxvlm}.zsh"
  print -r -- "Agent Guide    : Pass --min-p 0 for llama-server; never use LiteRT int4 or Mac CPU mixed."
fi

人工手动执行命令(macOS 终端运行):

chmod +x ./minicpm5_local_toolkit_macos27.zsh && zsh ./minicpm5_local_toolkit_macos27.zsh

5.2 方法二:交给 AI Agent 全自动配置(直接复制下方 Prompt)

如果你平时已经习惯用 Claude Code、Codex CLI、MiniMax Code 或 Antigravity 协同开发,完全不需要自己去终端里一步步按回车确认。把对应系统的脚本保存到当前工作目录后,直接把下面这段提示词发给你的 Agent,它会以非交互模式自动体检、输出脱敏 JSON 报告、生成本地启动脚本并建立专属本地 Worker 档案:

请根据当前操作系统执行对应的零依赖 MiniCPM5-15B-A2.5B 本地体检与配置脚本:
- Windows 11: powershell -ExecutionPolicy Bypass -File .\minicpm5_local_toolkit_windows11.ps1 -Auto -Json -Apply -ApplyOllama -ScaffoldAgent -Target .
- Ubuntu 26.04: bash ./minicpm5_local_toolkit_ubuntu2604.sh --auto --json --apply --apply-ollama --scaffold-agent --target .
- macOS 27: zsh ./minicpm5_local_toolkit_macos27.zsh --auto --json --apply --apply-ollama --scaffold-agent --target .

执行完毕后请帮我核验以下 5 项:
1. 确认 disk_space_warning 为 false,并根据 tier 与 recommended_gguf / recommended_litert 给出最适合当前机器的下载与启动命令(严禁推荐 LiteRT int4 与 16GB 机器跑 LiteRT int8);
2. 若在 macOS 上发现 mlx_lm_without_mlx_vlm_trap 为 true,立即提示改用 mlx-vlm main 分支(PR #2866/#2870),不要使用 mlx-lm;
3. 检查 ollama_kv_bloat_trap 与 stale_base_url_trap 状态,如写入了 ~/.zshrc 或生成了 ollama-override.conf,给出立即生效命令,并提醒 stock Ollama 低于 PR #32644 需替换 llama-server 引擎;
4. 检查 ~/.minicpm5-local 下已生成 Thinking 与 Fast 双模式启动器及 sampling-presets.json,确认内置 --min-p 0 与非思考模式 presence_penalty=1.5;
5. 确认当前工作区已生成 .claude/agents/minicpm5-local-worker.md,方便后续编程任务路由到本地 localhost 服务。

六、高频 Q&A:关于 MiniCPM5-15B-A2.5B 你最关心的 7 个问题

Q1:只有 16GB 内存的轻薄本或 Mac,到底选 GGUF、MLX 还是 LiteRT?

16GB 机器最稳妥的两个选择是 MiniCPM5-15B-A2.5B-Q4_K_M.gguf(8.49 GiB) 或 MiniCPM5-15B-A2.5B_mixed.litertlm(8.28 GB)。如果用的是 Apple Silicon Mac(16GB 统一内存),建议把上下文控制在 8192 并配合 q8_0 KV 缓存(或跑 LiteRT mixed --backend gpu,实测 M5 上有 45.5 tok/s)。千万别在 16GB 电脑上硬塞 15.08 GB 的 LiteRT int8,也别图省事选 LiteRT int4。

Q2:为什么我用 Ollama 拉不到,或者一运行就报 unknown model architecture: 'minicpm5_moe'?

因为 minicpm5_moe 是在 2026 年 11 月 29 日才并入 llama.cpp PR #32644(e18d1b21 / b12847)的。如果你的 Ollama 发行版打包的是旧内核(例如 0.40.19 及更早版本),要么升级到包含该提交的新版 Ollama,要么按照官方 ollama.md 指南自己编译静态版 llama-server 替换 Ollama 目录下的内嵌引擎(记得先备份 llama-server.orig)。

Q3:为什么明明是纯文本大模型,Mac 用户却要装 mlx-vlm 而不是 mlx-lm?

这是 OpenBMB 官方明确记录的路线选择:openbmb/MiniCPM5-15B-A2.5B-MLX(affine 4-bit, group_size=128)的架构加载器和 DSpark 投机解码器全部合进了 Neywa-Labs/mlx-vlm 的 main 分支(PR #2866 与 PR #2870)。老版本 mlx-vlm 0.8.2 和 mlx-lm 都没有这个实现。如果跑完之后聊天正文里露出了 XML 工具标签,检查一下 /health 里的 loaded_tool_parser 是否为 minicpm5(需要 PR #2870)。

Q4:iPhone 上怎么体验传说中「3GB 内存跑 15B 模型」的预取路由?

安卓和鸿蒙版 App 暂未支持该模型,目前 iOS 端(iOS 16+,建议 8GB 以上内存,12GB 体验最佳,预留 10GB 存储空间)可以通过官方 TestFlight 安装 MiniCPM-V Demo,在设置里选择下载 MiniCPM5-15B-A2.5B-Q3_gud-LCO-GGUF(约 6.8 GB),推理模式保持默认的 Memory saver 并开启 Expert predictor,即可复现约 3.1 GB 峰值内存、30 tok/s 的端侧体验。

Q5:为什么官方特意提醒多轮对话要「把历史思考 <think> 回传回去」?不怕浪费上下文吗?

很多人以为把上一轮的 <think>...</think> 删掉能省 Token,但实际上在多轮工具调用与长程 Agent 任务里这么做会带来两个坏处:第一,模型失去上一轮的计划推理脉络,容易重复调同一个工具或走偏;第二,删改历史消息会直接破坏 Prefix KV Cache(RadixCache)前缀命中,导致每一轮都要从头重算 Prefill!MiniCPM5 拥有 32Q:2KV 的极省缓存结构和 512K 上下文窗口,保留历史思考反而总耗时更短、更稳。

Q6:除了官方提供的 GGUF,还能自己用普通软件转 int4 量化吗?

强烈建议先用官方放出的量化版(GGUF Q4_K_M / Q8_0、LCO-GGUF、GPTQ、MLX 4-bit、LiteRT mixed)。从 LiteRT 官方 NLL 实测就能看出,MoE 模型对「非专家线性层(注意力和门控路由)」极其敏感——把路由和线性层一刀切压成 4-bit 会导致 NLL 从 1.414 恶化到 4.848。非要自己压 Q4_K_M,务必先用 llama-imatrix 跑 ~7M Token 校准重要性矩阵后再量化。

Q7:本地显卡或内存实在带不动,有零部署的在线免费试玩或 API 吗?

有的。OpenBMB 官方在 Hugging Face Space 提供了在线演示 openbmb/MiniCPM5-15B-A2.5B-Demo,同时也上线了「MiniCPM 端侧开源模型开放平台」(platform.modelbest.cn),申请 API Key 后把 Base URL 指向 https://api.modelbest.cn/v1、模型名填 MiniCPM5-15B-A2.5B,即可用标准 OpenAI SDK 直接调用。


参考资料与官方信源

评论

使用 GitHub 登录后即可评论,中英文版本共用同一讨论。 在 GitHub 上参与讨论

本文阅读量 --