Upload 35 files
Browse filesFiles changed (36)
- .gitattributes+1
- .gitignoreAdded+8
- AMOEBA_PAPER_DRAFT.docxAdded
- AMOEBA_PAPER_DRAFT.pdfAdded+3
- AMOEBA_PAPER_DRAFT.texAdded+731
- Amoeba-0.3B/LICENSEAdded+21
- Amoeba-0.3B/README.mdAdded+179
- Amoeba-0.3B/halt_heads.ptAdded+3
- Amoeba-0.3B/infer_with_gate.pyAdded+112
- Amoeba-0.6B/LICENSEAdded+21
- Amoeba-0.6B/README.mdAdded+177
- Amoeba-0.6B/halt_heads.ptAdded+3
- Amoeba-0.6B/infer_with_gate.pyAdded+112
- Amoeba-1B/LICENSEAdded+21
- Amoeba-1B/README.mdAdded+177
- Amoeba-1B/amoeba_da_infer.pyAdded+89
- Amoeba-1B/halt_heads.ptAdded+3
- Amoeba-1B/infer_with_gate.pyAdded+112
- Amoeba-1B/medusa_chat.ptAdded+3
- Amoeba-2B/LICENSEAdded+21
- Amoeba-2B/README.mdAdded+181
- Amoeba-2B/amoeba_da_infer.pyAdded+89
- Amoeba-2B/halt_heads.ptAdded+3
- Amoeba-2B/infer_with_gate.pyAdded+112
- Amoeba-2B/medusa_chat.ptAdded+3
- DOWNLOAD.mdAdded+10
- HF_MODEL_CARD_TEMPLATE.mdAdded+58
- LICENSEAdded+201
- MANIFEST.jsonAdded+155
- README.md+93-3
- README_legacy_earlyexit.mdAdded+373
- README_zh.mdAdded+83
- README_zh_legacy.mdAdded+320
- _LICENSES/APACHE-2.0.txtAdded+201
- _LICENSES/LICENSE_NOTE.mdAdded+68
- _LICENSES/MIT.txtAdded+21
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textAMOEBA_PAPER_DRAFT.pdf filter=lfs diff=lfs merge=lfs -text
12345678# Model weights (safetensors) are hosted on HuggingFace; see DOWNLOAD.md*.safetensors**/full_model/
# Abandoned early-exit halt heads are NOT part of the release (16 negative experiments)halt_heads.pt
# Draft heads (medusa_chat.pt) ARE included: needed to reproduce Amoeba-DA123version https://git-lfs.github.com/spec/v1oid sha256:f54ba50c83d9b02608920b213bcb7207820228e0ed5bf201a8440e8c411e0915size 114091123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath,amssymb}
\usepackage{booktabs}
\usepackage{geometry}
\geometry{left=2.2cm,right=2.2cm,top=2.2cm,bottom=2.2cm}
\usepackage{url}
\usepackage{hyperref}
\hypersetup{colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue}
\usepackage{enumitem}
\title{\textbf{Amoeba: From Early Exit to Verified Speculative Decoding\\
\large and Dynamic Loop Routing}\\
{\large A Systematic Empirical Study of Dynamic Computation in Small and Loop-Structured Language Models}}
\author{Weikai Yue, Hy 4 flash}
\date{Independent research report --- Draft v0.2 --- 2026-11-24}
\begin{document}
\maketitle
\begin{center}
\textit{All released models: Apache-2.0 \quad $\cdot$ \quad Single-GPU (RTX 4080S 32GB) research}
\end{center}
\begin{abstract}
We set out to build \emph{Amoeba}, a family of small language models with dynamic activation.
We first tested token-level early exit (halt heads, LayerSkip-style layer dropout, CALM-style
calibration) on MiniCPM5-2B: sixteen experiments showed the route is structurally infeasible on
this 42-layer deep-and-narrow GQA model (last two layers alone contribute $\sim$1.3 nats CE;
halt-head calibration fails at 80\% correctness), with a $\sim$1.16$\times$ structural ceiling.
We therefore reframed dynamic computation as \emph{verified speculative decoding}
(Amoeba-DA): $K$ parallel bottleneck draft heads predict future tokens from one cached hidden
state and the frozen base model verifies all candidates in one batched forward. Rather than
claiming bit-exact losslessness, we evaluate what matters in practice: \emph{downstream capability
preservation}. On MiniCPM5-2B, Amoeba-DA gives \textbf{2.015$\times$} speedup (26.6 to 53.6
tok/s, single-process measurement) while on 79 objective QA questions baseline accuracy is
91.14\% and Amoeba accuracy 93.67\%, with \textbf{zero regressions} (no question flipped from
correct to incorrect) and ROUGE-L 0.94. Token-level agreement with greedy is 0.734 -- the
differences are reasoning-trace length and paraphrase, not answer correctness. MiniCPM5-1B
gives 1.30$\times$ with the same protocol. Our central empirical finding is that the benefit
is \emph{architecture- and context-dependent}: on sliding-window hybrids (Gemma-4-E4B)
batched verification is numerically non-associative (hidden-state divergence accumulates over
42 layers) and agreement collapses, though capability is preserved; on MoE with KDA/MLA
(Ling-3.0-tiny) recurrent cache state blocks standard verification rollback; and the advantage
concentrates in short context because draft heads are trained on short on-policy corpora.
All Qwen-family speedups are WITHDRAWN after their verification engine proved incompatible.
In parallel we found an orthogonal mechanism: dynamic loop-depth routing on SenseNova-Loop-9B
gives 45\% speedup at 0.04 nats CE cost -- a quality-for-speed trade-off distinct from
speculative decoding. All reported speedups use a Python-bound HuggingFace \texttt{generate}
harness (27 tok/s for 2B); the same GPU under vLLM reaches 64 tok/s single-prompt or
$\sim$640--1280 tok/s batched, and our draft heads are bound to HF because they need hidden
states vLLM does not expose. To test whether the mechanism survives a real serving stack, we
evaluated vLLM's built-in n-gram speculative decoding on the same model: it gives
\textbf{1.806$\times$} (640$\to$1156 tok/s), so speculative decoding remains effective under a
production framework; adapting our draft heads to vLLM is future work. We release models (Apache-2.0), draft heads, scripts and the
full negative-result record.
\end{abstract}
\noindent\textbf{Keywords:} dynamic activation, early exit, speculative decoding, Medusa,
loop routing, tool calling, small language models, consumer hardware.
\section{Introduction}
Local language models (0.3--8B) are increasingly deployed as on-device assistants and coding
agents, where inference latency is the binding constraint. Dynamic computation --- spending
more compute on hard inputs and less on easy ones --- promises lower latency without retraining
the base model. The dominant recipe in the literature is token-level early exit: attach a halt
head after each layer, train with layer dropout and early-exit losses, and decide per token
whether to stop. This project started by implementing exactly that recipe (LayerSkip-style
layer dropout, CALM-style confidence calibration, entropy-regularized halt losses).
This report documents (i) why the recipe fails on the target architecture, (ii) how we replaced
it with a verification-based scheme that works, (iii) the boundary conditions we measured
across four model sizes plus an 8B dense model, and (iv) a separate, orthogonal
dynamic-computation mechanism on loop-structured models that we identify as the strongest
methodological lead. Throughout, we report negative and abandoned results in the same detail
as positive ones.
\subsection{Contributions}
\begin{enumerate}[leftmargin=*]
\item A systematic negative-result study of token-level early exit on a 42-layer GQA model
(16 experiments), with a cost model explaining the $\sim$1.16$\times$ structural ceiling (\S3).
\item A verified dynamic-activation method (Amoeba-DA) based on parallel draft heads with
batched verification, evaluated by \emph{downstream capability} rather than bit-exact
agreement: 2.015$\times$ speedup with zero accuracy regressions on 79 objective
questions (\S4, \S4.5).
\item An empirical boundary map of when verification-based acceleration works: full-attention
dense models succeed, sliding-window hybrids suffer numerical non-associativity, and
MoE/KDA cache semantics block verification rollback (\S4.6).
\item An empirical demonstration that on-policy, model-generated data dominates draft-head
quality at very low data budgets: replacing an external corpus with self-generated chat
raised $\alpha_2$ from 0.138 to 0.469 and nearly doubled speedup, using only
$\sim$500 samples / $\sim$30K tokens (\S4.2). We also identify short-context training
as the reason the advantage concentrates at short context (\S4.7, \S11).
\item An honest withdrawal of all Qwen-family speedups after their verification engine proved
incompatible with the model's KV cache (\S4.3, \S9).
\item A preliminary but methodologically distinct study of dynamic loop routing on a
loop-structured LLM, where the token itself decides the number of loop iterations (\S6).
\item A unified tool-use post-training recipe covering four base models and two chat-template
families, with an honest capability comparison (\S7).
\item A transparent account of what did not work: early exit, math CoT SFT, draft heads on
small models, noisy corpora, and a retracted speed measurement (\S9).
\item A careful positioning relative to concurrent work, in particular JetSpec (Hu et al.,
2026), including an explicit independence statement (\S8).
\end{enumerate}
\section{Background and Setup}
\subsection{Base models}
\begin{table}[h]
\centering
\begin{tabular}{lccccccc}
\toprule
Model & Layers & Hidden & Attention & Vocab & Context & License\\
\midrule
MiniCPM5-2B & 42 & 2048 & GQA 16Q/2KV & 130,560 & 131,072 & Apache-2.0\\
MiniCPM5-1B & 24 & 1536 & GQA 16Q/2KV & 130,560 & 131,072 & Apache-2.0\\
Qwen3-0.6B & 28 & 1024 & GQA 16/8 & 151,936 & 40,960 & Apache-2.0\\
MNN-Pocket-0.3B & 28 & 896 & GQA 14/2 & 65,536 & 40,960 & Apache-2.0\\
Qwen3-8B (study) & 36 & 4096 & GQA 32/8 & 151,936 & 40,960 & Apache-2.0\\
SenseNova-Loop-9B (study) & 32 phys. & 4096 & hybrid linear & $\sim$248K & --- & research\\
\bottomrule
\end{tabular}
\caption{Base models. The last two rows are study-only targets.}
\end{table}
MiniCPM5 uses the standard \texttt{LlamaForCausalLM} architecture ($\text{rope\_theta}=5\times10^6$),
so no custom kernels are needed. The official chat template was absent from local tokenizers
and was recovered from GGUF model-card metadata.
\subsection{Hardware and measurement constraints}
All training and inference ran on a single RTX 4080S 32GB (58GB system RAM). Decoding with
HuggingFace \texttt{generate} is CPU/Python-bound ($\sim$100\% CPU, $\sim$3\% GPU), so
wall-clock numbers are relative to that harness. vLLM 0.11 is ABI-incompatible with torch
2.15+cu132; all timings therefore use HF generate. A related investigation of
Qwen3.8-27B-FP8 required compiling \texttt{causal-conv1d} to avoid a reference fallback;
even then it ran at $\sim$1 tok/s and was abandoned. The relative speedups, not absolute
throughput, are the quantity of interest.
\section{Why Token-Level Early Exit Fails Here}
Let $\alpha(l)$ be the agreement between the argmax of layer $l$ and that of the final layer,
measured in teacher-forcing mode on the model's own generated replies. For MiniCPM5-2B:
\begin{table}[h]
\centering
\begin{tabular}{lccccccccc}
\toprule
Depth & 28 & 32 & 34 & 36 & 38 & 40 & 41 & 42\\
\midrule
$\alpha$ & .125 & .301 & .390 & .449 & .546 & .626 & .664 & 1.0\\
CE & 6.74 & 4.22 & 3.51 & 2.76 & 2.14 & 1.71 & 1.48 & \textbf{0.355}\\
\bottomrule
\end{tabular}
\caption{Layer-wise agreement and cross-entropy on self-generated chat data (2B).}
\end{table}
The last layer alone reduces CE by $\sim$1.3 nats. Combined with GQA's two KV heads, the
residual stream carries little redundancy: removing middle layers corrupts the representation,
while truncating before the final layers removes the readout interface.
This last-layer dominance is independently corroborated by BitSkip (Bhuvaneswaran \& Liu,
arXiv:2510.23766), which trains an 85M ternary-weight model from scratch with LayerSkip-style
early exit and reports per-layer exit perplexity of 12,418 at layer 10 but 216 at layer 11 --
a 57$\times$ drop attributable to the final layer alone. The two measurements differ in scale
(85M vs 2B), precision (ternary vs BF16), training (from scratch vs pretrained) and metric
(exit PPL vs CE contribution), yet agree that the final layer is a readout interface rather
than a redundant block. BitSkip attributes the cliff to insufficient representational maturity
at small scale and leaves 1B+ models to future work; our 2B result shows the effect survives
both the scale increase and the removal of quantization noise, so it is not purely a scale or
low-bit artifact. Both studies find that a shared LM head cannot serve as an intermediate exit
in this regime; BitSkip recommends per-layer exit heads, whereas we find that even with
dedicated halt heads early exit stays capped at $\sim$1.16$\times$ on the pretrained backbone,
as detailed below. We present this as cross-validation of a structural boundary, not as a
novelty claim.
\subsection{Sixteen experiments, all negative}
\begin{table}[h]
\centering
\small
\begin{tabular}{cll}
\toprule
\# & Approach & Result\\
\midrule
1 & Naive early exit (no gate, $\tau$=0.9) & Exits at layer 1; gibberish\\
2 & Confidence gate (conf$\geq$0.95) & 0.76--0.90$\times$ (slower)\\
3 & lm\_head-based gate & Gate costs 5$\times$1.25 layers $>$ layers saved\\
4 & Correctness-head gate & 0.87--1.09$\times$ plus repetition\\
5 & Layer dropout + per-layer CE (1200 steps) & CE drops, $\alpha$ unchanged (.466$\to$.469)\\
6 & Truncation at 38/42 & $\Delta$CE +1.62\\
7--9 & Skip middle layers / attention only & $\Delta$CE +5 to +10.7\\
10--11 & Skip MLP with oracle gate & $\Delta$CE +0.125--0.36\\
12--13 & Truncated draft + verify (d=36/41) & 0.40$\times$/0.84$\times$\\
14--15 & Parallel draft heads on CCI3 corpus & $\alpha_2$=0.138 $\to$ 1.13$\times$\\
16 & Halt-head calibration study & Fails calibration\\
\bottomrule
\end{tabular}
\caption{Early-exit / dynamic-depth experiment matrix (condensed).}
\end{table}
\noindent\textbf{Cost model.} Let $b=42+1.25$ (layers + lm\_head equivalent). A serial draft of
depth $d$ costs $(d+1.25)/b$ per drafted token; the acceptance probability $\alpha(d)$ never
exceeds that fraction, so serial self-speculation cannot pay for itself. Token-level early
exit has a theoretical ceiling of $\sim$1.16$\times$ even with a free gate.
\subsection{Halt-head calibration failure}
A per-layer halt head (MLP over hidden+1, seven candidate layers) was retrained on
self-generated chat data to BCE 0.0017. Calibration with corrected sigmoid semantics showed
that at layer 40 the high-confidence subset was only 80\% correct: even a 20\% target error
rate was unreachable, so no safe early-exit threshold exists. This is the central negative
finding: on deep-narrow GQA models the failure is structural, not a hyperparameter problem.
\section{Amoeba-DA: Verified Dynamic Activation}
\subsection{Principle and algorithm}
Instead of letting each token skip layers, we keep all layers for the committed token and use
$K$ parallel bottleneck heads to predict the next $K$ tokens from one cached hidden state:
\begin{equation}
h_k = h + W_2^{(k)}\,\mathrm{SiLU}\big(W_1^{(k)}\,\mathrm{float32}(h)\big),
\quad W_1\!:\!H\!\to\!512,\; W_2\!:\!512\!\to\!H\; (W_2 \text{ init}=0)
\end{equation}
\begin{equation}
\hat{c}_k = \arg\max\big(\mathrm{lm\_head}(\mathrm{norm}(h_k))\big),\quad k=1..K
\end{equation}
All heads share the frozen base lm\_head ($\sim$2M parameters each). The base verifies
$[\text{committed},\hat{c}_1,\dots,\hat{c}_K]$ in one forward; we accept the longest matching
prefix and emit the target's own next token at the first mismatch, so accepted tokens match
greedy decoding up to bf16 numerical differences.
The general speculative-decoding cost model is:
\begin{equation}
\mathbb{E}[\#\text{tokens}] = \frac{1-\alpha^{N+1}}{1-\alpha},\qquad
\text{Speedup} = \frac{1-\alpha^{N+1}}{(1-\alpha)(Nc+1)}
\end{equation}
Substituting our numbers: 2B ($\alpha\!\approx\!0.4,N\!=\!4,c\!\approx\!0.073$) gives
$\sim$2.09$\times$ (measured 2.02$\times$); 8B ($\alpha\!\approx\!0.3,c\!\approx\!0.07$) gives
$\sim$1.11$\times$ (measured 1.13$\times$). The model is predictive and the 8B result is not a bug.
\subsection{Training recipe}
Draft heads were trained on self-generated on-policy chat text with the backbone frozen
(AdamW, lr $6\times10^{-4}$). The single most important lever was data distribution. An external
web/news corpus (CCI3) sat at CE 3.7, roughly 10$\times$ away from the deployment distribution;
replacing it with model-generated chat (CE 1.31) raised $\alpha_2$ from 0.138 to 0.469 on 2B,
moving speedup from $\sim$1.13$\times$ to 2.04$\times$ --- a single change worth nearly
1$\times$. We emphasise that this is an empirical demonstration at a very small data budget
($\sim$500 samples, $\sim$30K on-policy tokens), not a claim of novelty: concurrent work
(JetSpec) independently reports that target-model-regenerated sequences outperform direct
corpus training. Our contribution is to show the effect reproduces on a single consumer GPU
with roughly three orders of magnitude less data. All released checkpoints were trained only
on self-generated data.
\subsection{Results and boundary curve}
\begin{table}[h]
\centering
\small
\begin{tabular}{lcccc}
\toprule
Model (attention) & $\alpha_2$ & Speedup & Capability & Status\\
\midrule
MiniCPM5-2B (full) & .469 & \textbf{2.015$\times$} (26.6$\to$53.6 tok/s) & 0 regressions / 79 & released\\
MiniCPM5-1B (full) & .462 & \textbf{1.30$\times$} & -- & released\\
Gemma-4-E4B (5:1 sliding) & .968 & 1.418$\times$ (batched) & agreement 0.4175; single-verify 96/96 & boundary\\
Ling-3.0-tiny (KDA/MLA MoE) & -- & not claimed & cache rollback blocked & boundary\\
Qwen3-8B / 0.6B / 0.3B & -- & WITHDRAWN & verification engine incompatible & retracted\\
\bottomrule
\end{tabular}
\caption{Amoeba-DA results under the capability criterion. Speedups for Qwen family are retracted:
their verification engine was incompatible with the model's KV cache (end-to-end $\alpha$ 0.04--0.07),
and the earlier 1.1--1.4$\times$ / 1.62$\times$ figures are not cited. Gemma's high teacher
$\alpha_2=0.968$ does not translate to batched-verification agreement because of numerical
non-associativity; single-token verification restores exact agreement but removes the speedup
(\S4.6). Timing uses the stable fast mode; shared-GPU measurements are bimodal and discarded.}
\end{table}
\noindent\textbf{Interpretation.} Speedup is governed by draft-target acceptance alignment and
relative readout cost, not model scale. On 0.3B/0.6B the lm\_head dominates compute and drafts
are less accurate, so verification costs more than it saves. On 8B the baseline is nearly as
fast as 2B (21.5--25 vs 27.1 tok/s) but acceptance is much lower (1.48 vs 2.61), collapsing the
gain to 1.1--1.4$\times$. We therefore make no ``bigger is faster/slower'' scaling claim.
\noindent\textbf{Tree verification and its limits.} We also experimented with tree verification
on 8B (budget 16, best-first expansion, one-pass tree attention); the final confirmed speedup
remained 1.1--1.4$\times$. The often-cited 4--9$\times$ figures for this class of method come
from much larger training budgets and H100-class hardware.
\subsection{Capability evaluation (the primary criterion)}
\label{sec:capability}
We do \emph{not} claim bit-exact losslessness. Token-level agreement with greedy decoding is
0.734 on 2B (and collapses on Gemma's batched path, \S4.6); divergences occur at bf16 near-ties
and in reasoning-trace length. Instead we measure downstream capability on 79 deterministic
objective questions (33 math, 32 factual, 14 reasoning; 30 Chinese / 49 English) with regex
answer matching. On MiniCPM5-2B:
\begin{table}[h]
\centering
\begin{tabular}{lccc}
\toprule
Group (n) & Baseline & Amoeba & Change\\
\midrule
ALL (79) & 91.14\% & \textbf{93.67\%} & +2.5pp\\
Math (33) & 96.97\% & 96.97\% & 0\\
Fact (32) & 87.5\% & 90.6\% & +3.1pp\\
Reasoning (14) & 85.7\% & 92.9\% & +7.1pp\\
\bottomrule
\end{tabular}
\caption{2B capability: regressions = 0 (no question flipped correct$\to$incorrect),
improvements = 2, ROUGE-L = 0.940, token-overlap F1 = 0.948. The +2.5pp is within noise;
the meaningful result is the absence of any regression despite 0.734 token agreement.}
\end{table}
The gap between 0.734 token agreement and zero capability regressions shows that token-level
divergence is dominated by paraphrase and thinking-trace length, not by answer errors. We
therefore state our claim as \emph{capability-preserving acceleration}, strictly weaker than
losslessness and verified rather than assumed.
\subsection{Architecture boundary}
\label{sec:arch-boundary}
The benefit is governed by the attention architecture and cache semantics, not by parameter
count. Table~\ref{sec:capability} and the results table establish three regimes:
\begin{itemize}[leftmargin=*]
\item \textbf{Full-attention dense} (MiniCPM5-2B/1B): batched and single-token forward are
numerically identical (batch-single agreement 1.0); 2.015$\times$ / 1.30$\times$.
\item \textbf{Sliding-window hybrid} (Gemma-4-E4B, 5:1 sliding/global): a per-layer hidden-state
comparison shows batched-vs-single divergence from layer 0 (max abs diff 0.125),
accumulating to 0.75 by layer 42. Teacher $\alpha_2=0.968$ but batch-single agreement
0.9667 and end-to-end agreement 0.4175. Switching to single-token verification restores
96/96 exact agreement on all tested prompts but is 3.7$\times$ slower, eliminating the
gain. Attribution is numerical, not the attention mask or position encoding (mask and
explicit-position variants leave the divergence unchanged).
\item \textbf{MoE + KDA/MLA} (Ling-3.0-tiny, 18 KDA + 6 MLA layers): KDA stores recurrent and
short-convolution state per layer; the standard \texttt{cache.crop()} used for verification
rollback cannot restore it. We report this as a boundary rather than claim a speedup;
replay-based verification is left to future work.
\end{itemize}
\subsection{Context-length boundary}
\label{sec:ctx-boundary}
All draft heads are trained on short on-policy corpora (2B/Gemma: 24 blocks $\times$ $\sim$512
tokens; Ling: $24\times320$). At longer context the hidden-state distribution shifts and
$\alpha$ -- hence accepted length $\mathbb{E}\!\approx\!1/(1-\alpha)$ -- is expected to fall,
while KV-cache attention makes batched verification less ``free''. A speedup-vs-context-length
curve (128--8192 tokens) is reported in \S4.7; we do not claim the speedup generalizes to long
context, and we treat this as an explicit limitation (\S11).
\section{Alternative Dynamic-Computation Mechanisms}
\label{sec:alternatives}
The token-verification recipe of \S4 is only one way to trade computation for latency. We tested
three alternatives -- more draft heads, a different training objective, and predicting the KV cache
itself -- and report them here in full because the boundary they reveal is a central result.
\subsection{More draft heads (K=8)}
Since speedup grows with accepted length, the most obvious lever is to increase the number of
parallel heads from $K{=}4$ to $K{=}8$ on 2B, using the same corpus and recipe (3000 steps). The
first four heads are unchanged ($\alpha_{2..5}=.463/.349/.293/.241$ vs $.469/.348/.293/.240$),
confirming $K{=}4$ already exhausts the useful prediction depth. The added heads are weak and
monotonically degrading: $\alpha_6=.195,\ \alpha_7=.166,\ \alpha_8=.147,\ \alpha_9=.117$. Expected
accepted length \emph{fell} from 2.61 to 1.69 and predicted speedup from $2.02\times$ to $1.67\times$.
Draft--target divergence grows with offset; adding heads cannot raise acceptance. We therefore did
not run an end-to-end benchmark with $K{=}8$.
\subsection{Forward-KL distillation (V3)}
Hard-label cross-entropy trains a draft head to reproduce only the target's argmax token. JetSpec
(Hu et al., 2026) instead uses forward KL, matching the target's full next-token distribution; at
their budget (780K samples, 8$\times$H100) this yields high acceptance. We tested the same objective
on 2B: for conditioning hidden $h_t$ and offset $k$, the draft logits $d_k=\mathrm{lm\_head}(\mathrm{norm}(h_k))$
were trained with $\mathcal{L} = \frac{1}{K}\sum_k \mathrm{KL}(\mathrm{softmax}(t_k/T)\,\|\,\mathrm{softmax}(d_k/T))$,
where $t_k$ is the frozen target's logits at future position $t{+}k$ (available from the corpus's
stored final hidden states) and $T{=}1$. Training loss dropped from 2366 to 117, but the held-out
acceptance rate \emph{collapsed}: $\alpha_2$ fell from 0.469 to 0.020 (offsets 3--5: 0.038/0.046/0.063),
and expected accepted length from 2.61 to 1.02. The objective optimises full-distribution agreement
on a dispersed, multi-modal target distribution and thereby loses the argmax information that
drives speculative acceptance. This is a negative result for our low-data setting, not a refutation
of the objective in general: the published success relies on much larger data and a tree-structured
draft.
\subsection{Learned KV-cache prediction (V4)}
The most radical alternative skips \emph{layers} rather than decode steps. A small MLP predicts a
layer's $K,V$ from the previous hidden state; if accurate, the layer's attention projection and
cache write could be avoided. We built a 30,208-token on-policy corpus from the 2B model's own
answers and trained $2048\!\to\!512\!\to\!512$ heads for layers 21 and 40.
\noindent\textbf{Phase 1 -- substitution accuracy.} Replacing predicted $K,V$ for a single layer
on held-out text gives:
\begin{center}
\begin{tabular}{lccc}
\toprule
Substitution & $\Delta$CE (nats) & top-1 flip & \\
\midrule
baseline & 0.0000 & 0.0\% & \\
layer 21 only & +0.0228 & 7.06\% & \\
layer 40 only & $-$0.0195 & 7.31\% & \\
both 21+40 & +0.0109 & 9.72\% & \\
\bottomrule
\end{tabular}
\end{center}
These flips are well below our capability criterion, and CE is essentially unchanged, so the
approximation is tolerable. A direct attempt to predict the whole next-layer hidden $h_{l+1}$ failed
catastrophically (cosine 0.28 with the true hidden; CE 8.3, 88\% flips) because normalized MSE was
dominated by a few massive ``attention-sink'' channels; predicting the residual increment
$\Delta h = h_{l+1}-h_l$ and returning $h_l+\hat{\Delta}$ fixed this.
\noindent\textbf{Phase 2 -- chain skipping.} With residual-delta heads we skipped a contiguous
block of layers. Top-1 flips grow with chain length: 6.65\% (1 layer), 13.11\% (2), 26.81\% (4),
77.50\% (8); CE rises from 0.49 to 4.64. A two-layer chain (21--22) was the capability-preserving
operating point: on the 79-question QA set accuracy went from 91.14\% to 96.20\% (no drop), but
decode throughput was \textbf{0.973$\times$} and prefill \textbf{0.834$\times$} of baseline on an
exclusive GPU -- the method was \emph{slower}. The reason is a MACs audit: in this model the MLP
accounts for 73.4\% of a layer's cost while $K,V$ projections are only 2.2\%; skipping two layers
saves little, while the predictor MLPs and the writing of predicted KV cost more. Reaching
$1.5\times$ would require skipping 15--16 layers ($c\approx0.056$ per emulated layer), but 8-layer
chains already destroy capability. We therefore conclude that learned KV prediction is a
capability-preserving approximation without measured acceleration on this dense 2B model.
\noindent\textbf{Mechanism-level contribution.} Unlike verification-based speculation, KV
prediction is feed-forward: $h_l \to$ predictor $\to K,V_{l+1}$. There is no accept/reject branch,
no \texttt{cache.crop()}, no rollback. The three cache failures of \S4 -- Qwen verification/cache
incompatibility, Ling's non-croppable KDA recurrent state, and Gemma's sliding-window batched
desync -- are \emph{structurally avoided}. We state this as a mechanism property, not an empirical
result for those architectures (no Qwen/KDA smoke test was run). We claim no novelty for KV
reconstruction: LCKV, CLA, MiniCache, HShare, AttentionPredictor and KV-Direct are cited in \S8.
\subsection{Where the acceleration budget actually is}
An external algorithm audit (DeepSeek V4.1 Flash, used as a research assistant; all numbers below
were independently verified where noted) analysed the per-layer MACs: MLP gate/up/down 37.75M
(73.4\%), $q$/$o$ projections 4.19M each (8.2\% each), $k$/$v$ projections 0.52M each (1.0\% each),
attention scores $4096T$ (1.1\% at $T{=}128$, 8.2\% at $T{=}1$K). Three consequences follow.
(i) Predicting $K,V$ can save at most 2.2\% of a layer -- no path to $1.5\times$. (ii) Skipping
only attention saves 15--24\% per layer at short context, giving at most $1.18$--$1.27\times$;
$>1.5\times$ would need long context. (iii) Whole-layer emulation needs $S{=}15$--$16$ skipped
layers for $1.5\times$, far beyond the 2--4 layers that preserve capability. The audit also found
that adjacent-layer KV is essentially uncorrelated (cosine $\approx 0$, so cross-layer KV reuse is
invalid on a frozen model) and that the residual update has a low-rank shared structure (rank-32
captures 98.8\% of variance), suggesting that a future low-rank residual emulator, not KV prediction,
is the more promising layer-skipping direction. These findings are consistent with our own V4
measurements and reinforce the boundary in \S4.
\section{Dynamic Loop Routing: A Genuinely Different Axis}
SenseNova-Loop-9B has 32 physical layers, of which layers 4--28 execute twice (56 layer
computations at full depth). Unlike speculative decoding, loop routing changes how much
computation a single token receives: a confidence threshold decides whether a token exits
after one loop or continues to a second --- token-level dynamic depth in the original sense.
\begin{table}[h]
\centering
\begin{tabular}{lccc}
\toprule
Configuration & CE & Throughput & Note\\
\midrule
Static loop1 & higher & faster & quality loss\\
Static loop2 & 1.484 & 2.46 tok/s & full compute, best quality\\
Dynamic, threshold 1.5 & 1.522 & 3.56 tok/s & \textbf{45\% faster}, +0.04 CE\\
\bottomrule
\end{tabular}
\caption{Preliminary SenseNova-Loop-9B results (single GPU, validated run).}
\end{table}
The threshold is a controllable quality/speed knob: one scalar trades 0.04 nats of CE for
45\% throughput. We consider this the strongest methodological lead because it is orthogonal
to speculative decoding --- a system could route loop depth then verify drafts at the routed
depth. That combination and multi-model validation are left as future work.
\noindent\textit{Draft status.} The loop study rests on one model; we do not claim generality.
\section{Tool-Use Post-Training}
We generated synthetic tool-call dialogues for calculator, get\_weather, search, get\_time.
MiniCPM5 (no native tool template) used a hand-built \texttt{<|im\_start|>} system message;
Qwen3-family models used their native \texttt{<tool\_call>} template. LoRA (r=16, $\alpha$=32,
dropout 0.05) in bf16, merged into standalone checkpoints. The 0.6B recipe was reduced to 1
epoch at lr $5\times10^{-5}$ after a 2-epoch run overfit and produced empty replies.
\begin{table}[h]
\centering
\begin{tabular}{lccc}
\toprule
Model & Version & Tool-call success & Notes\\
\midrule
2B & v2 & 4/4 & direct-answer cases also correct\\
1B & v2 & 4/4 & ---\\
0.6B & v2 & 3/3 & 2-epoch v1 overfit; v2 fixed\\
0.3B & v1 & 3/3 & fixed invented-tool-name failure\\
\bottomrule
\end{tabular}
\caption{Tool-call accuracy on calculator / weather / time.}
\end{table}
A ReAct loop (\texttt{agent\_infer.py}) parses both Qwen-style tool calls and bare nested JSON
via a balanced-brace decoder. Tool prompts require the tool-definition system message.
\section{Related Work and Relationship to JetSpec}
\subsection{Lineage}
\begin{itemize}[leftmargin=*]
\item Speculative decoding (Leviathan et al., 2023; Chen et al., 2023): cheap draft verified
by the target with a lossless rule. Amoeba-DA is an instance of this family.
\item Medusa (Cai et al., 2024): parallel bottleneck draft heads --- direct ancestor of our design.
\item EAGLE/EAGLE-3 (Li et al., 2024, 2025); DFlash (Chen et al., 2026): better draft alignment.
\item Early exit: CALM (Schuster et al., 2022), LayerSkip (Elhoushi et al., 2024),
Mixture-of-Depths; our \S3 is a negative-result study in this tradition.
\item Cross-layer KV: LCKV (Wu \& Tu, ACL 2024), YOCO (Sun et al., 2024), Cross-Layer
Attention (Brandon et al., NeurIPS 2024), MLKV (2025) share or compress KV across
layers, typically requiring pretraining. MiniCache (NeurIPS 2024) merges adjacent KV;
HShare (ICLR 2025) shares critical-token indices. AttentionPredictor (NeurIPS 2025)
predicts attention scores, not KV tensors. KV-Direct (arXiv 2603.19664, 2026) proves
KV are deterministic projections of the residual stream (exact reconstruction) and
reports failure on sliding-window models -- consistent with our boundary finding.
Our V4 (\S5) is a frozen-model learned-emulator study with downstream capability
evaluation, and claims no novelty for KV reconstruction.
\end{itemize}
\noindent\textbf{License note.} LayerSkip code is CC-BY-NC and was not copied; we implemented its
ideas from the paper and used Apache-2.0 CALM as a reference. JetSpec is CC BY 4.0; we cite its
ideas and reuse no code or weights.
\subsection{Independence statement and comparison with JetSpec}
\noindent\textbf{Independent discovery.} The core idea of Amoeba-DA --- parallel draft heads on
a frozen target with batched exact verification --- was developed in our local experiments on
2026-11-22, before we became aware of JetSpec (Hu et al., arXiv:2606.18394v3, submitted
2026-06-25, UCSD / Hao AI Lab). We learned of JetSpec during a later literature survey. We
therefore do \emph{not} claim novelty for the draft-head-and-verify mechanism itself. JetSpec
was published first and reports substantially stronger results; we cite it as the state of the
art and position our work as complementary.
JetSpec trains a causal parallel draft head over fused hidden states from five target layers,
uses a tree-causal mask, constructs a tree under a 256-node budget, and verifies it in one
forward with a custom kernel; it reports up to 9.64$\times$ on MATH-500 with Qwen3-8B on H100,
trained on 780K regenerated samples on 8$\times$H100 (draft cost $c$=0.0085 at budget 16 vs our
$c\approx0.07$).
\begin{table}[h]
\centering
\small
\begin{tabular}{lll}
\toprule
Dimension & Amoeba-DA (this work) & JetSpec (Hu et al., 2026)\\
\midrule
Draft structure & 4 bottleneck MLPs, last hidden & 5-layer causal decoder, fused features\\
Verification & single linear chain, $K$=4 & whole tree, budget 16--256\\
Accepted length $\tau$ & 1.48 (8B) / 2.61 (2B) & up to 10.76\\
Draft cost $c$ & $\sim$0.07 & 0.0085 ($N$=16)\\
Training data & $\sim$30K self-generated tokens, 1$\times$4080S & 780K, 8$\times$H100\\
Objective & hard-label CE & forward-KL distillation\\
Reported 8B speedup & 1.1--1.4$\times$ & 4--9.64$\times$ (H100)\\
\bottomrule
\end{tabular}
\caption{Amoeba-DA versus JetSpec: difference of configuration and budget, not principle.}
\end{table}
\noindent\textbf{Our complementary contributions:} (i) systematic characterisation of why
early-exit dynamic depth fails before adopting verification; (ii) a minimal recipe
(consumer GPU, $\sim$30K tokens, $K$=4) making verification-based acceleration accessible;
(iii) a boundary curve across dense, hybrid-linear and loop architectures; (iv) dynamic loop
routing as an orthogonal dynamic-computation axis.
\section{Negative, Abandoned and Retracted Results}
\begin{enumerate}[leftmargin=*]
\item Token-level early exit: 16 experiments, all failing quality or speed (\S3).
\item Math CoT SFT: MATH stayed 0.70 while MMLU fell 0.42$\to$0.20 and HumanEval
0.6--0.9$\to$0.45. Discarded; no released model contains it.
\item Draft heads on 0.3B/0.6B: slower (0.36$\times$/0.60$\times$); not shipped.
\item CCI3 corpus: CE 3.7, $\sim$10$\times$ from deployment distribution; unused in releases.
\item Qwen3.8-27B-FP8: even after compiling \texttt{causal-conv1d}, $\sim$1 tok/s; abandoned.
\item Qwen family WITHDRAWN: a training-label offset bug was found and fixed, but end-to-end
acceptance stayed 0.04--0.07 even though teacher $\alpha_2$ reached 0.76. Crop, replay,
hidden-match and batch-single checks all failed to restore agreement; the verification
engine is incompatible with the Qwen KV cache. No Qwen speedup is cited.
\item Retracted measurement: early 8B run reported 1.62$\times$ with a depressed 8.1 tok/s
baseline (system load); not cited. All shared-GPU timings are bimodal (2B: 2.8 vs 26
tok/s; Gemma: 7/23/73 s per prompt; Ling: 1.2 vs 12 tok/s), so reported speedups use
only single-process stable-fast-mode measurements.
\item \textbf{vLLM engineering obstacles.} vLLM 0.11 wheels are built against torch 2.8+cu128
and failed to import under the main torch 2.15+cu132 environment with an undefined-symbol
error (\texttt{c10\_cuda\_check\_implementation}); downgrading the main environment would
have broken the compiled \texttt{fla}/\texttt{causal-conv1d} kernels, so we built an isolated
venv (torch 2.8+cu128) instead. Even then, a transformers-5.x tokenizer incompatibility
(\texttt{all\_special\_tokens\_extended} missing) required a monkey-patch before
\texttt{from vllm import LLM}, and several early smoke tests failed only because competing
GPU jobs left insufficient free VRAM for CUDA-graph capture. In an isolated venv the import,
model load and generation all work; these were environment issues, not method failures.
\item The $\sim$1.45$\times$ (45\%) loop result is \emph{dynamic loop routing} (quality-for-speed,
CE +0.04), NOT Amoeba-DA. Amoeba-DA applied to the loop model gives agreement 1.0
(415/415) but 0.568$\times$ -- verification too costly. These lines are kept separate.
\item \textbf{More draft heads (K=8):} extending K from 4 to 8 did not help: holdout
$\alpha_{6..9}$ fell from 0.195 to 0.117, and expected accepted length dropped from
2.61 to 1.69 (predicted speedup 2.02$\times\to$1.67$\times$). Draft--target divergence
grows with offset; adding heads cannot raise acceptance.
\item \textbf{V2, confidence-layered verification:} splitting drafts by softmax confidence
(high: accept unverified; mid: single-token verify; low: reject) gave no sweet spot.
The draft head is badly overconfident (mean $p=0.777$ vs accuracy 0.469): reaching
95\% precision needs $\tau>0.9999$ covering only 23\% of tokens, so most still need
verification. At $\tau$ high, 2B reached agreement 1.0 but was \emph{slower than greedy}
(163\,s vs 117\,s); at $\tau$ low, a single high-confidence error collapsed a sequence.
\item \textbf{V3 and V4, alternative objectives and layer skips:} forward-KL distillation
collapsed acceptance ($\alpha_2$: 0.469$\to$0.020) and learned KV prediction preserved
capability but was slower (0.973$\times$ decode). Both are described in full in \S5,
together with the K=8 result and the MACs audit.
\item \textbf{Serving-framework check (positive control):} to test whether speculative
decoding survives a real serving stack, we ran vLLM 0.11's built-in n-gram speculative
decoding on MiniCPM5-2B: \textbf{1.806$\times$} (640$\to$1156 tok/s). This confirms the
mechanism is framework-independent. Our draft heads cannot be plugged into vLLM directly
because it does not expose hidden states; a Medusa/EAGLE-style proposer adaptation is left
to future work. This result also shows the absolute throughput gain from the execution
framework is far larger than any architecture-level acceleration we measured.
\item \textbf{Gemma numerical-debug dead ends.} Before attributing Gemma's batched-verification
collapse to numerical non-associativity, we tested and ruled out: attention-mask variants
(\texttt{ones\_total}, \texttt{ones\_new}, \texttt{none}); explicit position ids; fp32 lm-head
readout; and changing attention implementation (eager vs sdpa). None changed the per-layer
hidden divergence (0.125 at layer 0, accumulating to 0.75 by layer 41). Single-token
verification restored exact agreement (96/96) but was 3.7$\times$ slower. The divergence is
in the batched matmul itself, not in masking or position encoding.
\item \textbf{Measurement artifact invalidating speed claims.} Per-prompt baseline timing is
bimodal and environment-driven, not model-driven: in one run of 20 prompts the first nine
ran at 2.8 tok/s and the last ten at 26 tok/s, with no difference in prompt content. The
same artifact appears in capability-evaluation generation (2.5 vs 27 tok/s),
long-context curves, and shared-GPU runs where baseline and Amoeba independently hit
fast/slow modes (producing apparent speedups from 0.287$\times$ to 5$\times$). We therefore
do not report any speedup derived from shared-GPU timing; the few numbers we cite are from
single-process, warm-up, repeated stable-fast-mode measurements. Several exploratory
conclusions (e.g.\ early readings that V2/V4 were ``slower'') are weak exactly because of
this artifact; they are reported as trends, not as precise ratios.
\item \textbf{Long-context experiment incomplete.} The speedup-vs-context-length curve (128--8K
tokens) was started but not completed: the measurement process was interrupted and the
surviving partial data (\texttt{longctx\_phase1.json}) covers only the shortest lengths.
An early smoke test at 128 tokens showed $\alpha_2\approx0.024$ and $1.16\times$ on two
prompts -- far below the short-context $\alpha_2=0.469$ -- suggesting substantial decay,
but we do not present this as a fitted curve. We refer to the short-context limitation in
\S11 and leave the full curve to future work.
\item \textbf{Abandoned model targets.} Qwen3.5-4B was downloaded and tested but abandoned:
baseline 29.9 tok/s, end-to-end 0.887--0.899$\times$, inconsistent batch-forward logits,
and unusable draft heads. SenseNova-Loop-9B's causal-conv1d kernel would not compile under
CUDA 12.8, so its baseline was first measured with a reference fallback (5.7 tok/s at loop1,
2.9 at loop2). SparkX-2.6-4B's released weights are FP8 in most distributions; we located
a BF16 variant, but its custom code required several transformers-4.57-era compatibility
patches under transformers 5.24, and its all-FP32 layer execution made baseline slow.
\end{enumerate}
\section{Conclusion}
We reframed ``dynamic activation'' from skipping layers within a token to dynamically
committing several tokens per step after exact verification (Amoeba-DA) and, on loop-structured
models, to dynamically choosing the number of loop iterations. On MiniCPM5-2B the first route
delivers \textbf{2.015$\times$} speedup while preserving downstream capability (79 objective
questions, zero regressions, ROUGE-L 0.94); MiniCPM5-1B gives 1.30$\times$. Our central finding
is that the benefit is bounded by architecture and context: it holds on full-attention dense
models, is numerically fragile on sliding-window hybrids, is blocked by KDA cache semantics on
MoE models, and concentrates in short context because the draft heads are trained on short
on-policy data. All Qwen-family speedups are withdrawn. The orthogonal loop-routing route gives
45\% speedup at 0.04 nats CE cost, a genuine quality-for-speed trade-off distinct from
speculative decoding. We release models (Apache-2.0), draft heads, scripts, raw data and the
full negative-result record -- including withdrawn and failed results -- for reproducibility.
\section{Limitations and Future Work}
\begin{itemize}[leftmargin=*]
\item \textbf{Short-context training.} All draft heads were trained on short on-policy corpora
($\sim$12K tokens). The reported acceleration is measured on short prompts; we do not
claim it generalizes to long context, and we quantify the decay in \S4.7. Training
draft heads on long-context on-policy data is future work.
\item \textbf{Capability scope.} We claim downstream accuracy preservation, not bit-exact
decoding; token agreement is 0.734 on 2B. Capability is measured on 79 objective QA
questions; open-ended generation, long-form reasoning, instruction-following nuance and
safety are not evaluated.
\item \textbf{Architecture dependence.} The method does not accelerate sliding-window hybrids
(numerical non-associativity) or KDA/MLA MoE (cache rollback), and Qwen-family numbers
are withdrawn (\S4.6, \S9). It is not a universal accelerator.
\item \textbf{Faithfulness--speed trade-off.} Three verification strategies were measured:
batched verification is fast but numerically non-associative on sliding architectures;
single-token verification is exact but 0.6--0.7$\times$; confidence layering has no
sweet spot because draft confidence is miscalibrated. We did not find a scheme that is
simultaneously faithful and fast, and we state this as an empirical boundary rather
than an implementation defect (\S9).
\item \textbf{Layer-skipping ceiling.} A MACs audit and KV-prediction experiments (\S5) show
that MLP, not attention, is 73.4\% of a layer's cost; $1.5\times$ needs skipping 15--16
layers, but capability collapses well before that. Learned KV prediction preserves QA
accuracy yet is slower than the baseline. Alternative layer-emulation designs are future work.
\item \textbf{Harness dependence.} All reported speedups use HuggingFace \texttt{generate},
which is Python-bound here ($\sim$100\% CPU, $\sim$3\% GPU): 27 tok/s for 2B versus a
theoretical bandwidth limit of $\sim$179 tok/s. Under vLLM 0.11 the same model reaches
64 tok/s single-prompt and $\sim$640--1280 tok/s batched. Our draft heads depend on hidden
states that vLLM does not expose, so they are bound to the HF harness and their vLLM
adaptation (e.g. a Medusa/EAGLE-style proposer) is future work. Importantly, the mechanism
itself is not framework-specific: vLLM's built-in n-gram speculative decoding gives
\textbf{1.806$\times$} (640$\to$1156 tok/s) on the same model, confirming that
verification-based multi-token decoding remains effective in a production stack.
The absolute throughput leap from the execution framework (CUDA graphs, PagedAttention)
is far larger than any architecture-level gain we measured; we report both facts.
Shared-GPU timings are bimodal; speedups use single-process stable-fast mode.
\item Loop routing rests on one model; multi-model validation and token-exit analysis needed.
\item Combining loop-depth routing with draft verification at the routed depth is future work.
\item \textbf{Adjacent directions are already occupied (scope note).} Several extensions that
follow naturally from our negative results have been published by other groups during
this study; we record them rather than claim them. \emph{From-scratch low-bit training:}
BitNet b1.58 (Ma et al., arXiv:2402.17764; JMLR 2025) trains ternary weights with a
straight-through estimator; BitSkip (Bhuvaneswaran \& Liu, arXiv:2510.23766) already
studies the composition of extreme quantization and early exit, and finds -- consistently
with our \S3 result on a \emph{pretrained} backbone -- that training from scratch is what
makes intermediate exits viable. We note that BitNet reports the KV cache of its models
as losslessly quantizable to 4 bits, but not to 1.58 bits.
\emph{Low-bit and structured KV caches:} CommVQ (Li et al., ICML 2025) achieves 2-bit
KV with a RoPE-commutative codebook; VecInfer, AnTKV and KVPath push this to 1--2 bits
or add a cross-layer dimension. Our ``add one discrete dimension'' idea is an instance
of this line, not a new mechanism. \emph{Reversible state:} KV-Direct (arXiv:2603.19664)
reconstructs K/V exactly from one residual per token (5\,KB vs 136\,KB per token) and
ReplaySSM (NVIDIA, 2026) makes recurrent-state rollback an $O(1)$ buffer-pointer move;
together these address the verification-failure rollback cost that blocked our
confidence-layering and KDA experiments (\S9), but they are prior work.
\emph{Image and multimodal generation is not an unexplored refuge:} early-exit diffusion
(ASE, Moon et al., ICML 2024; AdaDiff, ECCV 2024; DuoDiff, 2024), dynamic DiT compute
(DyDiT++, TPAMI 2026; DiffCR, CVPR 2025; MoDDiT, 2026; DC-DiT, 2026), speculative
diffusion (De Bortoli et al., ICML 2025; SpeCa, 2025; FREE, 2025; SSD, 2026; VVS, 2025)
and 1--2-bit visual KV caches (CalibQuant, arXiv:2502.14882; AKVQ-VL, 2025; VisCache,
EMNLP 2026) are all published, often with larger speedups than ours. End-device small
diffusion models (0.3--0.4B) with elastic depth are likewise studied (SnapGen++, 2026;
JuZhou 1.0, 2026; EdgeDiT, CVPRW 2026). What remains genuinely underrepresented is not a
mechanism but an \emph{evaluation discipline}: downstream capability preservation with
zero regressions instead of bit-exactness or FID alone; boundary mapping across
architectures that reports failures; and harness-level throughput comparison. TwinPrune
(Liu et al., arXiv:2610.17530) independently exposed a related evaluation flaw -- VLM
compression claims validated only on prefill-only probes measure prefill quality, not
decode quality -- which supports the same view. More broadly, this concern is now an
active research topic in its own right: ``On Evaluating Performance of LLM Inference
Systems'' (SoCC 2026) gives a baseline-fairness / setup / metric-design checklist whose
speculative-decoding case study mirrors our \S4 analysis; ``The Silent Hyperparameter''
(arXiv:2605.19537) surveys 200 inference engines and 35,000 papers and finds that the
backend alone shifts benchmark scores by up to 16.6 points, a large-scale confirmation
of the harness dependence we observed at single-model scale; and a rigor-matched audit
of layer skipping (arXiv:2608.28846) shows that separating online-search overhead from
pure inference cost reverses naive wall-clock rankings. These works do not invalidate
our measurements -- they explain why our evaluation protocol matters. Transferring it to
diffusion and VLM inference, rather than inventing another accelerator, is the most
defensible next step.
\end{itemize}
\appendix
\section{Reproducibility}
Key artifacts: \texttt{medusa\_train4.py}, \texttt{medusa\_bench\_final.py},
\texttt{medusa\_agreement.py}, \texttt{agent\_infer.py}, \texttt{gen\_agent\_data2.py},
\texttt{train\_agent\_sft.py}, \texttt{bench\_compare.py},
\texttt{minicpm5\_chat\_template.jinja}, \texttt{ckpt\_\{2b,1b,06b,03b\}\_agent/full\_model/},
\texttt{medusa\_chat.pt}, \texttt{medusa\_chat\_1b.pt}, \texttt{docs/*.md},
\texttt{bench2/final\_results/}.
\section{Default decoding recommendation}
Greedy decoding can loop on long answers (2B repeated a sentence 20+ times). Recommended:
\texttt{temperature=0.8, top\_p=0.95, repetition\_penalty=1.05}. Official model-card scores
use temperature 1.0 and larger budgets, so our short-subset greedy scores are not directly
comparable.
\end{document}123456789101112131415161718192021Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
本仓库 Amoeba 模型的默认许可证为 Apache-2.0(基座 MiniCPM5 / Qwen3 为 Apache-2.0)。
完整许可证全文请见官方链接: http://www.apache.org/licenses/LICENSE-2.0
标准声明(发布时请按实际情况补充版权与 NOTICES):
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
注意:所有版本(含 Amoeba-0.3B 的 MNN-Pocket 基座)均为 Apache-2.0;用户可自行调整版权信息。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179> **Updated (Amoeba-DA).** This directory documents the original token-level early-exit research line, which was investigated and **rejected**. The shipped technique is **Amoeba-DA** (parallel draft heads + full-model verification): 2B 2.02×, 1B 1.30×, statistically lossless (not bit-exact). See the root `README.md` / `README_zh.md` and `docs/动态激活_完整实验矩阵.md`.
---
license: apache-2.0
base_model:
- taobao-mnn/MNN-Pocket-0.3B
library_name: transformers
pipeline_tag: text-generation
tags:
- dynamic-activation
- early-exit
- halt-head
- qwen3
- training-in-progress
---
# Amoeba-0.3B
## 中文
**一句话简介**:Amoeba-0.3B 是 `taobao-mnn/MNN-Pocket-0.3B` 的独立研究衍生模型,计划在小词表 Qwen3 架构(28 层、hidden 896)上挂载 token 级 halt head,验证动态激活方法在端侧极小基座上的收益与 scaling 规律。**当前状态:训练中 / 待发布——GPU 上仅有 step-3 冒烟 checkpoint,无可用正式权重。**
### 1. 基座模型(Base model)
| 项目 | 值 |
|---|---|
| 名称 | `taobao-mnn/MNN-Pocket-0.3B`(只使用主仓库 BF16 权重;`-MNN` / `-GGUF` 是部署产物,不可用于训练) |
| 架构 | `Qwen3ForCausalLM`(`model_type: qwen3`),transformers ≥4.51 原生支持,**不需要** `trust_remote_code`;attention 含 q_norm/k_norm(per-head RMSNorm, dim=64);config 用 `dtype: bfloat16` 字段 |
| 层数 | 28(`layer_types` 全部为 `full_attention`) |
| hidden_size / intermediate_size | 896 / 2560 |
| 注意力 | GQA 14 个 Q 头 / 2 个 KV 头,`head_dim=64`,RoPE `rope_theta=1e6` |
| 词表 | **65536**(三者中最小);`tie_word_embeddings=true`;`eos=65512` `<\|im_end\|>`,`pad=65510`,`bos=null` |
| 上下文 | 40960(官方称部署支持 32K) |
| 精度与参数 | bfloat16,约 300M 参数;config 中 `use_cache=false`,**推理前必须显式设为 True** |
| 基座 License | **Apache-2.0**(官方 LICENSE.txt;注意:不是 MIT) |
### 2. Amoeba 改造说明(设计,尚未产出正式权重)
- **Halt head 结构**:每层输出挂 `nn.Linear(hidden_size + 1, 1)`;0.3B 为 **`Linear(897, 1) × 28`**(新增参数约 2.5 万)。输入为该层隐状态 `h_i` 与 token 级不确定性 `unc=tanh(-log(p_max))` 的拼接。冒烟 checkpoint 已实测核实:`ckpt_03b_smoke/halt_heads.pt` 的 cfg 为 `n_layer=28, hidden_size=896, vocab_size=65536, eos=[65512], pad=65510`,权重形状 `(1, 897)`。
- **实现方式**:`AutoModelForCausalLM.from_pretrained(...)` 加载(解析为 Qwen3ForCausalLM),复用 0.6B 分支的 `AmoebaModel` wrapper 逐层 forward,不修改 modeling 代码;中间层 logits 由 `norm + lm_head` 计算。必须使用 SDPA 并校验注意力类名含 `Sdpa`。因 `tie_word_embeddings=true`,halt-only checkpoint 只存 halt heads。
- **动态激活**:逐 token 累计 `cum = 1-∏(1-p_l)`,`cum ≥ threshold` 时提前经 `norm + lm_head` 输出;小容量基座更容易把退出分布学成"全退浅层"或"全退末层",训练时已把均匀先验 γ 从 2.0 降到 1.0、语义项 η 从 0.1 降到 0.05(脚本已核实),不可照搬 2B 超参。
- **特殊适配**:硬编码 `eos_id=1` 必须改为 **65512**(停止条件、ckpt 元信息同步改);`pad_id=65510`;外部语料必须用本基座 tokenizer 重新 tokenize 并断言 `max(id) < 65536`(越界会直接崩溃);词表小使 CE 显存很低,可把 `--ce-samples` 提到 64~128 提升决策质量;评测/`generate` 前设 `model.config.use_cache = True`。
### 3. 用法示例(发布后接口示意)
> 当前只有 step-3 冒烟 checkpoint(lr=0,仅验证维度与梯度),**不可用于真实推理**。以下为权重发布后的加载方式示意。
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer_qwen03b import AmoebaModel # Qwen3 分支 wrapper(待发布)
BASE = "taobao-mnn/MNN-Pocket-0.3B" # 发布后替换为 Hub 仓库
HALT = "./halt_heads.pt" # 正式版 halt 权重(待发布)
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
base.config.use_cache = True # config 默认 false,生成前必须打开
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("你好,用一句话介绍你自己。", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
# eos_id=65512、pad_id=65510;token id 必须 < 65536
```
### 4. 训练状态(诚实说明)
- **训练中 / 待发布**:2026-11-22 GPU 核实——`/data/work/ckpt_qwen03b_full/` 与 `/data/work/ckpt_03b_fixed/` **均不存在**;只有 `ckpt_03b_smoke/halt_heads.pt`(step 3,lr=0,仅冒烟测试)和早期空目录 `ckpt_qwen03b_full_BUGGY_2354/`。`logs_03b_full.log` 显示 full 训练曾跑到约 step 460,但没有保存权重(无 `[save]` 记录)。**目前没有可下载/可推理的正式 checkpoint。**
- **已知风险**:基座较新(2026-11 发布),小词表 + 小容量下 halt 决策极不稳定;日志中逐层 CE 在 L4 后几乎平坦(≈29~31),属于典型的"浅层与深层无质量差异"——若直接早退会重现 2B/1B 的退出坍缩。需先按修复方案(`lam=0`、质量门控、冻结基座重训 halt)处理,并以"强制退出 CE 曲线 + PPL + 退出层分布 + 贪心生成"四件套验收后才发布。
- **训练数据(计划/部分已用)**:CCI3-Data(Apache-2.0)等,必须用 65536 词表 tokenizer 重新 tokenize。
### 5. License
- 基座 `taobao-mnn/MNN-Pocket-0.3B`:**Apache-2.0**(官方 LICENSE.txt,**不是 MIT**);衍生权重发布后整体采用 **Apache-2.0**(附 LICENSE + NOTICE,保留上游版权声明)。
- Amoeba 新增部分(halt head、wrapper、训练/评测脚本、本 card)同样为 **Apache-2.0**。
- 商标/背书:独立研究项目,**与淘宝 / MNN 团队无隶属或官方背书关系**;模型名不含 "official"。
- 数据署名:训练数据含 `nvidia/OpenMathReasoning`(CC-BY-4.0,见致谢);未复制 LayerSkip(CC-BY-NC)代码。
### 6. Citation / 致谢
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-0.3B}
}
```
- 基座:Taobao-MNN Team, *MNN-Pocket-0.3B* (Apache-2.0).
- 方法思想:Schuster et al., *CALM*; Elhoushi et al., *LayerSkip*(仅论文思想,未用其代码)。
- 数据:BAAI/CCI3-Data (Apache-2.0)、nvidia/OpenMathReasoning (**CC-BY-4.0**,特此署名)。
---
## English
**One-line summary**: Amoeba-0.3B is an independent research derivative of `taobao-mnn/MNN-Pocket-0.3B`, planning to add token-level halt heads to a small-vocabulary Qwen3 base (28 layers, hidden 896) to study dynamic-activation gains and scaling at the tiniest on-device scale. **Status: training in progress / unreleased — only a step-3 smoke checkpoint exists on GPU; no usable weights.**
### 1. Base model
| Field | Value |
|---|---|
| Name | `taobao-mnn/MNN-Pocket-0.3B` (main repo BF16 weights only; `-MNN` / `-GGUF` are deployment artifacts and unusable for training) |
| Architecture | `Qwen3ForCausalLM` (`model_type: qwen3`), natively supported by transformers ≥4.51; **no** `trust_remote_code`. Attention includes q_norm/k_norm (per-head RMSNorm, dim=64); config uses the `dtype: bfloat16` field |
| Layers | 28 (all `layer_types` are `full_attention`) |
| hidden_size / intermediate_size | 896 / 2560 |
| Attention | GQA, 14 Q / 2 KV heads, `head_dim=64`, RoPE `rope_theta=1e6` |
| Vocabulary | **65536** (smallest in the family); `tie_word_embeddings=true`; `eos=65512` `<\|im_end\|>`, `pad=65510`, `bos=null` |
| Context | 40960 (official docs say 32K deployment support) |
| Precision & size | bfloat16, ~300M params; config has `use_cache=false` — **set it to True explicitly before inference** |
| Base license | **Apache-2.0** (official LICENSE.txt; **not MIT**) |
### 2. Amoeba modification (design; no official weights yet)
- **Halt head**: one `nn.Linear(hidden_size + 1, 1)` per layer — for 0.3B, **`Linear(897, 1) × 28`** (~25k new parameters). Input = layer hidden state `h_i` plus token-level uncertainty `unc=tanh(-log(p_max))`. Verified from the smoke checkpoint (`ckpt_03b_smoke/halt_heads.pt`): cfg `n_layer=28, hidden_size=896, vocab_size=65536, eos=[65512], pad=65510`, weight shape `(1, 897)`.
- **Implementation**: load via `AutoModelForCausalLM.from_pretrained(...)` (resolves to Qwen3ForCausalLM), reuse the 0.6B-branch `AmoebaModel` wrapper's layer-by-layer forward, no modeling-code edits; intermediate logits via `norm + lm_head`. SDPA required; attention class must contain `Sdpa`. With `tie_word_embeddings=true`, halt-only checkpoints store halt heads only.
- **Dynamic activation**: per-token `cum = 1-∏(1-p_l)`; exit at the first layer where `cum ≥ threshold`. A tiny base tends to learn "exit all at shallow layers" or "exit all at the last layer"; the script already lowers the uniformity weight γ 2.0→1.0 and semantic weight η 0.1→0.05 (verified) — do not copy 2B hyperparameters.
- **Adaptation notes**: hardcoded `eos_id=1` must become **65512** (also fix stopping condition and ckpt metadata); `pad_id=65510`; retokenize all corpora with this base's tokenizer and assert `max(id) < 65536` (out-of-range ids crash training); the small vocabulary lowers CE memory, so `--ce-samples` can be raised to 64~128; set `model.config.use_cache = True` before evaluation/generation.
### 3. Usage (interface sketch for a future release)
> Only a step-3 smoke checkpoint (lr=0, dimension/gradient check) exists — **not usable for real inference**. The snippet illustrates the post-release loading flow.
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer_qwen03b import AmoebaModel # Qwen3-branch wrapper (to be released)
BASE = "taobao-mnn/MNN-Pocket-0.3B" # replace with released Hub repo
HALT = "./halt_heads.pt" # official halt weights (unreleased)
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
base.config.use_cache = True # config defaults to false; enable for generation
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("Hello, introduce yourself in one sentence.", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
# eos_id=65512, pad_id=65510; token ids must stay < 65536
```
### 4. Training status (honest disclosure)
- **IN PROGRESS / UNRELEASED**: GPU verification on 2026-11-22 — `/data/work/ckpt_qwen03b_full/` and `/data/work/ckpt_03b_fixed/` **do not exist**; only `ckpt_03b_smoke/halt_heads.pt` (step 3, lr=0, smoke test) and an earlier empty dir `ckpt_qwen03b_full_BUGGY_2354/`. `logs_03b_full.log` shows a full run reached ~step 460 but produced no saved weights (no `[save]` record). **No downloadable/inferable official checkpoint exists.**
- **Known risks**: the base is new (released 2026-11) and the small vocabulary/capacity makes halt decisions unstable; logs show per-layer CE nearly flat after L4 (~29–31) — the classic "no quality difference between shallow and deep layers" signature, which would reproduce the 2B/1B exit collapse if early exits were used. Fix first (`lam=0`, quality gating, halt retraining on a frozen base), then release only after the four-part check: forced-exit CE curve + PPL + exit-layer distribution + greedy generation.
- **Training data (planned/partially used)**: CCI3-Data (Apache-2.0) etc.; all corpora must be retokenized to the 65536 vocabulary.
### 5. License
- Base `taobao-mnn/MNN-Pocket-0.3B` is **Apache-2.0** (official LICENSE.txt; **not MIT**); derivative weights, once released, will be **Apache-2.0** (LICENSE + NOTICE, upstream notices preserved).
- All Amoeba additions (halt heads, wrapper, training/eval scripts, this card) are **Apache-2.0**.
- Trademark: independent research, **not affiliated with or endorsed by Taobao/MNN**; no "official" in the model name.
- Data attribution: training data includes `nvidia/OpenMathReasoning` (**CC-BY-4.0**, credited); no LayerSkip (CC-BY-NC) code copied.
### 6. Citation / acknowledgements
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-0.3B}
}
```
- Base: Taobao-MNN Team, *MNN-Pocket-0.3B* (Apache-2.0).
- Method inspiration: Schuster et al., *CALM*; Elhoushi et al., *LayerSkip* (ideas only, no code).
- Data: BAAI/CCI3-Data (Apache-2.0), nvidia/OpenMathReasoning (**CC-BY-4.0**, credited).123version https://git-lfs.github.com/spec/v1oid sha256:0a48bbe608c178f8b9085f7610289977f0d587c718c7b55b0e1b05a48f1d8576size 118453123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# -*- coding: utf-8 -*-"""amoeba_infer_with_gate.py — Amoeba 动态激活推理(带质量门,推荐用法)
关键:原始 halt head 会坍缩到浅层(L2-L6)导致乱码。质量门(conf_min)强制只有"该层对下一 token 的置信度 >= conf_min"才允许退出,把计算推到质量足够的深层,从而恢复生成质量。
用法: python amoeba_infer_with_gate.py --model-path <full_model目录> \ --ckpt <halt_heads.pt> --conf-min 0.85 --prompt "你好" # conf_min 越大越保守(质量越好、加速越少);推荐 0.8~0.95 # conf_min=1.0 等价全层(无早退);conf_min=0.0 等价无门(会坍缩,勿用)"""import sys, argparse, torchsys.stdout.reconfigure(encoding="utf-8", errors="replace")import torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer
ap = argparse.ArgumentParser()ap.add_argument("--model-path", required=True)ap.add_argument("--ckpt", default="")ap.add_argument("--conf-min", type=float, default=0.85, help="质量门:每层置信度下限,越大越保守")ap.add_argument("--threshold", type=float, default=0.9, help="halt 累积退出概率阈值")ap.add_argument("--prompt", default="你好")ap.add_argument("--max-new", type=int, default=96)ap.add_argument("--temperature", type=float, default=0.7)args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"tok = AutoTokenizer.from_pretrained(args.model_path)base = AutoModelForCausalLM.from_pretrained(args.model_path, dtype=torch.bfloat16, device_map=device).eval()base.config.use_cache = Falsen_layer = base.config.num_hidden_layershidden_size = base.config.hidden_size
# halt heads(与训练一致:Linear(hidden+1,1))halt_heads = torch.nn.ModuleList([torch.nn.Linear(hidden_size + 1, 1) for _ in range(n_layer)])if args.ckpt: obj = torch.load(args.ckpt, map_location="cpu", weights_only=False) sd = obj.get("halt_heads", obj) cleaned = {k.replace("halt_heads.", ""): v for k, v in sd.items()} halt_heads.load_state_dict(cleaned, strict=True) print(f"[load] halt heads from {args.ckpt}", flush=True)halt_heads = halt_heads.to(device).eval()
def unc_of(logits_1): p = F.softmax(logits_1.float(), dim=-1) pmax = p.max(dim=-1).values.clamp_min(1e-8) return torch.tanh(-torch.log(pmax))
def call_layer(layer, hidden, **kw): import inspect sig = inspect.signature(layer.forward) if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()): out = layer(hidden, **kw) else: out = layer(hidden, {k: v for k, v in kw.items() if k in sig.parameters}) return out[0] if isinstance(out, (tuple, list)) else out
@torch.no_grad()def generate(prompt): ctx = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" ids = tok(ctx, return_tensors="pt", add_special_tokens=False).to(device)["input_ids"] exits = [] for _ in range(args.max_new): T = ids.shape[1] emb = base.model.embed_tokens(ids) pos = torch.arange(T, device=device).unsqueeze(0) pe = base.model.rotary_emb(emb, pos) common = dict(attention_mask=None, position_ids=pos, past_key_value=None, past_key_values=None, output_attentions=False, use_cache=False, cache_position=torch.arange(T, device=device), position_embeddings=pe) h = emb hiddens = [] for layer in base.model.layers: h = call_layer(layer, h, **common) hiddens.append(h) remaining = torch.ones(1, device=device) chosen = None used = n_layer for i in range(n_layer): hl = hiddens[i][:, -1, :] logits = base.lm_head(base.model.norm(hl.unsqueeze(1)))[:, 0, :] conf = F.softmax(logits.float(), dim=-1).max(dim=-1).values # [1] p = torch.sigmoid(halt_heads[i](torch.cat([hl, unc_of(logits).unsqueeze(-1)], dim=-1)).squeeze(-1)) remaining = remaining * (1 - p) quality_ok = (conf >= args.conf_min) | (i >= n_layer - 2) if ((1 - remaining >= args.threshold) & quality_ok).all(): chosen = logits; used = i + 1; break if chosen is None: chosen = base.lm_head(base.model.norm(hiddens[-1][:, -1, :].unsqueeze(1)))[:, 0, :] used = n_layer if args.temperature <= 0: nxt = chosen.argmax(dim=-1, keepdim=True) else: nxt = torch.multinomial(F.softmax(chosen / args.temperature, dim=-1), 1) ids = torch.cat([ids, nxt], dim=1) exits.append(used) if nxt.item() in (1, 151645, 65512, 2): break reply = tok.decode(ids[0][ids.shape[1]-0:].tolist(), skip_special_tokens=True) if False else tok.decode(ids[0][len(tok(ctx, add_special_tokens=False)['input_ids']):].tolist(), skip_special_tokens=True) return reply, exits
print(f"[cfg] conf_min={args.conf_min} threshold={args.threshold} layers={n_layer}", flush=True)reply, exits = generate(args.prompt)print(f"用户: {args.prompt}\n助手: {reply}")print(f"[退出层均值 {sum(exits)/len(exits):.1f}/{n_layer} | 生成 {len(exits)} token]", flush=True)123456789101112131415161718192021Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
本仓库 Amoeba 模型的默认许可证为 Apache-2.0(基座 MiniCPM5 / Qwen3 为 Apache-2.0)。
完整许可证全文请见官方链接: http://www.apache.org/licenses/LICENSE-2.0
标准声明(发布时请按实际情况补充版权与 NOTICES):
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
注意:所有版本(含 Amoeba-0.3B 的 MNN-Pocket 基座)均为 Apache-2.0;用户可自行调整版权信息。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177> **Updated (Amoeba-DA).** This directory documents the original token-level early-exit research line, which was investigated and **rejected**. The shipped technique is **Amoeba-DA** (parallel draft heads + full-model verification): 2B 2.02×, 1B 1.30×, statistically lossless (not bit-exact). See the root `README.md` / `README_zh.md` and `docs/动态激活_完整实验矩阵.md`.
---
license: apache-2.0
base_model:
- Qwen/Qwen3-0.6B
library_name: transformers
pipeline_tag: text-generation
tags:
- dynamic-activation
- early-exit
- halt-head
- qwen3
- training-in-progress
---
# Amoeba-0.6B
## 中文
**一句话简介**:Amoeba-0.6B 是 `Qwen/Qwen3-0.6B` 的独立研究衍生模型,计划在 Qwen3 架构(28 层、含 q_norm/k_norm)上挂载 token 级 halt head 实现动态深度推理,用于验证 Amoeba 方法跨模型族的普适性。**当前状态:训练中 / 待发布——GPU 上仅有 step-3 冒烟 checkpoint,无可用正式权重。**
### 1. 基座模型(Base model)
| 项目 | 值 |
|---|---|
| 名称 | `Qwen/Qwen3-0.6B` |
| 架构 | `Qwen3ForCausalLM`(`model_type: qwen3`),transformers ≥4.51 原生支持,**不需要** `trust_remote_code`;注意力内含 Qwen3 特有的 **q_norm / k_norm**(per-head RMSNorm, dim=128),wrapper 逐层调用时自动执行,不可绕过或修改 modeling 代码 |
| 层数 | 28 |
| hidden_size / intermediate_size | 1024 / 3072 |
| 注意力 | GQA 16 个 Q 头 / **8 个 KV 头**,`head_dim=128`,RoPE `rope_theta=1e6` |
| 词表 | 151936;`tie_word_embeddings=true`(lm_head 与 embed_tokens 共享);`eos=151645` `<\|im_end\|>`,`pad=151643` |
| 上下文 | 40960(≈40K;以 config 为准,tokenizer_config 的 131072 是假象) |
| 精度 | bfloat16,参数量约 0.60B |
| 基座 License | **Apache-2.0**(Qwen 官方 LICENSE) |
### 2. Amoeba 改造说明(设计,尚未产出正式权重)
- **Halt head 结构**:每层输出挂 `nn.Linear(hidden_size + 1, 1)`;0.6B 为 **`Linear(1025, 1) × 28`**(新增参数约 2.9 万)。输入为该层隐状态 `h_i` 与 token 级不确定性 `unc=tanh(-log(p_max))` 的拼接。冒烟 checkpoint 已实测核实:`ckpt_06b_smoke/halt_heads.pt` 的 cfg 为 `n_layer=28, hidden_size=1024, vocab_size=151936, eos=[151645], pad=151643`,权重形状 `(1, 1025)`。
- **实现方式**:用 `AutoModelForCausalLM.from_pretrained(...)` 加载(解析为 Qwen3ForCausalLM),沿用 `AmoebaModel` wrapper 逐层 forward,不修改 modeling 代码;中间层 logits 仍由 `norm + lm_head` 计算。必须使用 SDPA 并校验注意力类名含 `Sdpa`(wrapper 依赖自动因果掩码)。
- **动态激活**:逐 token 累计 `cum = 1-∏(1-p_l)`,`cum ≥ threshold` 时经 `norm + lm_head` 提前输出;因 `tie_word_embeddings=true`,保存 halt-only checkpoint 时**只存 halt heads,不要存 tied lm_head**。
- **特殊适配**:脚本里硬编码的 `eos_id=1` 必须改为 **151645**(否则生成永不停止);语料需用 Qwen2Tokenizer 重新 tokenize(Qwen ChatML 模板,注意 `<think>`/`enable_thinking`),断言 `max(token_id) < 151936`;8 个 KV 头使生成 KV cache 更大,评测长上下文时注意显存。
### 3. 用法示例(发布后接口示意)
> 当前只有冒烟 checkpoint(step 3,随机初始化附近),**不可用于真实推理**。以下为权重发布后的加载方式示意。
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer_qwen06b import AmoebaModel # Qwen3 分支 wrapper(待发布)
BASE = "Qwen/Qwen3-0.6B" # 发布后替换为 Hub 仓库
HALT = "./halt_heads.pt" # 正式版 halt 权重(待发布)
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("你好,简单介绍一下你自己。", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
# 注意:eos_id=151645、pad_id=151643;生成时不要沿用 1B/2B 的 eos=1
```
### 4. 训练状态(诚实说明)
- **训练中 / 待发布**:2026-11-22 GPU 核实——`/data/work/ckpt_qwen06b_full/` 与 `/data/work/ckpt_06b_fixed/` **均不存在**;只有 `ckpt_06b_smoke/halt_heads.pt`(step 3,仅用于验证维度与梯度的冒烟测试),以及早期空目录 `ckpt_qwen06b_full_BUGGY_2354/`。`logs_06b_full.log` 显示 full 训练曾跑到约 step 560,但没有产出保存的权重(无 `[save]` 记录)。**目前没有可下载/可推理的正式 checkpoint。**
- **已知风险**:Qwen3 小基座上均匀先验与语义项更敏感���0.3B 脚本已将 γ 从 2.0 降到 1.0、η 降到 0.05);2B/1B 上观察到的退出坍缩(浅层早退导致 PPL 暴涨)同样需要通过 `lam=0`、质量门控、冻结教师重训 halt 等方式修复。0.6B 修复训练完成后需通过"强制退出 CE 曲线 + PPL + 退出层分布 + 贪心生成"四件套验收才发布。
- **训练数据(计划/部分已用)**:CCI3-Data(Apache-2.0)等,与主线一致。
### 5. License
- 基座 `Qwen/Qwen3-0.6B`:**Apache-2.0**;衍生权重发布后整体采用 **Apache-2.0**(附 LICENSE + NOTICE)。
- Amoeba 新增部分(halt head、wrapper、训练/评测脚本、本 card)同样为 **Apache-2.0**。
- 商标/背书:独立研究项目,**与阿里云 / Qwen 团队无隶属或官方背书关系**;模型名不含 "official"。
- 数据署名:训练数据含 `nvidia/OpenMathReasoning`(CC-BY-4.0,见致谢);未复制 LayerSkip(CC-BY-NC)代码。
### 6. Citation / 致谢
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-0.6B}
}
```
- 基座:Qwen Team, *Qwen3-0.6B* (Apache-2.0).
- 方法思想:Schuster et al., *CALM*; Elhoushi et al., *LayerSkip*(仅论文思想,未用其代码)。
- 数据:BAAI/CCI3-Data (Apache-2.0)、nvidia/OpenMathReasoning (**CC-BY-4.0**,特此署名)。
---
## English
**One-line summary**: Amoeba-0.6B is an independent research derivative of `Qwen/Qwen3-0.6B`, planning to add token-level halt heads to the Qwen3 architecture (28 layers, with q_norm/k_norm) for adaptive-depth inference, testing cross-family generality of the Amoeba method. **Status: training in progress / unreleased — only a step-3 smoke checkpoint exists on GPU; no usable weights.**
### 1. Base model
| Field | Value |
|---|---|
| Name | `Qwen/Qwen3-0.6B` |
| Architecture | `Qwen3ForCausalLM` (`model_type: qwen3`), natively supported by transformers ≥4.51; **no** `trust_remote_code`. Attention includes Qwen3-specific **q_norm / k_norm** (per-head RMSNorm, dim=128), executed automatically by the layer-by-layer wrapper — never bypass or edit modeling code |
| Layers | 28 |
| hidden_size / intermediate_size | 1024 / 3072 |
| Attention | GQA, 16 Q / **8 KV** heads, `head_dim=128`, RoPE `rope_theta=1e6` |
| Vocabulary | 151936; `tie_word_embeddings=true` (lm_head tied to embed_tokens); `eos=151645` `<\|im_end\|>`, `pad=151643` |
| Context | 40960 (~40K; config is authoritative, tokenizer_config's 131072 is not) |
| Precision | bfloat16, ~0.60B parameters |
| Base license | **Apache-2.0** (official Qwen LICENSE) |
### 2. Amoeba modification (design; no official weights yet)
- **Halt head**: one `nn.Linear(hidden_size + 1, 1)` per layer — for 0.6B, **`Linear(1025, 1) × 28`** (~29k new parameters). Input = layer hidden state `h_i` plus token-level uncertainty `unc=tanh(-log(p_max))`. Verified from the smoke checkpoint (`ckpt_06b_smoke/halt_heads.pt`): cfg `n_layer=28, hidden_size=1024, vocab_size=151936, eos=[151645], pad=151643`, weight shape `(1, 1025)`.
- **Implementation**: load via `AutoModelForCausalLM.from_pretrained(...)` (resolves to Qwen3ForCausalLM), keep the `AmoebaModel` wrapper's layer-by-layer forward, no modeling-code edits; intermediate logits still via `norm + lm_head`. SDPA is required and the attention class name must contain `Sdpa` (the wrapper relies on automatic causal masking).
- **Dynamic activation**: per-token `cum = 1-∏(1-p_l)`; exit at the first layer where `cum ≥ threshold` via `norm + lm_head`. Because `tie_word_embeddings=true`, halt-only checkpoints must store **halt heads only — never the tied lm_head**.
- **Adaptation notes**: hardcoded `eos_id=1` must become **151645** (otherwise generation never stops); retokenize corpora with Qwen2Tokenizer (Qwen ChatML template, mind `<think>`/`enable_thinking`) and assert `max(token_id) < 151936`; 8 KV heads enlarge generation KV cache — watch memory on long-context evaluation.
### 3. Usage (interface sketch for a future release)
> Only a step-3 smoke checkpoint (near-random initialization) exists — **not usable for real inference**. The snippet illustrates the post-release loading flow.
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer_qwen06b import AmoebaModel # Qwen3-branch wrapper (to be released)
BASE = "Qwen/Qwen3-0.6B" # replace with released Hub repo
HALT = "./halt_heads.pt" # official halt weights (unreleased)
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("Hello, tell me about yourself.", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
# eos_id=151645, pad_id=151643; do not reuse eos=1 from 1B/2B
```
### 4. Training status (honest disclosure)
- **IN PROGRESS / UNRELEASED**: GPU verification on 2026-11-22 — `/data/work/ckpt_qwen06b_full/` and `/data/work/ckpt_06b_fixed/` **do not exist**; only `ckpt_06b_smoke/halt_heads.pt` (step 3, dimension/gradient smoke test) and an earlier empty dir `ckpt_qwen06b_full_BUGGY_2354/`. `logs_06b_full.log` shows a full run reached ~step 560 but produced no saved weights (no `[save]` record). **No downloadable/inferable official checkpoint exists.**
- **Known risks**: small Qwen3 bases are sensitive to the uniformity prior and semantic term (the 0.3B script already lowered γ 2.0→1.0, η→0.05). Exit collapse observed on 2B/1B (shallow exits, PPL explosion) must also be fixed here via `lam=0`, quality gating, frozen-teacher halt retraining. Release requires passing the four-part check: forced-exit CE curve + PPL + exit-layer distribution + greedy generation.
- **Training data (planned/partially used)**: CCI3-Data (Apache-2.0) etc., consistent with the mainline.
### 5. License
- Base `Qwen/Qwen3-0.6B` is **Apache-2.0**; derivative weights, once released, will be **Apache-2.0** (LICENSE + NOTICE).
- All Amoeba additions (halt heads, wrapper, training/eval scripts, this card) are **Apache-2.0**.
- Trademark: independent research, **not affiliated with or endorsed by Alibaba/Qwen**; no "official" in the model name.
- Data attribution: training data includes `nvidia/OpenMathReasoning` (**CC-BY-4.0**, credited); no LayerSkip (CC-BY-NC) code copied.
### 6. Citation / acknowledgements
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-0.6B}
}
```
- Base: Qwen Team, *Qwen3-0.6B* (Apache-2.0).
- Method inspiration: Schuster et al., *CALM*; Elhoushi et al., *LayerSkip* (ideas only, no code).
- Data: BAAI/CCI3-Data (Apache-2.0), nvidia/OpenMathReasoning (**CC-BY-4.0**, credited).123version https://git-lfs.github.com/spec/v1oid sha256:67a0c2507cd02219e0c3d5befc9968c24c2eeaa24b6bab77fe368b38046a7ab5size 132789123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# -*- coding: utf-8 -*-"""amoeba_infer_with_gate.py — Amoeba 动态激活推理(带质量门,推荐用法)
关键:原始 halt head 会坍缩到浅层(L2-L6)导致乱码。质量门(conf_min)强制只有"该层对下一 token 的置信度 >= conf_min"才允许退出,把计算推到质量足够的深层,从而恢复生成质量。
用法: python amoeba_infer_with_gate.py --model-path <full_model目录> \ --ckpt <halt_heads.pt> --conf-min 0.85 --prompt "你好" # conf_min 越大越保守(质量越好、加速越少);推荐 0.8~0.95 # conf_min=1.0 等价全层(无早退);conf_min=0.0 等价无门(会坍缩,勿用)"""import sys, argparse, torchsys.stdout.reconfigure(encoding="utf-8", errors="replace")import torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer
ap = argparse.ArgumentParser()ap.add_argument("--model-path", required=True)ap.add_argument("--ckpt", default="")ap.add_argument("--conf-min", type=float, default=0.85, help="质量门:每层置信度下限,越大越保守")ap.add_argument("--threshold", type=float, default=0.9, help="halt 累积退出概率阈值")ap.add_argument("--prompt", default="你好")ap.add_argument("--max-new", type=int, default=96)ap.add_argument("--temperature", type=float, default=0.7)args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"tok = AutoTokenizer.from_pretrained(args.model_path)base = AutoModelForCausalLM.from_pretrained(args.model_path, dtype=torch.bfloat16, device_map=device).eval()base.config.use_cache = Falsen_layer = base.config.num_hidden_layershidden_size = base.config.hidden_size
# halt heads(与训练一致:Linear(hidden+1,1))halt_heads = torch.nn.ModuleList([torch.nn.Linear(hidden_size + 1, 1) for _ in range(n_layer)])if args.ckpt: obj = torch.load(args.ckpt, map_location="cpu", weights_only=False) sd = obj.get("halt_heads", obj) cleaned = {k.replace("halt_heads.", ""): v for k, v in sd.items()} halt_heads.load_state_dict(cleaned, strict=True) print(f"[load] halt heads from {args.ckpt}", flush=True)halt_heads = halt_heads.to(device).eval()
def unc_of(logits_1): p = F.softmax(logits_1.float(), dim=-1) pmax = p.max(dim=-1).values.clamp_min(1e-8) return torch.tanh(-torch.log(pmax))
def call_layer(layer, hidden, **kw): import inspect sig = inspect.signature(layer.forward) if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()): out = layer(hidden, **kw) else: out = layer(hidden, {k: v for k, v in kw.items() if k in sig.parameters}) return out[0] if isinstance(out, (tuple, list)) else out
@torch.no_grad()def generate(prompt): ctx = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" ids = tok(ctx, return_tensors="pt", add_special_tokens=False).to(device)["input_ids"] exits = [] for _ in range(args.max_new): T = ids.shape[1] emb = base.model.embed_tokens(ids) pos = torch.arange(T, device=device).unsqueeze(0) pe = base.model.rotary_emb(emb, pos) common = dict(attention_mask=None, position_ids=pos, past_key_value=None, past_key_values=None, output_attentions=False, use_cache=False, cache_position=torch.arange(T, device=device), position_embeddings=pe) h = emb hiddens = [] for layer in base.model.layers: h = call_layer(layer, h, **common) hiddens.append(h) remaining = torch.ones(1, device=device) chosen = None used = n_layer for i in range(n_layer): hl = hiddens[i][:, -1, :] logits = base.lm_head(base.model.norm(hl.unsqueeze(1)))[:, 0, :] conf = F.softmax(logits.float(), dim=-1).max(dim=-1).values # [1] p = torch.sigmoid(halt_heads[i](torch.cat([hl, unc_of(logits).unsqueeze(-1)], dim=-1)).squeeze(-1)) remaining = remaining * (1 - p) quality_ok = (conf >= args.conf_min) | (i >= n_layer - 2) if ((1 - remaining >= args.threshold) & quality_ok).all(): chosen = logits; used = i + 1; break if chosen is None: chosen = base.lm_head(base.model.norm(hiddens[-1][:, -1, :].unsqueeze(1)))[:, 0, :] used = n_layer if args.temperature <= 0: nxt = chosen.argmax(dim=-1, keepdim=True) else: nxt = torch.multinomial(F.softmax(chosen / args.temperature, dim=-1), 1) ids = torch.cat([ids, nxt], dim=1) exits.append(used) if nxt.item() in (1, 151645, 65512, 2): break reply = tok.decode(ids[0][ids.shape[1]-0:].tolist(), skip_special_tokens=True) if False else tok.decode(ids[0][len(tok(ctx, add_special_tokens=False)['input_ids']):].tolist(), skip_special_tokens=True) return reply, exits
print(f"[cfg] conf_min={args.conf_min} threshold={args.threshold} layers={n_layer}", flush=True)reply, exits = generate(args.prompt)print(f"用户: {args.prompt}\n助手: {reply}")print(f"[退出层均值 {sum(exits)/len(exits):.1f}/{n_layer} | 生成 {len(exits)} token]", flush=True)123456789101112131415161718192021Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
本仓库 Amoeba 模型的默认许可证为 Apache-2.0(基座 MiniCPM5 / Qwen3 为 Apache-2.0)。
完整许可证全文请见官方链接: http://www.apache.org/licenses/LICENSE-2.0
标准声明(发布时请按实际情况补充版权与 NOTICES):
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
注意:所有版本(含 Amoeba-0.3B 的 MNN-Pocket 基座)均为 Apache-2.0;用户可自行调整版权信息。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177> **Updated (Amoeba-DA).** This directory documents the original token-level early-exit research line, which was investigated and **rejected**. The shipped technique is **Amoeba-DA** (parallel draft heads + full-model verification): 2B 2.02×, 1B 1.30×, statistically lossless (not bit-exact). See the root `README.md` / `README_zh.md` and `docs/动态激活_完整实验矩阵.md`.
---
license: apache-2.0
base_model:
- openbmb/MiniCPM5-1B
library_name: transformers
pipeline_tag: text-generation
tags:
- dynamic-activation
- early-exit
- halt-head
- on-device
- research-preview
---
# Amoeba-1B
## 中文
**一句话简介**:Amoeba-1B 是 `openbmb/MiniCPM5-1B` 的独立研究衍生模型,通过对 24 层 Transformer 逐层挂载 token 级 halt head 实现按 token 自适应的动态深度推理;已完成一轮全参研究训练,权重已产出,但因退出坍缩问题仍待修复,当前为**研究预览 / 待正式发布**。
### 1. 基座模型(Base model)
| 项目 | 值 |
|---|---|
| 名称 | `openbmb/MiniCPM5-1B` |
| 架构 | `LlamaForCausalLM`(`model_type: llama`),与 2B 完全同构,无需 `trust_remote_code` |
| 层数 | 24 |
| hidden_size / intermediate_size | **1536 / 4608**(注意:不是旧文档中误写的 2048/6144) |
| 注意力 | GQA 16 个 Q 头 / 2 个 KV 头,`head_dim=128`,RoPE `rope_theta=5e6` |
| 词表 | 130560(与 2B 共用 tokenizer 与特殊 token:`eos=[1, 130073]`,`pad=1`) |
| 上下文 | 131072(128K) |
| 精度 | bfloat16,`tie_word_embeddings=false`,参数量约 1.08B |
| 基座 License | **Apache-2.0** |
### 2. Amoeba 改造说明
- **Halt head 结构**:每层输出挂 `nn.Linear(hidden_size + 1, 1)`;1B 为 **`Linear(1537, 1) × 24`**,新增参数约 3.7 万。输入为该层隐状态 `h_i` 与 token 级不确定性标量 `unc=tanh(-log(p_max))` 的拼接。已由 GPU 上 `ckpt_1b_boost/halt_heads.pt` 元信息实测核实:cfg 为 `n_layer=24, hidden_size=1536, vocab_size=130560, eos=[1,130073], pad=1`,权重形状 `(1, 1537)`。
- **动态激活**:与 2B 相同——推理时逐层累计 `cum = 1-∏(1-p_l)`,`cum ≥ threshold` 即经共享 `norm + lm_head` 输出该 token 并提前退出;每个 token 独立决定退出层,可与 loop 机制正交。wrapper 逐层 forward,不修改 `modeling_llama.py`,保护 KV cache / generate。
- **训练配置(已核实)**:`ckpt_1b_boost/halt_heads.pt` 为 step 1000、`mode=full`,含自蒸馏(`kd=true, kd_weight=1.0, kd_temp=2.0, hidden_kd_weight=0.1`)、`halt_loss_scale=0.5`、`base_lr=2e-5 / head_lr=1e-4`、基座解冻(`base_unfrozen=true`)、layer dropout `p_max=0.2`、轮转出口 `rot_r=4`。基座与 tokenizer 完整保存在 `ckpt_1b_boost/full_model/`(含 `config.json`、`generation_config.json`、`model.safetensors` 约 2.1GB、`tokenizer.json` 等,已核实)。
### 3. 用法示例
> 依赖项目 wrapper `amoeba_train_perlayer.py`(待随权重发布);接口以实际脚本为准。
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer import AmoebaModel # 项目 wrapper(待发布)
BASE = "./full_model" # 发布后替换为 Hub 仓库(微调后的基座 + tokenizer)
HALT = "./halt_heads.pt" # step-1000 研究用 halt 决策权重
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("你好,请写一段关于动态激活的简短说明。", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
```
由于已发现退出坍缩(第 4 节),请使用**保守阈值**(如 0.95)并同时报告强制退出 CE / PPL / 平均退出层;`threshold` 过小会退到浅层并生成乱码。
### 4. 训练状态(诚实说明)
- **已产出研究用 checkpoint,待修复后发布**:`ckpt_1b_boost/full_model/`(完整基座权重)+ `ckpt_1b_boost/halt_heads.pt`(step 1000)均已落盘,GPU 上已核实。另有早期 `ckpt_1b/`、`ckpt_1b_perlayer/` 作为对照。
- **存在已知问题**:日志显示训练不稳定——`lm_ce` 在 14→25→12 间过山车,KD loss 在 1.8↔345 间锯齿震荡,梯度范数出现 7722~8311 的尖峰;逐层 CE 在 L4 之后几乎平坦(≈11.7),即"浅层与深层预测质量无差别",符合退出坍缩特征。质量门控验证尚未在本版本完成。**该 checkpoint 仅供研究复现,不应作为稳定发布版。**
- **修复方向**:按项目"退出坍缩修复方案"——`lam=0`、弱化均匀先验/熵正则、冻结教师自蒸馏(严禁 `kd_weight=1.0` 的移动教师)、加厚 CE 采样,并在冻结基座上单独重训/校准 halt 决策;修复完成并通过对齐口径的质量-速度评测后再正式发布。
### 5. License
- 基座 `openbmb/MiniCPM5-1B`:**Apache-2.0**;衍生权重整体以 **Apache-2.0** 发布(附 LICENSE + NOTICE,保留上游版权声明)。
- Amoeba 新增部分(halt head、wrapper、训练/评测脚本、本 card)同样为 **Apache-2.0**。
- 商标/背书:独立研究项目,**与 OpenBMB 无隶属或官方背书关系**。
- 数据署名:训练语料含 `nvidia/OpenMathReasoning`(CC-BY-4.0,见致谢);未复制 LayerSkip(CC-BY-NC)代码。
### 6. Citation / 致谢
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-1B}
}
```
- 基座:OpenBMB, *MiniCPM5-1B* (Apache-2.0).
- 方法思想:Schuster et al., *CALM*; Elhoushi et al., *LayerSkip*(仅论文思想,未用其代码)。
- 数据:BAAI/CCI3-Data (Apache-2.0)、open-thoughts/OpenThoughts-Agent-SFT-100K (Apache-2.0)、nvidia/OpenMathReasoning (**CC-BY-4.0**,特此署名)。
---
## English
**One-line summary**: Amoeba-1B is an independent research derivative of `openbmb/MiniCPM5-1B`. It attaches token-level halt heads to all 24 Transformer layers for per-token adaptive depth. One full research training run has completed and weights exist, but exit collapse is a known unresolved issue — currently a **research preview / pending official release**.
### 1. Base model
| Field | Value |
|---|---|
| Name | `openbmb/MiniCPM5-1B` |
| Architecture | `LlamaForCausalLM` (`model_type: llama`), fully isomorphic to the 2B model; no `trust_remote_code` |
| Layers | 24 |
| hidden_size / intermediate_size | **1536 / 4608** (not the outdated 2048/6144 assumption) |
| Attention | GQA, 16 Q / 2 KV heads, `head_dim=128`, RoPE `rope_theta=5e6` |
| Vocabulary | 130560 (same tokenizer/specials as 2B: `eos=[1, 130073]`, `pad=1`) |
| Context | 131072 (128K) |
| Precision | bfloat16, `tie_word_embeddings=false`, ~1.08B parameters |
| Base license | **Apache-2.0** |
### 2. Amoeba modification
- **Halt head**: one `nn.Linear(hidden_size + 1, 1)` per layer — for 1B, **`Linear(1537, 1) × 24`**, ~37k new parameters. Input = layer hidden state `h_i` plus token-level uncertainty `unc=tanh(-log(p_max))`. Verified from GPU checkpoint metadata (`ckpt_1b_boost/halt_heads.pt`): cfg `n_layer=24, hidden_size=1536, vocab_size=130560, eos=[1,130073], pad=1`, weight shape `(1, 1537)`.
- **Dynamic activation**: as in 2B — at inference each token accumulates `cum = 1-∏(1-p_l)` and exits at the first layer where `cum ≥ threshold`, via the shared `norm + lm_head`. Layer-by-layer wrapper forward leaves `modeling_llama.py` untouched, preserving KV cache / generate.
- **Training config (verified)**: `ckpt_1b_boost/halt_heads.pt` is step 1000, `mode=full`, with self-distillation (`kd=true, kd_weight=1.0, kd_temp=2.0, hidden_kd_weight=0.1`), `halt_loss_scale=0.5`, `base_lr=2e-5 / head_lr=1e-4`, base unfrozen, layer dropout `p_max=0.2`, rotating exits `rot_r=4`. Full fine-tuned base and tokenizer are stored in `ckpt_1b_boost/full_model/` (`model.safetensors` ~2.1GB, verified).
### 3. Usage
> Requires the project wrapper (`amoeba_train_perlayer.py`, to be released); adapt to the actual API.
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer import AmoebaModel # project wrapper (to be released)
BASE = "./full_model" # replace with released Hub repo (fine-tuned base + tokenizer)
HALT = "./halt_heads.pt" # step-1000 research halt weights
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("Hello, briefly describe dynamic activation.", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.95)
print(tok.decode(out[0], skip_special_tokens=True))
```
Because exit collapse is known (§4), use a **conservative threshold** (e.g. 0.95) and report forced-exit CE / PPL / mean exit layer alongside generation; small thresholds collapse to shallow layers and produce gibberish.
### 4. Training status (honest disclosure)
- **Research checkpoint produced; pending fixed release**: `ckpt_1b_boost/full_model/` (full base weights) + `ckpt_1b_boost/halt_heads.pt` (step 1000) are on disk (verified). Earlier `ckpt_1b/` and `ckpt_1b_perlayer/` serve as ablations.
- **Known issues**: logs show instability — `lm_ce` swings 14→25→12, KD loss oscillates 1.8↔345, gradient norms spike to 7722���8311; per-layer CE is nearly flat after L4 (~11.7), i.e. shallow and deep layers have indistinguishable prediction quality — a signature of exit collapse. Quality-gate validation has not been completed for this version. **Research reproduction only, not a stable release.**
- **Fix direction**: per the project's exit-collapse plan — `lam=0`, weaker uniformity/entropy terms, frozen-teacher distillation (never `kd_weight=1.0` with a moving teacher), thicker CE sampling, then retrain/calibrate halt decisions on a frozen base; official release only after aligned-quality speed/quality evaluation passes.
### 5. License
- Base `openbmb/MiniCPM5-1B` is **Apache-2.0**; derivative weights released under **Apache-2.0** (LICENSE + NOTICE, upstream notices preserved).
- All Amoeba additions (halt heads, wrapper, training/eval scripts, this card) are **Apache-2.0**.
- Trademark: independent research, **not affiliated with or endorsed by OpenBMB**.
- Data attribution: training data includes `nvidia/OpenMathReasoning` (**CC-BY-4.0**, credited); no LayerSkip (CC-BY-NC) code copied.
### 6. Citation / acknowledgements
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-1B}
}
```
- Base: OpenBMB, *MiniCPM5-1B* (Apache-2.0).
- Method inspiration: Schuster et al., *CALM*; Elhoushi et al., *LayerSkip* (ideas only, no code).
- Data: BAAI/CCI3-Data (Apache-2.0), open-thoughts/OpenThoughts-Agent-SFT-100K (Apache-2.0), nvidia/OpenMathReasoning (**CC-BY-4.0**, credited).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# -*- coding: utf-8 -*-
"""
Amoeba-DA inference: parallel draft heads + frozen-base batched verification.
Minimal, self-contained reference implementation. The released heads are medusa_chat.pt.
"""
import torch, torch.nn as nn, torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.cache_utils import DynamicCache
class DraftHead(nn.Module):
"""Residual bottleneck head: h + W2 SiLU(W1 h), W2 init=0."""
def __init__(self, H, bn=512):
super().__init__()
self.fc1 = nn.Linear(H, bn, bias=False)
self.fc2 = nn.Linear(bn, H, bias=False)
nn.init.zeros_(self.fc2.weight)
def forward(self, h):
return h + self.fc2(F.silu(self.fc1(h.float()))).to(h.dtype)
class AmoebaDA:
def __init__(self, model_path, head_path, device="cuda"):
self.tok = AutoTokenizer.from_pretrained(model_path)
self.m = AutoModelForCausalLM.from_pretrained(
model_path, dtype=torch.bfloat16, device_map=device).eval()
for p in self.m.parameters(): p.requires_grad_(False)
self.device = device
H = self.m.config.hidden_size
sd = torch.load(head_path, map_location=device, weights_only=False)
self.heads = nn.ModuleList([DraftHead(H).to(device) for _ in range(len(sd))])
for k, key in enumerate(sd): self.heads[k].load_state_dict(sd[key])
self.heads.eval()
self.K = len(self.heads)
self.eos = self.m.generation_config.eos_token_id
if not isinstance(self.eos, (list, tuple)): self.eos = [self.eos]
@torch.no_grad()
def _fwd(self, ids, cache, total):
kw = dict(input_ids=ids, use_cache=True, output_hidden_states=True,
attention_mask=torch.ones((ids.shape[0], total), device=ids.device,
dtype=torch.long))
kw["cache"] = cache
try: return self.m(**kw)
except TypeError:
kw.pop("cache"); kw["past_key_values"] = cache; return self.m(**kw)
@torch.no_grad()
def generate(self, prompt, max_new_tokens=96):
ids = self.tok(prompt, return_tensors="pt", add_special_tokens=False).to(self.device)["input_ids"]
cache = DynamicCache(); plen = ids.shape[1]
o = self._fwd(ids, cache, plen)
h = o.hidden_states[-1][:, -1, :]
cur = int(o.logits[0, -1].argmax())
seq = []
for _ in range(max_new_tokens):
seq.append(cur)
if cur in self.eos or len(seq) >= max_new_tokens: break
cand = []
if self.K > 0:
hs = torch.stack([hd(h) for hd in self.heads], 0) # [K,1,H]
cand = self.m.lm_head(self.m.model.norm(hs)).argmax(-1)[:, 0].tolist()
vt = torch.tensor([[cur] + cand], device=self.device, dtype=torch.long)
o = self._fwd(vt, cache, cache.get_seq_length() + vt.shape[1])
vlog, vh = o.logits[0], o.hidden_states[-1][0]
n = 1
for i in range(len(cand)):
if int(vlog[i].argmax()) == cand[i]: n += 1
else: break
for j in range(n - 1):
seq.append(cand[j])
if cand[j] in self.eos: break
remove = vt.shape[1] - n
if remove > 0:
try: cache.crop(-remove)
except Exception: break
idx = min(n - 1, vlog.shape[0] - 1)
h = vh[idx:idx + 1]
cur = int(vlog[idx].argmax())
if seq and seq[-1] in self.eos: break
return self.tok.decode(seq, skip_special_tokens=True)
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="Amoeba-1B/full_model")
ap.add_argument("--heads", default="Amoeba-1B/medusa_chat.pt")
ap.add_argument("--prompt", default="1+1等于几?")
a = ap.parse_args()
m = AmoebaDA(a.model, a.heads)
print(m.generate(a.prompt))123version https://git-lfs.github.com/spec/v1oid sha256:12a148686f744d6c9ddcedd41e08a0464c860b8670a38e399c2feacd13205997size 163189123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# -*- coding: utf-8 -*-"""amoeba_infer_with_gate.py — Amoeba 动态激活推理(带质量门,推荐用法)
关键:原始 halt head 会坍缩到浅层(L2-L6)导致乱码。质量门(conf_min)强制只有"该层对下一 token 的置信度 >= conf_min"才允许退出,把计算推到质量足够的深层,从而恢复生成质量。
用法: python amoeba_infer_with_gate.py --model-path <full_model目录> \ --ckpt <halt_heads.pt> --conf-min 0.85 --prompt "你好" # conf_min 越大越保守(质量越好、加速越少);推荐 0.8~0.95 # conf_min=1.0 等价全层(无早退);conf_min=0.0 等价无门(会坍缩,勿用)"""import sys, argparse, torchsys.stdout.reconfigure(encoding="utf-8", errors="replace")import torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer
ap = argparse.ArgumentParser()ap.add_argument("--model-path", required=True)ap.add_argument("--ckpt", default="")ap.add_argument("--conf-min", type=float, default=0.85, help="质量门:每层置信度下限,越大越保守")ap.add_argument("--threshold", type=float, default=0.9, help="halt 累积退出概率阈值")ap.add_argument("--prompt", default="你好")ap.add_argument("--max-new", type=int, default=96)ap.add_argument("--temperature", type=float, default=0.7)args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"tok = AutoTokenizer.from_pretrained(args.model_path)base = AutoModelForCausalLM.from_pretrained(args.model_path, dtype=torch.bfloat16, device_map=device).eval()base.config.use_cache = Falsen_layer = base.config.num_hidden_layershidden_size = base.config.hidden_size
# halt heads(与训练一致:Linear(hidden+1,1))halt_heads = torch.nn.ModuleList([torch.nn.Linear(hidden_size + 1, 1) for _ in range(n_layer)])if args.ckpt: obj = torch.load(args.ckpt, map_location="cpu", weights_only=False) sd = obj.get("halt_heads", obj) cleaned = {k.replace("halt_heads.", ""): v for k, v in sd.items()} halt_heads.load_state_dict(cleaned, strict=True) print(f"[load] halt heads from {args.ckpt}", flush=True)halt_heads = halt_heads.to(device).eval()
def unc_of(logits_1): p = F.softmax(logits_1.float(), dim=-1) pmax = p.max(dim=-1).values.clamp_min(1e-8) return torch.tanh(-torch.log(pmax))
def call_layer(layer, hidden, **kw): import inspect sig = inspect.signature(layer.forward) if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()): out = layer(hidden, **kw) else: out = layer(hidden, {k: v for k, v in kw.items() if k in sig.parameters}) return out[0] if isinstance(out, (tuple, list)) else out
@torch.no_grad()def generate(prompt): ctx = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" ids = tok(ctx, return_tensors="pt", add_special_tokens=False).to(device)["input_ids"] exits = [] for _ in range(args.max_new): T = ids.shape[1] emb = base.model.embed_tokens(ids) pos = torch.arange(T, device=device).unsqueeze(0) pe = base.model.rotary_emb(emb, pos) common = dict(attention_mask=None, position_ids=pos, past_key_value=None, past_key_values=None, output_attentions=False, use_cache=False, cache_position=torch.arange(T, device=device), position_embeddings=pe) h = emb hiddens = [] for layer in base.model.layers: h = call_layer(layer, h, **common) hiddens.append(h) remaining = torch.ones(1, device=device) chosen = None used = n_layer for i in range(n_layer): hl = hiddens[i][:, -1, :] logits = base.lm_head(base.model.norm(hl.unsqueeze(1)))[:, 0, :] conf = F.softmax(logits.float(), dim=-1).max(dim=-1).values # [1] p = torch.sigmoid(halt_heads[i](torch.cat([hl, unc_of(logits).unsqueeze(-1)], dim=-1)).squeeze(-1)) remaining = remaining * (1 - p) quality_ok = (conf >= args.conf_min) | (i >= n_layer - 2) if ((1 - remaining >= args.threshold) & quality_ok).all(): chosen = logits; used = i + 1; break if chosen is None: chosen = base.lm_head(base.model.norm(hiddens[-1][:, -1, :].unsqueeze(1)))[:, 0, :] used = n_layer if args.temperature <= 0: nxt = chosen.argmax(dim=-1, keepdim=True) else: nxt = torch.multinomial(F.softmax(chosen / args.temperature, dim=-1), 1) ids = torch.cat([ids, nxt], dim=1) exits.append(used) if nxt.item() in (1, 151645, 65512, 2): break reply = tok.decode(ids[0][ids.shape[1]-0:].tolist(), skip_special_tokens=True) if False else tok.decode(ids[0][len(tok(ctx, add_special_tokens=False)['input_ids']):].tolist(), skip_special_tokens=True) return reply, exits
print(f"[cfg] conf_min={args.conf_min} threshold={args.threshold} layers={n_layer}", flush=True)reply, exits = generate(args.prompt)print(f"用户: {args.prompt}\n助手: {reply}")print(f"[退出层均值 {sum(exits)/len(exits):.1f}/{n_layer} | 生成 {len(exits)} token]", flush=True)123version https://git-lfs.github.com/spec/v1oid sha256:58d741cf22d03c93eae5c7a3889520250d023c3dd329e364efa3efe6913bbf30size 25169839123456789101112131415161718192021Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
本仓库 Amoeba 模型的默认许可证为 Apache-2.0(基座 MiniCPM5 / Qwen3 为 Apache-2.0)。
完整许可证全文请见官方链接: http://www.apache.org/licenses/LICENSE-2.0
标准声明(发布时请按实际情况补充版权与 NOTICES):
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
注意:所有版本(含 Amoeba-0.3B 的 MNN-Pocket 基座)均为 Apache-2.0;用户可自行调整版权信息。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181> **Updated (Amoeba-DA).** This directory documents the original token-level early-exit research line, which was investigated and **rejected**. The shipped technique is **Amoeba-DA** (parallel draft heads + full-model verification): 2B 2.02×, 1B 1.30×, statistically lossless (not bit-exact). See the root `README.md` / `README_zh.md` and `docs/动态激活_完整实验矩阵.md`.
---
license: apache-2.0
base_model:
- openbmb/MiniCPM5-2B
library_name: transformers
pipeline_tag: text-generation
tags:
- dynamic-activation
- early-exit
- halt-head
- on-device
- research-preview
---
# Amoeba-2B
## 中文
**一句话简介**:Amoeba-2B 是 `openbmb/MiniCPM5-2B` 的独立研究衍生模型,在每一层 Transformer 后挂一个极轻量的 token 级 halt head,让每个 token 自适应决定经过多少层(动态深度 / early exit),目标是在少量质量代价下换取端侧推理加速。**当前状态:训练中 / 待发布(详见第 5 节)。**
### 1. 基座模型(Base model)
| 项目 | 值 |
|---|---|
| 名称 | `openbmb/MiniCPM5-2B` |
| 架构 | `LlamaForCausalLM`(`model_type: llama`),标准 Transformer Decoder-only,无需 `trust_remote_code` |
| 层数 | 42 |
| hidden_size / intermediate_size | 2048 / 6144 |
| 注意力 | GQA 16 个 Q 头 / 2 个 KV 头,`head_dim=128`,RoPE `rope_theta=5e6` |
| 词表 | 130560(BPE,ChatML 风格;`eos=[1, 130073]`,`pad=1`) |
| 上下文 | 131072(128K) |
| 精度 | bfloat16,`tie_word_embeddings=false` |
| 基座 License | **Apache-2.0**(官方 README 明确) |
### 2. Amoeba 改造说明
- **Halt head 结构**:在基座 `model.layers[i]` 的每层输出后挂一个 `nn.Linear(hidden_size + 1, 1)` 二分类门控;2B 为 `Linear(2049, 1) × 42`,总新增参数约 8.6 万(相对 2.6B 基座可忽略)。输入 = 该层隐状态 `h_i` 拼接 token 级不确定性标量 `unc = tanh(-log(p_max))`。`+1` 维与权重形状已由 GPU checkpoint 实测核实(`halt_heads.pt` 中 `0.weight` 形状为 `(1, 2049)`,cfg 为 `n_layer=42, hidden_size=2048, vocab_size=130560`)。
- **实现方式**:以 wrapper(`AmoebaModel`)逐层 forward,**不修改 `modeling_llama.py` 内部循环**,保留基座全部权重、tokenizer、KV cache 与 `generate` 兼容性。中间层输出经 `norm + lm_head` 得到 logits;注意力必须使用 SDPA(eager 下需显式传 4D 因果 mask)。
- **动态激活(推理)**:每个 token 独立维护累计退出概率 `cum = 1 - ∏(1 - p_l)`,`cum` 首次超过阈值 `threshold` 即在该层经 `norm + lm_head` 输出并停止后续层计算;阈值越大越保守(越接近全层 42 层)。训练目标为逐层 CE + anchor + 均匀先验 + 语义一致性 + 熵正则(LayerSkip 思想自研实现,**未复制 LayerSkip 的 CC-BY-NC 代码**)。
### 3. 用法示例
> 依赖:随权重发布的 `amoeba_train_perlayer.py` / `amoeba_eval.py`(当前尚未公开发布);下例接口以脚本实际定义为准(`AmoebaModel`、`generate_with_exits`)。
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer import AmoebaModel # 项目 wrapper(待随权重发布)
BASE = "openbmb/MiniCPM5-2B" # 替换为发布后的 Hub 仓库
HALT = "./halt_heads.pt" # 随本模型发布(修复版)
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
if "halt_heads" in ckpt:
model.halt_heads.load_state_dict(ckpt["halt_heads"]) # 修复版 ckpt
ids = tok("你好,请解释什么是动态早退。", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.9)
print(tok.decode(out[0], skip_special_tokens=True))
```
评测时请同时报告 **强制退出 CE 曲线 / PPL / 平均退出层 / 贪心生成质量**(`amoeba_eval.py`),不要只看训练日志的 CE。旧版 checkpoint 在 `threshold` 较小时会发生退出坍缩(见第 5 节),建议先用保守阈值并配合 top-1 置信度门(`conf_min≈0.95`)。
### 4. 训练状态(诚实说明)
- **主线修复训练中(训练中 / 待发布)**:2026-11-22 核实,GPU 上 `/data/work/ckpt_2b_fixed/` 目录当前为空;进程 `amoeba_train_perlayer.py --model-path /data/models/MiniCPM5-2B --mode baseline --lam 0 --halt-loss-scale 0.1 --p-max 0.10 --rot-r 8 --steps 400 --out-dir /data/work/ckpt_2b_fixed` 正在运行(约 step 120/400)。该轮按"退出坍缩修复方案 A"配置:关闭早退奖励 `lam=0`、减弱均匀先验、加厚 CE 采样,目标是先恢复全层质量再重训 halt 决策。**尚无修复版权重可用于发布。**
- **旧 checkpoint(不可作为发布版)**:`ckpt_2b_full_BUGGY_2354/halt_heads.pt`(step 800,实测形状 `Linear(2049,1)×42`)与 `ckpt_2b_tune/`、`ckpt_2b_full/` 属于早期训练。其逐层 CE 在 L8 之后几乎平坦(≈11.3),而质量门控扫描显示:低置信度门时早退 PPL 高达数千(退出坍缩到浅层、生成乱码),只有 `conf_min=0.95, threshold=0.9` 时早退 PPL≈24.8、平均退出层≈38.5(接近全层,加速收益很小)。这些 checkpoint 仅作研究记录,**不应下载使用**。
- **训练数据**:CCI3-Data(BAAI,Apache-2.0)+ 对话 SFT / agent / 数学推理数据(详见 Citation)。修复轮仅使用 CCI3 子集。
### 5. License
- 基座 `openbmb/MiniCPM5-2B`:**Apache-2.0**。本模型为 Apache-2.0 允许的衍生作品,整体以 **Apache-2.0** 发布(随仓库附 LICENSE + NOTICE,保留上游版权声明)。
- Amoeba 新增部分(halt head 结构、wrapper、训练与评测脚本、本 model card)同样采用 **Apache-2.0**。
- 商标/背书声明:这是独立研究项目,**与 OpenBMB 无隶属或官方背书关系**;模型名不含 "official"。
- 数据署名:训练数据含 `nvidia/OpenMathReasoning`(CC-BY-4.0,见致谢);**未复制** LayerSkip(CC-BY-NC)代码,仅按其论文公式自行实现。
### 6. Citation / 致谢
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-2B}
}
```
- 基座:OpenBMB, *MiniCPM5-2B* (Apache-2.0).
- 方法与思想来源:Schuster et al., *Confident Adaptive Language Modeling* (CALM); Elhoushi et al., *LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding*(仅引用论文思想,不含其代码).
- 数据:BAAI/CCI3-Data (Apache-2.0)、open-thoughts/OpenThoughts-Agent-SFT-100K (Apache-2.0)、nvidia/OpenMathReasoning (**CC-BY-4.0**,特此署名)。
- 感谢 GPU 实验环境与所有开源基座/数据发布方。
---
## English
**One-line summary**: Amoeba-2B is an independent research derivative of `openbmb/MiniCPM5-2B`. It attaches an ultra-lightweight token-level halt head after every Transformer layer so each token adaptively decides how many layers to traverse (dynamic depth / early exit), aiming for on-device speedups at a small quality cost. **Current status: training in progress / unreleased (see §5).**
### 1. Base model
| Field | Value |
|---|---|
| Name | `openbmb/MiniCPM5-2B` |
| Architecture | `LlamaForCausalLM` (`model_type: llama`), standard decoder-only Transformer; no `trust_remote_code` needed |
| Layers | 42 |
| hidden_size / intermediate_size | 2048 / 6144 |
| Attention | GQA, 16 Q / 2 KV heads, `head_dim=128`, RoPE `rope_theta=5e6` |
| Vocabulary | 130560 (BPE, ChatML style; `eos=[1, 130073]`, `pad=1`) |
| Context | 131072 (128K) |
| Precision | bfloat16, `tie_word_embeddings=false` |
| Base license | **Apache-2.0** (per official README) |
### 2. Amoeba modification
- **Halt head**: after each `model.layers[i]` output we place a binary gate `nn.Linear(hidden_size + 1, 1)` — for 2B, `Linear(2049, 1) × 42`, ~86k new parameters. Input = hidden state `h_i` concatenated with a token-level uncertainty scalar `unc = tanh(-log(p_max))`. Shapes were verified on the GPU checkpoint (`halt_heads.pt`: `0.weight` = `(1, 2049)`, cfg `n_layer=42, hidden_size=2048, vocab_size=130560`).
- **Implementation**: an `AmoebaModel` wrapper performs layer-by-layer forward **without touching `modeling_llama.py`**, preserving all base weights, tokenizer, KV cache and `generate` compatibility. Intermediate logits are computed via `norm + lm_head`; SDPA attention is required (eager attention needs an explicit 4D causal mask).
- **Dynamic activation at inference**: each token accumulates exit probability `cum = 1 - ∏(1 - p_l)`; the first layer where `cum` exceeds `threshold` emits the token via `norm + lm_head` and skips all later layers. Higher threshold = more conservative (closer to all 42 layers). Training uses per-layer CE + anchor + uniformity prior + semantic consistency + entropy regularization, reimplemented from published ideas (**no LayerSkip CC-BY-NC code copied**).
### 3. Usage
> Requires the project wrapper scripts (`amoeba_train_perlayer.py` / `amoeba_eval.py`), not yet publicly released; adapt to the actual API at release time.
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from amoeba_train_perlayer import AmoebaModel # project wrapper (to be released)
BASE = "openbmb/MiniCPM5-2B" # replace with the released Hub repo
HALT = "./halt_heads.pt"
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
model = AmoebaModel(base).eval().cuda()
ckpt = torch.load(HALT, map_location="cpu", weights_only=False)
if "halt_heads" in ckpt:
model.halt_heads.load_state_dict(ckpt["halt_heads"])
ids = tok("Hello, explain dynamic early exit.", return_tensors="pt").input_ids.cuda()
out = model.generate_with_exits(ids, max_new_tokens=64, threshold=0.9)
print(tok.decode(out[0], skip_special_tokens=True))
```
For evaluation, always report **forced-exit CE curve / PPL / mean exit layer / greedy generation quality** (`amoeba_eval.py`), not just training CE. Older checkpoints collapse to shallow exits at small thresholds; use a conservative threshold plus a top-1 confidence gate (`conf_min≈0.95`) until the fix is validated.
### 4. Training status (honest disclosure)
- **Mainline fix run IN PROGRESS (unreleased)**: verified on 2026-11-22 — `/data/work/ckpt_2b_fixed/` is currently empty, while `amoeba_train_perlayer.py --model-path /data/models/MiniCPM5-2B --mode baseline --lam 0 --halt-loss-scale 0.1 --p-max 0.10 --rot-r 8 --steps 400 --out-dir /data/work/ckpt_2b_fixed` is running (~step 120/400). This is "fix plan A": `lam=0`, weaker uniformity prior, thicker CE sampling — first recover full-layer quality, then retrain halt decisions. **No fixed weights are available for release yet.**
- **Old checkpoints (not for release)**: `ckpt_2b_full_BUGGY_2354/halt_heads.pt` (step 800, verified `Linear(2049,1)×42`), `ckpt_2b_tune/`, `ckpt_2b_full/`. Their per-layer CE is nearly flat after L8 (~11.3); quality-gate scans show early-exit PPL in the thousands at low confidence gates (exit collapse / gibberish), while `conf_min=0.95, threshold=0.9` yields PPL≈24.8 at mean exit layer ≈38.5 (near full depth, little speedup). These are research records only, **do not download**.
- **Training data**: CCI3-Data (BAAI, Apache-2.0) plus dialogue SFT / agent / math-reasoning data (see citations); the fix run uses only a CCI3 subset.
### 5. License
- Base `openbmb/MiniCPM5-2B` is **Apache-2.0**; derivative weights are released under **Apache-2.0** (LICENSE + NOTICE included; upstream copyright notices preserved).
- All Amoeba additions (halt heads, wrapper, training/eval scripts, this card) are **Apache-2.0**.
- Trademark: independent research, **not affiliated with or endorsed by OpenBMB**; no "official" in the model name.
- Data attribution: training data includes `nvidia/OpenMathReasoning` (**CC-BY-4.0**, credited above); **no LayerSkip (CC-BY-NC) code** was copied — only its published ideas were reimplemented.
### 6. Citation / acknowledgements
```bibtex
@misc{amoeba2026,
title = {Amoeba: Token-Level Dynamic Activation via Per-Layer Halt Heads},
year = {2026},
note = {Independent research project; model card for Amoeba-2B}
}
```
- Base: OpenBMB, *MiniCPM5-2B* (Apache-2.0).
- Method inspiration: Schuster et al., *Confident Adaptive Language Modeling* (CALM); Elhoushi et al., *LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding* (ideas only, no code).
- Data: BAAI/CCI3-Data (Apache-2.0), open-thoughts/OpenThoughts-Agent-SFT-100K (Apache-2.0), nvidia/OpenMathReasoning (**CC-BY-4.0**, credited).
- Thanks to the open-source base/data communities and the GPU environment used for experiments.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# -*- coding: utf-8 -*-
"""
Amoeba-DA inference: parallel draft heads + frozen-base batched verification.
Minimal, self-contained reference implementation. The released heads are medusa_chat.pt.
"""
import torch, torch.nn as nn, torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.cache_utils import DynamicCache
class DraftHead(nn.Module):
"""Residual bottleneck head: h + W2 SiLU(W1 h), W2 init=0."""
def __init__(self, H, bn=512):
super().__init__()
self.fc1 = nn.Linear(H, bn, bias=False)
self.fc2 = nn.Linear(bn, H, bias=False)
nn.init.zeros_(self.fc2.weight)
def forward(self, h):
return h + self.fc2(F.silu(self.fc1(h.float()))).to(h.dtype)
class AmoebaDA:
def __init__(self, model_path, head_path, device="cuda"):
self.tok = AutoTokenizer.from_pretrained(model_path)
self.m = AutoModelForCausalLM.from_pretrained(
model_path, dtype=torch.bfloat16, device_map=device).eval()
for p in self.m.parameters(): p.requires_grad_(False)
self.device = device
H = self.m.config.hidden_size
sd = torch.load(head_path, map_location=device, weights_only=False)
self.heads = nn.ModuleList([DraftHead(H).to(device) for _ in range(len(sd))])
for k, key in enumerate(sd): self.heads[k].load_state_dict(sd[key])
self.heads.eval()
self.K = len(self.heads)
self.eos = self.m.generation_config.eos_token_id
if not isinstance(self.eos, (list, tuple)): self.eos = [self.eos]
@torch.no_grad()
def _fwd(self, ids, cache, total):
kw = dict(input_ids=ids, use_cache=True, output_hidden_states=True,
attention_mask=torch.ones((ids.shape[0], total), device=ids.device,
dtype=torch.long))
kw["cache"] = cache
try: return self.m(**kw)
except TypeError:
kw.pop("cache"); kw["past_key_values"] = cache; return self.m(**kw)
@torch.no_grad()
def generate(self, prompt, max_new_tokens=96):
ids = self.tok(prompt, return_tensors="pt", add_special_tokens=False).to(self.device)["input_ids"]
cache = DynamicCache(); plen = ids.shape[1]
o = self._fwd(ids, cache, plen)
h = o.hidden_states[-1][:, -1, :]
cur = int(o.logits[0, -1].argmax())
seq = []
for _ in range(max_new_tokens):
seq.append(cur)
if cur in self.eos or len(seq) >= max_new_tokens: break
cand = []
if self.K > 0:
hs = torch.stack([hd(h) for hd in self.heads], 0) # [K,1,H]
cand = self.m.lm_head(self.m.model.norm(hs)).argmax(-1)[:, 0].tolist()
vt = torch.tensor([[cur] + cand], device=self.device, dtype=torch.long)
o = self._fwd(vt, cache, cache.get_seq_length() + vt.shape[1])
vlog, vh = o.logits[0], o.hidden_states[-1][0]
n = 1
for i in range(len(cand)):
if int(vlog[i].argmax()) == cand[i]: n += 1
else: break
for j in range(n - 1):
seq.append(cand[j])
if cand[j] in self.eos: break
remove = vt.shape[1] - n
if remove > 0:
try: cache.crop(-remove)
except Exception: break
idx = min(n - 1, vlog.shape[0] - 1)
h = vh[idx:idx + 1]
cur = int(vlog[idx].argmax())
if seq and seq[-1] in self.eos: break
return self.tok.decode(seq, skip_special_tokens=True)
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="Amoeba-2B/full_model")
ap.add_argument("--heads", default="Amoeba-2B/medusa_chat.pt")
ap.add_argument("--prompt", default="1+1等于几?")
a = ap.parse_args()
m = AmoebaDA(a.model, a.heads)
print(m.generate(a.prompt))123version https://git-lfs.github.com/spec/v1oid sha256:3fcdbb2b437c15b21bfc85c4be3cc0f7eb785f1890e4db3aaf7bd4e5b503cd24size 370485123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# -*- coding: utf-8 -*-"""amoeba_infer_with_gate.py — Amoeba 动态激活推理(带质量门,推荐用法)
关键:原始 halt head 会坍缩到浅层(L2-L6)导致乱码。质量门(conf_min)强制只有"该层对下一 token 的置信度 >= conf_min"才允许退出,把计算推到质量足够的深层,从而恢复生成质量。
用法: python amoeba_infer_with_gate.py --model-path <full_model目录> \ --ckpt <halt_heads.pt> --conf-min 0.85 --prompt "你好" # conf_min 越大越保守(质量越好、加速越少);推荐 0.8~0.95 # conf_min=1.0 等价全层(无早退);conf_min=0.0 等价无门(会坍缩,勿用)"""import sys, argparse, torchsys.stdout.reconfigure(encoding="utf-8", errors="replace")import torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoTokenizer
ap = argparse.ArgumentParser()ap.add_argument("--model-path", required=True)ap.add_argument("--ckpt", default="")ap.add_argument("--conf-min", type=float, default=0.85, help="质量门:每层置信度下限,越大越保守")ap.add_argument("--threshold", type=float, default=0.9, help="halt 累积退出概率阈值")ap.add_argument("--prompt", default="你好")ap.add_argument("--max-new", type=int, default=96)ap.add_argument("--temperature", type=float, default=0.7)args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"tok = AutoTokenizer.from_pretrained(args.model_path)base = AutoModelForCausalLM.from_pretrained(args.model_path, dtype=torch.bfloat16, device_map=device).eval()base.config.use_cache = Falsen_layer = base.config.num_hidden_layershidden_size = base.config.hidden_size
# halt heads(与训练一致:Linear(hidden+1,1))halt_heads = torch.nn.ModuleList([torch.nn.Linear(hidden_size + 1, 1) for _ in range(n_layer)])if args.ckpt: obj = torch.load(args.ckpt, map_location="cpu", weights_only=False) sd = obj.get("halt_heads", obj) cleaned = {k.replace("halt_heads.", ""): v for k, v in sd.items()} halt_heads.load_state_dict(cleaned, strict=True) print(f"[load] halt heads from {args.ckpt}", flush=True)halt_heads = halt_heads.to(device).eval()
def unc_of(logits_1): p = F.softmax(logits_1.float(), dim=-1) pmax = p.max(dim=-1).values.clamp_min(1e-8) return torch.tanh(-torch.log(pmax))
def call_layer(layer, hidden, **kw): import inspect sig = inspect.signature(layer.forward) if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()): out = layer(hidden, **kw) else: out = layer(hidden, {k: v for k, v in kw.items() if k in sig.parameters}) return out[0] if isinstance(out, (tuple, list)) else out
@torch.no_grad()def generate(prompt): ctx = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" ids = tok(ctx, return_tensors="pt", add_special_tokens=False).to(device)["input_ids"] exits = [] for _ in range(args.max_new): T = ids.shape[1] emb = base.model.embed_tokens(ids) pos = torch.arange(T, device=device).unsqueeze(0) pe = base.model.rotary_emb(emb, pos) common = dict(attention_mask=None, position_ids=pos, past_key_value=None, past_key_values=None, output_attentions=False, use_cache=False, cache_position=torch.arange(T, device=device), position_embeddings=pe) h = emb hiddens = [] for layer in base.model.layers: h = call_layer(layer, h, **common) hiddens.append(h) remaining = torch.ones(1, device=device) chosen = None used = n_layer for i in range(n_layer): hl = hiddens[i][:, -1, :] logits = base.lm_head(base.model.norm(hl.unsqueeze(1)))[:, 0, :] conf = F.softmax(logits.float(), dim=-1).max(dim=-1).values # [1] p = torch.sigmoid(halt_heads[i](torch.cat([hl, unc_of(logits).unsqueeze(-1)], dim=-1)).squeeze(-1)) remaining = remaining * (1 - p) quality_ok = (conf >= args.conf_min) | (i >= n_layer - 2) if ((1 - remaining >= args.threshold) & quality_ok).all(): chosen = logits; used = i + 1; break if chosen is None: chosen = base.lm_head(base.model.norm(hiddens[-1][:, -1, :].unsqueeze(1)))[:, 0, :] used = n_layer if args.temperature <= 0: nxt = chosen.argmax(dim=-1, keepdim=True) else: nxt = torch.multinomial(F.softmax(chosen / args.temperature, dim=-1), 1) ids = torch.cat([ids, nxt], dim=1) exits.append(used) if nxt.item() in (1, 151645, 65512, 2): break reply = tok.decode(ids[0][ids.shape[1]-0:].tolist(), skip_special_tokens=True) if False else tok.decode(ids[0][len(tok(ctx, add_special_tokens=False)['input_ids']):].tolist(), skip_special_tokens=True) return reply, exits
print(f"[cfg] conf_min={args.conf_min} threshold={args.threshold} layers={n_layer}", flush=True)reply, exits = generate(args.prompt)print(f"用户: {args.prompt}\n助手: {reply}")print(f"[退出层均值 {sum(exits)/len(exits):.1f}/{n_layer} | 生成 {len(exits)} token]", flush=True)123version https://git-lfs.github.com/spec/v1oid sha256:cd5b64a32fb399090aabfce2f032e2d55a7754c776636ec932b7c0f488d7e7cbsize 3355840512345678910# Model weights
Weights are hosted on HuggingFace (GitHub file-size limits):
- [leexamp/Amoeba-2B](https://huggingface.co/leexamp/Amoeba-2B) — `huggingface-cli download leexamp/Amoeba-2B`
- [leexamp/Amoeba-1B](https://huggingface.co/leexamp/Amoeba-1B) — `huggingface-cli download leexamp/Amoeba-1B`
- [leexamp/Amoeba-0.6B](https://huggingface.co/leexamp/Amoeba-0.6B) — `huggingface-cli download leexamp/Amoeba-0.6B`
- [leexamp/Amoeba-0.3B](https://huggingface.co/leexamp/Amoeba-0.3B) — `huggingface-cli download leexamp/Amoeba-0.3B`
The 120M early checkpoint is not a standalone HF model (needs conversion) and is omitted.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758---
license: apache-2.0
base_model:
- openbmb/MiniCPM5-2B # replace per variant
datasets:
- in-house synthetic tool-use dialogues (self-generated from base models)
library_name: transformers
pipeline_tag: text-generation
tags:
- amoeba
- speculative-decoding
- tool-calling
- on-device
---
# Amoeba-{SIZE}
Amoeba-{SIZE} is an independent research derivative of **{BASE}** (Apache-2.0). It is
post-trained for tool calling and, for 2B/1B, ships parallel draft heads for
Amoeba-DA verified speculative decoding. This is **not** an official model of the base
model's organization.
## What was changed
- Tool-use SFT on synthetic self-generated tool-call dialogues (calculator, weather,
search, time), merged into a standalone checkpoint.
- For 2B/1B only: K parallel bottleneck draft heads (`medusa_chat.pt`) trained on
model-generated chat data; the backbone weights are unchanged.
## How to use
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained(".")
model = AutoModelForCausalLM.from_pretrained(".", dtype="auto", device_map="auto")
# tool calls require a tool-definition system message (see repo agent_infer.py)
# recommended sampling: temperature=0.8, top_p=0.95, repetition_penalty=1.05
```
## Reported results
- Tool-call success: {TOOL}
- Amoeba-DA speedup: {SPEED} (single RTX 4080S, HF generate, greedy)
- Greedy decoding may loop on long answers; use the sampling settings above.
## Limitations
Amoeba-DA output matches greedy decoding up to bf16 near-ties (statistically near-lossless,
not bit-exact). Speedup depends on draft acceptance rate; on Qwen3-8B the same method
gives only 1.1–1.4×. An earlier early-exit line was rejected and is not shipped.
Released tool SFT used only in-house synthetic dialogues; CCI3 and OpenMathReasoning
were used in abandoned experiments only.
## License and attribution
Apache-2.0. Derivative of {BASE} (Apache-2.0). No LayerSkip code was copied
(CC-BY-NC); its ideas were implemented from the paper. Independent research project,
not affiliated with the base model providers.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155{
"name": "Amoeba release",
"version": "1.2",
"license": "apache-2.0",
"date": "2026-11-25",
"github": "https://github.com/leexamp/Amoeba",
"huggingface": "https://huggingface.co/leexamp",
"files": [
{
"path": "AMOEBA_PAPER_DRAFT.docx",
"bytes": 88438,
"sha256": "de397de8786d7fc4e20b44a0bd0988181ebb4272f4e4378b66652f7ec4c62129"
},
{
"path": "AMOEBA_PAPER_DRAFT.pdf",
"bytes": 114091,
"sha256": "f54ba50c83d9b02608920b213bcb7207820228e0ed5bf201a8440e8c411e0915"
},
{
"path": "AMOEBA_PAPER_DRAFT.tex",
"bytes": 50464,
"sha256": "6bb506fafff9155d5bce816cdcba5e47bc3e8d2061fc0d6398090dbd14e8557a"
},
{
"path": "DOWNLOAD.md",
"bytes": 644,
"sha256": "5e64f4cc39e122b5ef73004c3ca3ad785ec32c3bff3559100da5ae347871fde5"
},
{
"path": "HF_MODEL_CARD_TEMPLATE.md",
"bytes": 2174,
"sha256": "0563d7c215e799d843a1e96675c5ba50d5677b0c63ec056a01c775bd224d75a5"
},
{
"path": "LICENSE",
"bytes": 11357,
"sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
},
{
"path": "README.md",
"bytes": 4484,
"sha256": "7a99bd18dcf2463a3c0a564c0d4b2fd12717e25bb6ec8d273c16e490393357b4"
},
{
"path": "README_legacy_earlyexit.md",
"bytes": 23924,
"sha256": "0b26bfbc7b8d35d84830a312b567f96591b28eb37445198d5d7a7285299f08dd"
},
{
"path": "README_zh.md",
"bytes": 4159,
"sha256": "6ae14797eb030a218aa84162b4b21d088bb70d5af1e1cc40d575d1340a5fec57"
},
{
"path": "README_zh_legacy.md",
"bytes": 20730,
"sha256": "d5c6c216631d8be0c47d449434fdc0985b837ab773396d319bb88487ad32a3d0"
},
{
"path": "Amoeba-0.3B\\infer_with_gate.py",
"bytes": 5229,
"sha256": "1630dc74e4ec64e7cc6894d3dcbb1136ae2439eb012ed569deb738b043ae9f4c"
},
{
"path": "Amoeba-0.3B\\LICENSE",
"bytes": 1039,
"sha256": "d1e5a8c9991c338cfad3c995d0b057ded0f333803c11d1c093e53a6a5e12e807"
},
{
"path": "Amoeba-0.3B\\README.md",
"bytes": 13504,
"sha256": "41b024612f7993ab87c4aed4b2cb6f31acd0b6b30fc3954e9f92d33985ce8ed4"
},
{
"path": "Amoeba-0.6B\\infer_with_gate.py",
"bytes": 5229,
"sha256": "1630dc74e4ec64e7cc6894d3dcbb1136ae2439eb012ed569deb738b043ae9f4c"
},
{
"path": "Amoeba-0.6B\\LICENSE",
"bytes": 1039,
"sha256": "d1e5a8c9991c338cfad3c995d0b057ded0f333803c11d1c093e53a6a5e12e807"
},
{
"path": "Amoeba-0.6B\\README.md",
"bytes": 12308,
"sha256": "f64f8a410c0aca1d8d9d7df21b0601274c8b28b1d23959f87ce6d627a781cb0c"
},
{
"path": "Amoeba-1B\\amoeba_da_infer.py",
"bytes": 4066,
"sha256": "a3049632aa55d414d40ec7dbad7f4a788c4345c14166c66b3e707480631c59ae"
},
{
"path": "Amoeba-1B\\infer_with_gate.py",
"bytes": 5229,
"sha256": "1630dc74e4ec64e7cc6894d3dcbb1136ae2439eb012ed569deb738b043ae9f4c"
},
{
"path": "Amoeba-1B\\LICENSE",
"bytes": 1039,
"sha256": "d1e5a8c9991c338cfad3c995d0b057ded0f333803c11d1c093e53a6a5e12e807"
},
{
"path": "Amoeba-1B\\medusa_chat.pt",
"bytes": 25169839,
"sha256": "58d741cf22d03c93eae5c7a3889520250d023c3dd329e364efa3efe6913bbf30"
},
{
"path": "Amoeba-1B\\README.md",
"bytes": 11705,
"sha256": "cb050ff642de49c9588ec151c1bed4460d71c02e138a298d8d3d2777c370fe8d"
},
{
"path": "Amoeba-2B\\amoeba_da_infer.py",
"bytes": 4066,
"sha256": "b35b017c741d6ac0485c145f20400d19be96648111c1ecd48a35a1e3642ea554"
},
{
"path": "Amoeba-2B\\infer_with_gate.py",
"bytes": 5229,
"sha256": "1630dc74e4ec64e7cc6894d3dcbb1136ae2439eb012ed569deb738b043ae9f4c"
},
{
"path": "Amoeba-2B\\LICENSE",
"bytes": 1039,
"sha256": "d1e5a8c9991c338cfad3c995d0b057ded0f333803c11d1c093e53a6a5e12e807"
},
{
"path": "Amoeba-2B\\medusa_chat.pt",
"bytes": 33558405,
"sha256": "cd5b64a32fb399090aabfce2f032e2d55a7754c776636ec932b7c0f488d7e7cb"
},
{
"path": "Amoeba-2B\\README.md",
"bytes": 13205,
"sha256": "d1be322d2de6dc0fccc771310da52fb50b4d8060a3ffd94f8e9002214e46d8d1"
},
{
"path": "_LICENSES\\APACHE-2.0.txt",
"bytes": 11357,
"sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
},
{
"path": "_LICENSES\\LICENSE_NOTE.md",
"bytes": 3674,
"sha256": "4c1c2d3c9210e7d644e71140ba296cd3eb903255dfc3f8e54e76164ed1cec097"
},
{
"path": "_LICENSES\\MIT.txt",
"bytes": 1065,
"sha256": "6b198160f4dbfa1d792ef1b9be03db36e3e63d9edbacf1faec8d50510358bc78"
}
]
}123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Amoeba**Capability-preserving dynamic activation for small language models — an empirical boundary study.**Amoeba is a family of four Apache-2.0 models (0.3B / 0.6B / 1B / 2B) built on MiniCPM5,Qwen3 and MNN-Pocket bases. It ships:- **Amoeba-DA** — verifier-based speculative decoding: K parallel bottleneck draft headspropose future tokens from one cached hidden state, and the frozen base model verifies allcandidates in one batched forward. Only released for the 2B and 1B models.- **Tool calling** — all four sizes are post-trained to emit tool calls, with a ReActinference script included.> **Research status.** This is an empirical study, not a universal accelerator. The central> finding is that acceleration is **architecture- and harness-dependent**: Amoeba-DA gives a> clean 2.015x on full-attention MiniCPM5-2B, but sliding-window hybrids (Gemma, SparkX) and> MoE/KDA models (Ling) do not benefit. All speedups are measured against a Python-bound> HuggingFace `generate` harness; under vLLM the same model already runs much faster. The paper> reports all withdrawn, failed and abandoned results in full. Token-level early exit was> systematically tested (16 experiments) and **rejected**; no released model ships it.## Results (single RTX 4080S 32GB; HF `generate`, greedy)| Model | Base | Amoeba-DA speedup | Capability | Tool calling ||---|---|---|---|---|| Amoeba-2B | MiniCPM5-2B | **2.015x** (26.6 -> 53.6 tok/s) | 79 QA: 91.14% -> 93.67%, **0 regressions** | 4/4 || Amoeba-1B | MiniCPM5-1B | **1.30x** | -- | 4/4 || Amoeba-0.6B | Qwen3-0.6B | not shipped | -- | 3/3 || Amoeba-0.3B | MNN-Pocket-0.3B | not shipped | -- | 3/3 |We do **not** claim bit-exact losslessness: token agreement on 2B is 0.734. The claim is*downstream capability preservation*, measured on 79 objective questions with zerocorrect-to-incorrect flips (ROUGE-L 0.94). An orthogonal mechanism, dynamic loop-depthrouting on SenseNova-Loop-9B, gives 45% at +0.04 nats CE — a quality-for-speed trade-off,reported separately. All Qwen-family speedups are WITHDRAWN (verification engineincompatible with its KV cache).## Repository layout```Amoeba-2B/ Amoeba-1B/ Amoeba-0.6B/ Amoeba-0.3B/full_model/ # standalone HF checkpoint (tokenizer + safetensors)README.md # per-model cardLICENSEamoeba_da_infer.py # draft-head inference (2B/1B only)AMOEBA_PAPER_DRAFT.pdf / .tex / .docx # 12-page research reportMANIFEST.json # checksums and file inventory_LICENSES/ # upstream license texts```## Quick start```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizerp = "Amoeba-2B/full_model"tok = AutoTokenizer.from_pretrained(p)model = AutoModelForCausalLM.from_pretrained(p, dtype="auto", device_map="auto")out = model.generate(**tok("你好", return_tensors="pt").to(model.device),max_new_tokens=128, do_sample=True,temperature=0.8, top_p=0.95, repetition_penalty=1.05)print(tok.decode(out[0], skip_special_tokens=True))```Greedy decoding can loop on long answers — use the sampling settings above. Tool callingrequires a tool-definition system message; see `amoeba_da_infer.py` / `infer_with_gate.py`.## Paper`AMOEBA_PAPER_DRAFT.pdf` — *Amoeba: From Early Exit to Verified Speculative Decoding andDynamic Loop Routing*. Sections cover the rejected early-exit line, Amoeba-DA capabilityevaluation and architecture boundaries, alternative mechanisms (more heads, forward-KL,KV prediction), the loop-routing result, a vLLM serving check, the full negative-resultrecord, and positioning relative to Medusa / EAGLE / JetSpec / LCKV / CLA / AttentionPredictor/ KV-Direct. We claim no novelty for the draft-head-and-verify mechanism.## LicenseAll Amoeba weights and this repository are Apache-2.0. Base models remain Apache-2.0(MiniCPM5, Qwen3, MNN-Pocket). No LayerSkip (CC-BY-NC) code was copied; its ideas wereimplemented from the paper. CCI3 and other dirty corpora were used in abandoned experimentsonly and are **not** part of any released checkpoint. Independent research project, notaffiliated with OpenBMB / Alibaba / Taobao.## Citation```bibtex@misc{amoeba2026,title = {Amoeba: From Early Exit to Verified Speculative Decoding and Dynamic Loop Routing},author = {Weikai Yue and Hy 4 flash},year = {2026},note = {Independent research report}}```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373---
license: apache-2.0
base_model:
- openbmb/MiniCPM5-2B
- openbmb/MiniCPM5-1B
- Qwen/Qwen3-0.6B
- taobao-mnn/MNN-Pocket-0.3B
datasets:
- in-house synthetic tool-use dialogues (self-generated from base models)
library_name: transformers
pipeline_tag: text-generation
tags:
- dynamic-activation
- amoeba-da
- verified-speculative-decoding
- tool-calling
- on-device
- efficient-inference
---
# Amoeba: Verified Dynamic Activation for Language Models
**Amoeba** is a family of language models with **Amoeba-DA** (verified dynamic activation) and tool-calling (agent) capability. Amoeba-DA uses K parallel draft heads to propose tokens `t+2..t+K+1` from a single hidden state; the untouched base model verifies all candidates in one batched forward. A candidate is accepted only if it matches the target model's own greedy argmax, so decoding is statistically equivalent to full-depth greedy decoding.
> **Status (updated).** The earlier token-level early-exit (halt head) line was systematically rejected — 16 measured routes all failed on this 42-layer deep-narrow architecture. The shipped technique is **Amoeba-DA**: **2.02×** on Amoeba-2B (27.1 → 54.7 tok/s, RTX 4080S) and **1.30×** on Amoeba-1B. Tool calling is included (2B/1B LoRA SFT; 0.6B/0.3B native tool templates). See §5 and `docs/动态激活_完整实验矩阵.md`.
---
## 1. Introduction
Conventional transformers apply the same number of layers to every token. This is wasteful on device and edge scenarios, where a large fraction of tokens (function words, punctuation, easy continuations) could be resolved with far less computation.
Amoeba augments a pretrained base model with a lightweight **per-layer halt head**. At each layer, the model asks a learned binary question: *"can I stop here?"* A token exits as soon as its **cumulative exit probability** crosses a confidence threshold. The result is a model whose effective depth adapts per token and per prompt, controlled by a single inference-time `threshold`.
The design is deliberately base-agnostic. The same wrapper has been applied across three model families (MiniCPM5, Qwen3, MNN-Pocket) and four scales, from 2B down to 120M, to study how the quality–speed tradeoff scales with model size.
---
## 2. Core Innovation
> **Historical scope.** Sections 2–4 and 6 document the *early-exit* research line, which was investigated and **rejected** (see §5.2b and the experiment matrix). It is retained as the rationale for the design choice, not as a claimed capability of the released checkpoints. The shipped technique is Amoeba-DA (parallel draft heads + full-model verification).
### 2.1 Per-layer halt heads
For a base model with `L` transformer layers and hidden size `H`, Amoeba attaches one halt head after every layer:
```python
halt_heads = nn.ModuleList([
nn.Linear(H + 1, 1) for _ in range(L)
])
```
The `+1` input is a **token-level uncertainty scalar** derived from the next-token distribution at that layer:
```
unc = tanh(-log(p_max)) # p_max = max softmax probability of the layer's logits
score_l = halt_heads[l](concat(h_l, unc)) # h_l = hidden state at layer l
p_l = sigmoid(score_l)
```
Intuitively, a token that the layer is already confident about (high `p_max`, low `unc`) is a better candidate for early exit. The uncertainty signal lets the halt head condition its decision on both the representation and the model's confidence.
### 2.2 Exit decision by cumulative probability
Exit is not decided by a single layer in isolation. The halt head emits a per-layer probability `p_l`, and the model tracks the **cumulative exit probability**:
```
survival = Π_{j<l} (1 - p_j) # probability of having survived to layer l
P(exit by layer l) = 1 - survival
```
A token exits at the first layer where `1 - survival >= threshold`. A **higher `threshold` is more conservative** — the token traverses more layers before stopping; `threshold = 1.0` effectively forces full-depth evaluation. This gives practitioners a single knob to trade speed for quality at inference time.
### 2.3 The halt loss
The halt heads are trained with a composite objective designed to avoid confident-but-wrong early exits:
| Term | Purpose |
|---|---|
| **Uniform prior** | Encourage an approximately uniform distribution over exit layers so that every exit point is trained, rather than collapsing onto a single shallow layer. |
| **Semantic consistency** | Constrain intermediate-layer outputs to agree semantically with the final layer (via KL divergence and/or cosine similarity on logits / normalized hidden states). This is the key to *losing less quality* at early exits. |
| **Entropy regularization** | Penalize premature collapse of the halt distribution toward one-hot decisions, stabilizing training. |
| **Route loss** | Weight each layer's language-model loss by the probability of routing to it, so the halt head is optimized for token-level language modeling. |
The distinguishing claim of this design is that a learned halt head with semantic and entropy constraints should **lose less quality than a plain confidence threshold** — a hypothesis we are quantifying rather than asserting.
### 2.4 Per-layer reinforcement training
An early failure taught us that training only the halt heads (with a frozen base) is insufficient: the per-layer language-model loss becomes a *read-only probe* with no path to update the decoder, so intermediate layers never become "exitable." The remedy is **per-layer reinforcement training**:
- **Unfreeze the decoder** so that the per-layer cross-entropy gradients actually reach the layers that produce each intermediate hidden state.
- **Per-layer independent LM loss**, computed at every enabled exit with **uniform or inverse-CE exit weights** (rather than a quadratic weighting that starves the shallow layers).
- **Final-layer anchor** (`L_anchor`) to prevent catastrophic forgetting of full-depth quality.
- **Layer dropout** (LayerSkip-style, `p_max ≈ 0.1–0.2`): stochastically skip deeper layers during training so that shallow layers learn to carry predictive information themselves.
- **Self-distillation** from the final layer to intermediate exits (KL on logits + cosine on representations), used as a refinement after per-layer CE is under control.
After the base is strengthened, the halt heads are **recalibrated** on the new hidden-state distribution. This "train the athlete, then train the judge" ordering is central to the method.
### 2.5 Ideas, not copied code
Layer dropout, early-exit language-model loss, and self-distillation are **ideas** inspired by published research (LayerSkip, Elhoushi et al. 2024; CALM, Schuster et al. 2022). Our implementation is written from scratch. **No LayerSkip source code was copied** — see [License & Acknowledgments](#7-license--acknowledgments).
---
## 3. Model Family
| Variant | Base | Arch | Layers | Hidden | Vocab | Status |
|---|---|---|---:|---:|---:|---|
| **Amoeba-2B** | MiniCPM5-2B | `LlamaForCausalLM` | 42 | 2048 | 130560 | Main line; active development (exit-collapse fix in progress) |
| **Amoeba-1B** | MiniCPM5-1B | `LlamaForCausalLM` | 24 | 1536 | 130560 | Weights prepared; adaptation smoke-tested |
| **Amoeba-0.6B** | Qwen3-0.6B | `Qwen3ForCausalLM` | 28 | 1024 | 151936 | Configs validated; training in progress |
| **Amoeba-0.3B** | MNN-Pocket-0.3B | `Qwen3ForCausalLM` | 28 | 896 | 65536 | Configs validated; training in progress |
| **Amoeba-120M** | Custom tiny testbed | Qwen3-like | 16 | 768 | 4104 | Testbed only — mechanism validated, base too weak for quality evaluation |
**Notes on the variants**
- **2B / 1B** share the MiniCPM5 tokenizer, vocabulary (130560), and special tokens (`eos = [1, 130073]`, `pad = 1`). The 1B model has `hidden_size = 1536` (not 2048), so all dimensions are read dynamically from `config`.
- **0.6B / 0.3B** are native `Qwen3ForCausalLM` models (not "Llama-like") with Qwen3's `q_norm`/`k_norm` inside the attention layers. They are loaded with `AutoModelForCausalLM`; `trust_remote_code` is not required. Their EOS/PAD ids differ (`0.6B: 151645 / 151643`, `0.3B: 65512 / 65510`) and corpora must be re-tokenized to each base's vocabulary.
- **120M** is a small testbed built during an earlier, now-deprecated small-vocabulary experiment. Its dynamic-activation mechanism works (depth responds smoothly to `threshold`), but generation quality is too poor to evaluate early-exit quality loss; it is included only as a mechanistic demonstration.
- The family spans **three base-model families and four scales**, enabling a scaling study of "dynamic-activation benefit vs. model size." The 2B line is the validation target; the smaller variants follow once the method is confirmed.
---
## 4. Usage
Amoeba does not modify the base model's modeling code. It uses a **thin wrapper** that holds the base model plus the halt heads and steps through layers manually. This preserves `generate()` behavior and avoids breaking KV-cache handling in `transformers`.
### 4.1 Loading
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
class AmoebaModel:
"""Base LM + one halt head per layer. No changes to modeling_*.py."""
def __init__(self, base, halt_heads):
self.base, self.halt_heads = base, halt_heads
@classmethod
def from_pretrained(cls, base_path, halt_path, attn_implementation="sdpa"):
base = AutoModelForCausalLM.from_pretrained(
base_path,
torch_dtype=torch.bfloat16,
attn_implementation=attn_implementation, # wrapper relies on SDPA causal masking
).cuda().eval()
base.config.use_cache = True
cfg = base.config
heads = torch.nn.ModuleList([
torch.nn.Linear(cfg.hidden_size + 1, 1).to(base.device)
for _ in range(cfg.num_hidden_layers)
])
ckpt = torch.load(halt_path, map_location="cpu", weights_only=False)
heads.load_state_dict(ckpt["halt_heads"])
return cls(base, heads)
model = AmoebaModel.from_pretrained(
"openbmb/MiniCPM5-2B", "path/to/halt_heads.pt"
)
tok = AutoTokenizer.from_pretrained("openbmb/MiniCPM5-2B")
```
### 4.2 Dynamic inference with `threshold`
`threshold` is compared against the **cumulative exit probability**. Higher values are more conservative (deeper exit); lower values exit earlier.
```python
@torch.no_grad()
def generate(model, tok, prompt, threshold=0.7, max_new_tokens=64,
forced_exit=None):
"""
threshold in [0, 1]: higher => more conservative => more layers.
Illustrative depth on the 120M testbed: 0.5 -> ~3.8 layers,
0.8 -> ~7.1 layers, 1.0 -> all 16 layers.
forced_exit: int in [0, L-1] => evaluate a fixed exit layer (no routing).
Useful for quality-vs-depth evaluation.
"""
base, heads = model.base, model.halt_heads
L = len(heads)
ids = tok(prompt, return_tensors="pt").input_ids.cuda()
past = None
for _ in range(max_new_tokens):
h = base.model.embed_tokens(ids)
pos = torch.arange(h.shape[1], device=h.device)[None, :]
cos, sin = base.model.rotary_emb(h, pos)
survival, exit_at = 1.0, L - 1
for i, layer in enumerate(base.model.layers):
h = layer(h, position_embeddings=(cos, sin), past_key_value=past,
use_cache=True)[0]
if forced_exit is not None:
if i == forced_exit:
exit_at = i
break
continue
logits = base.lm_head(base.model.norm(h[:, -1:]))
p_max = logits.float().softmax(-1).max(-1).values
unc = torch.tanh(-p_max.log()).clamp_min(0)
p_l = heads[i](torch.cat([h[:, -1, :], unc[:, None]], -1)).sigmoid()
survival *= (1.0 - p_l.item())
if 1.0 - survival >= threshold:
exit_at = i
break
logits = base.lm_head(base.model.norm(h[:, -1:]))
ids = torch.cat([ids, logits.argmax(-1)[:, None]], -1)
return tok.decode(ids[0], skip_special_tokens=True), exit_at
text, layer = generate(model, tok, "The capital of France is", threshold=0.7)
print(f"exited at layer {layer}: {text}")
```
> The snippet is **illustrative** — it exposes the routing logic (`threshold`, cumulative probability, `forced_exit`). A production implementation should handle the KV cache and per-layer `past_key_value` objects explicitly; incorrect cache handling can erase or even reverse the theoretical speedup.
### 4.3 Forced-exit evaluation
To measure quality at a fixed depth, pass `forced_exit=i`. Sweeping `i = 0 … L-1` yields the **forced-exit CE/PPL curve**, the standard diagnostic for how "exitable" each intermediate layer is. A healthy model shows a roughly flat curve close to the final-layer CE; the current checkpoints do not yet (see below).
---
## 5. Performance & Current Status
### 5.1 Measured speed (Amoeba-DA)
| Model | Baseline greedy | Amoeba-DA | Speedup | Avg accepted tokens/step |
|---|---:|---:|---:|---:|
| Amoeba-2B | 27.1 tok/s | 54.7 tok/s | **2.02×** | 2.61 |
| Amoeba-1B | 44.7 tok/s | 58.0 tok/s | **1.30×** | — |
Draft-head top-1 agreement on chat holdout (2B): 0.469 / 0.348 / 0.293 / 0.240 for offsets 2–5. Crucially, training the heads on **on-policy self-generated chat text** (CE 1.31) instead of off-policy web text (CE 3.71) raised α₂ from 0.138 to 0.469 and speedup from 1.13× to 2.02×.
### 5.2 Quality / exactness statement
Amoeba-DA accepts a candidate only when it matches the target model's own argmax at that position. In **bf16**, batched verification and single-token greedy round near-ties (logits within ~0.01) differently, so output is **not literally bit-identical**: 6/20 prompts matched exactly, with **83.7% positional token match** and an average matching prefix of 75.9 tokens. Quality is therefore *statistically lossless*, not bit-exact — do not claim otherwise. See `medusa_agreement.json`.
### 5.2b Why token-level early exit was rejected
Token-level early exit, layer skipping, attention skipping, MLP skipping and confidence-gated exits were all measured and failed (16 experiments). The 42-layer deep-narrow MiniCPM5 architecture has **no inter-layer redundancy**: keeping 76% of layers still yields CE 11.7 (≈ ln V, i.e. random). Gate cost is ~1.25 layers (an `lm_head` call), while a usable exit depth is ≥40 of 42 — ceiling ≈1.16×. Full data: `docs/动态激活_完整实验矩阵.md`.
### 5.3 Dialogue quality measurement (8 fixed prompts, greedy)
To answer "how much does dialogue quality drop", we compared three modes on the same 8 fixed prompts: **original base, full depth** / **Amoeba full depth (τ=1, no early exit)** / **Amoeba quality gate (conf≥0.95)**. Lower 3-gram repetition and garble rates are better; a smaller exit layer means earlier exit.
| Model | Mode | Avg length | 3-gram repeat | Garble | Avg exit layer |
|---|---|---:|---:|---:|---:|
| **Amoeba-2B** | Original full | 234 | 0.000 | 0.007 | 42 |
| | Amoeba full | 238 | 0.006 | 0.009 | 42 |
| | Amoeba gated | 128 | 0.179 | 0.002 | 36.2 |
| **Amoeba-1B** | Original full | 264 | 0.308 | 0.000 | 24 |
| | Amoeba full | 302 | 0.159 | 0.000 | 24 |
| | Amoeba gated | 258 | 0.589 | 0.000 | 18.6 |
| **Amoeba-0.6B** | Original full | 205 | 0.000 | 0.017 | 28 |
| | Amoeba full | 208 | 0.000 | 0.013 | 28 |
| | Amoeba gated | 187 | 0.013 | 0.019 | 24.2 |
| **Amoeba-0.3B** | Original full | 92 | 0.000 | 0.001 | 28 |
| | Amoeba full | 93 | 0.000 | 0.003 | 28 |
| | Amoeba gated | 161 | 0.140 | 0.000 | 10.5 |
**Takeaways:** (1) **Amoeba full depth ≈ original** — length, repetition, and garble are nearly identical, confirming the modification itself is safe. (2) **The quality gate has a visible cost** — e.g. 2B 3-gram repetition rises 0.000→0.179 and answers shorten (234→128); 0.3B exits at only 10.5/28 layers with repetition 0.140. (3) **Smaller models are more aggressive and lose more** — consistent with weaker intermediate representations. (4) **Acceleration remains limited** — 2B exits at 36.2/42 layers, saving little; 0.3B is more aggressive but pays a repetition penalty. These are local-protocol numbers, not official evaluation-stack results.
---
---
## 5.5 Usage notes & honest limitations (read before deploying)
1. **Greedy decoding loops on long answers.** On 2B, greedy generation repeated a
sentence 20+ times in a long role-play answer. Use the recommended sampling:
`temperature=0.8, top_p=0.95, repetition_penalty=1.05`. All reported capability
deltas were measured with the recovered official chat template
(`<think>` enabled); our short-subset greedy scores are **not comparable** to the
official model-card numbers (MATH-500 94.6 etc., sampled at temperature 1.0).
2. **Tool calls require the tool-definition system message.** `agent_infer.py` supplies
it. Asking for weather with a bare chat template makes the model say it has no
real-time data — this is a prompt issue, not a capability failure.
3. **Training data correction.** Early experiments used CCI3-Data, but it is a noisy
Chinese web/news corpus (CE 3.7 vs 1.31 on self-generated chat) and **was not used
for the released checkpoints**. The released tool-calling SFT used in-house
synthetic tool-use dialogues generated from the base models. The math-CoT SFT
experiment using OpenMathReasoning degraded MMLU and was **discarded**; no released
model includes it.
4. **0.6B tool-call checkpoint:** the first 2-epoch run overfit (loss 0.0008) and
produced empty replies. The released `ckpt_06b_agent_v2` uses 1 epoch / lr 5e-5.
5. **Draft heads are only shipped for 2B and 1B.** On 0.6B/0.3B they measured 0.60× /
0.36× (slower) and are not distributed as a speed feature.
6. **vLLM is not usable in this environment** (v0.11 ABI-incompatible with torch
2.15+cu132); all timings use HuggingFace `generate` and are CPU/Python-bound.
---
## 6. Training Method (Overview)
The training pipeline proceeds in stages, each with a gate before continuing:
1. **Baseline reproduction.** Record the untouched base model's CE/accuracy and its forced-exit curve; confirm the final layer is the quality ceiling.
2. **Method viability.** Use overfit tests to verify gradients reach both the halt heads (`halt_grad > 0`) and the decoder (`base_grad > 0`), and that per-layer CE can be reduced at a target layer without hurting the final layer.
3. **Per-layer reinforcement.** Unfreeze the decoder; apply per-layer independent LM loss (uniform or inverse-CE weights) plus a final-layer anchor. Optionally add layer dropout (`p_max ≈ 0.1–0.2`) and self-distillation (KL at `T = 2`, cosine on normalized representations) with a low learning rate (base `1e-5`–`5e-5`, heads `1e-4`–`2e-4`).
4. **Halt-head recalibration.** With the strengthened base fixed, retrain the halt heads with the full halt objective and calibrate the exit threshold (rather than relying on a hard-coded value).
5. **Capability post-training (planned).** Add tool-use and reasoning ability with agent data (OpenThoughts-Agent-SFT-100K, Mixture-of-Thoughts, OpenMathReasoning), re-tokenized into each base's vocabulary.
**Research lineage.** The layer-dropout + early-exit-loss recipe follows the ideas of **LayerSkip** (Elhoushi et al., 2024) and the confidence-adaptive per-token halting of **CALM** (Schuster et al., 2022). We implement these ideas independently; see the licensing note below.
---
## 7. License & Acknowledgments
**Amoeba weights and code are released under Apache-2.0.** Amoeba is a derivative work of the base models listed below, with added tool-calling SFT and **Amoeba-DA** (verified dynamic activation via parallel draft heads). This is an independent research project, **not affiliated with or endorsed by OpenBMB, Alibaba/Qwen, or Taobao/MNN**.
### Base models
| Base | Organization | License |
|---|---|---|
| MiniCPM5-2B, MiniCPM5-1B | OpenBMB | Apache-2.0 |
| Qwen3-0.6B | Alibaba / Qwen | Apache-2.0 |
| MNN-Pocket-0.3B | Taobao / MNN | Apache-2.0 |
### Training data
- **BAAI/CCI3-Data** — Apache-2.0
- **open-thoughts/OpenThoughts-Agent-SFT-100K** — Apache-2.0
- **nvidia/OpenMathReasoning** — CC-BY-4.0 (attribution required; we gratefully acknowledge this dataset)
- Reasoning traces in Mixture-of-Thoughts are distilled from **DeepSeek-R1** (MIT, which permits蒸馏 / derivative use); the upstream data-card license field is absent, so we treat this source conservatively.
### Research references
- **LayerSkip** — Elhoushi et al., 2024, *"LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding"* (Meta). Ideas only (layer dropout, early-exit loss, self-distillation). The original LayerSkip **code is CC-BY-NC** and **was not copied**; our implementation is independent and uses no LayerSkip source files.
- **CALM** — Schuster et al., 2022, *"Confident Adaptive Language Modeling"* (Google). Confidence-adaptive per-token halting; reference implementation is Apache-2.0.
- We preserve all upstream copyright notices and include a `NOTICE` file listing base-model attributions, as required by Apache-2.0.
---
## 8. Limitations
1. **Under active tuning.** Dynamic-activation quality is not yet reliable. Exit collapse in early checkpoints means current weights should be treated as research artifacts, not deployable models; no validated quality–speed curve is published.
2. **Text-first.** The current work targets pure text generation. Multimodal dynamic activation is planned as a future extension and is not part of these checkpoints.
3. **Threshold calibration.** The exit `threshold` is task- and model-dependent. A single hard-coded value (e.g. 0.7) is not universally appropriate; the soft expected depth used in training does not necessarily match the hard exit taken at inference. Users should calibrate the threshold on their target task.
4. **Overhead can erode gains.** Per-layer `lm_head`/halt-head calls, Python-level layer iteration, and KV-cache handling can reduce or negate theoretical speedups if not implemented carefully.
5. **Small-model sensitivity.** Smaller bases (0.3B, 120M) have limited capacity and are more prone to exit collapse; their halt-loss hyper-parameters need more conservative settings. The 120M testbed's tiny legacy vocabulary (4104) makes it unsuitable for quality evaluation.
---
## 9. Citation
If you use Amoeba in research, please cite this project and the base models / methods it builds upon:
```bibtex
@misc{amoeba2026,
title = {Amoeba: Verified Dynamic Activation for Language Models},
year = {2026},
note = {Independent research project; Apache-2.0}
}
@inproceedings{elhoushi2024layerskip,
title = {LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding},
author = {Elhoushi, Mostafa and Chen, Weijie and others},
year = {2024}
}
@inproceedings{schuster2022calm,
title = {Confident Adaptive Language Modeling},
author = {Schuster, Tal and Fisch, Amit and others},
year = {2022}
}
```
Please also cite the relevant base-model papers (MiniCPM5, Qwen3, MNN-Pocket) and datasets used in your variant.
---
## 10. Disclaimer
Amoeba is an independent research project. It is **not** an official model from OpenBMB, Alibaba/Qwen, or Taobao/MNN, and carries no endorsement from them. The models are provided for research and educational purposes; the quality limitations described above apply.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# Amoeba
**面向小语言模型的、以能力保持为目标的动态激活研究。**
Amoeba 是一个包含四个 Apache-2.0 模型的模型族(0.3B / 0.6B / 1B / 2B),基于
MiniCPM5、Qwen3 和 MNN-Pocket 基座。它提供:
- **Amoeba-DA** —— 验证式投机解码:K 个并行瓶颈草稿头从单一缓存隐藏状态预测后续 token,
冻结的基座模型在一个批量前向中验证所有候选。仅在 2B / 1B 上发布。
- **工具调用** —— 四个尺寸都经过后训练可发出工具调用,附带 ReAct 推理脚本。
> **研究定位。** 这是一项实证研究,不是通用加速器。核心发现是加速**依赖架构与执行框架**:
> Amoeba-DA 在全注意力的 MiniCPM5-2B 上取得干净的 2.015×,但在滑窗混合架构(Gemma、SparkX)
> 与 MoE/KDA 架构(Ling)上无收益。所有加速比都相对于 Python 瓶颈的 HuggingFace `generate`
> 测量;在 vLLM 下同一模型本身就快得多。论文完整报告了所有撤回、失败与放弃的结果。
> token 级 early-exit 经 16 组实验系统性否定,**没有**发布模型使用它。
## 结果(单卡 RTX 4080S 32GB;HF `generate`,贪心)
| 模型 | 基座 | Amoeba-DA 加速 | 能力 | 工具调用 |
|---|---|---|---|---|
| Amoeba-2B | MiniCPM5-2B | **2.015×**(26.6 → 53.6 tok/s) | 79 题:91.14% → 93.67%,**零倒退** | 4/4 |
| Amoeba-1B | MiniCPM5-1B | **1.30×** | — | 4/4 |
| Amoeba-0.6B | Qwen3-0.6B | 未发布 | — | 3/3 |
| Amoeba-0.3B | MNN-Pocket-0.3B | 未发布 | — | 3/3 |
我们**不**宣称逐位无损:2B 的 token 一致率为 0.734。主张是**下游能力保持**,在 79 道客观题上
以零"对→错"翻转验证(ROUGE-L 0.94)。另一条正交机制——SenseNova-Loop-9B 的动态 loop 深度路由
以 +0.04 nats CE 换取 45% 加速,是独立的质量-速度权衡,单独报告。Qwen 全系加速数字**全部撤回**
(验证引擎与其 KV cache 不兼容)。
## 仓库结构
```
Amoeba-2B/ Amoeba-1B/ Amoeba-0.6B/ Amoeba-0.3B/
full_model/ # 独立的 HF checkpoint
README.md # 模型卡
LICENSE
amoeba_da_infer.py # 草稿头推理(仅 2B/1B)
AMOEBA_PAPER_DRAFT.pdf / .tex / .docx # 12 页研究报告
MANIFEST.json / DOWNLOAD.md
_LICENSES/ # 上游许可证
```
## 快速开始
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
p = "Amoeba-2B/full_model"
tok = AutoTokenizer.from_pretrained(p)
model = AutoModelForCausalLM.from_pretrained(p, dtype="auto", device_map="auto")
out = model.generate(**tok("你好", return_tensors="pt").to(model.device),
max_new_tokens=128, do_sample=True,
temperature=0.8, top_p=0.95, repetition_penalty=1.05)
print(tok.decode(out[0], skip_special_tokens=True))
```
贪心解码在长回答上可能循环重复——使用上面的采样参数。工具调用需要工具定义的 system message。
## 论文
`AMOEBA_PAPER_DRAFT.pdf` —— 《Amoeba: From Early Exit to Verified Speculative Decoding
and Dynamic Loop Routing》。章节覆盖被否定的 early-exit 路线、Amoeba-DA 的能力评估与架构边界、
替代机制(更多草稿头、forward-KL、KV 预测)、Loop 路由、vLLM 服务框架验证、完整的负面结果记录,
以及与 Medusa / EAGLE / JetSpec / LCKV / CLA / AttentionPredictor / KV-Direct 的审慎定位。
我们不声称草稿头+验证机制本身的新颖性。
## 许可证
所有 Amoeba 权重和本仓库均为 Apache-2.0。基座模型同样为 Apache-2.0。
没有复制 LayerSkip 代码(CC-BY-NC),其思想从论文独立实现。CCI3 等脏语料只用于已废弃实验,
**不在任何发布 checkpoint 中**。独立研究项目,与基座模型机构无关。
## 引用
```bibtex
@misc{amoeba2026,
title = {Amoeba: From Early Exit to Verified Speculative Decoding and Dynamic Loop Routing},
author = {Weikai Yue and Hy 4 flash},
year = {2026},
note = {Independent research report}
}
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# Amoeba:验证式动态激活语言模型家族
> **Amoeba** 是一族具备 **Amoeba-DA(验证式动态激活)** 与工具调用(agent)能力的语言模型。Amoeba-DA 用 K 个并行草稿头从同一份 hidden 一次性猜出 `t+2..t+K+1`,再由**未修改的基座模型**一次前向并行验证;只有当候选与基座自身贪心 argmax 一致时才接受,因此输出与全层贪心在统计意义上等价。
>
> **状态(已更新)**:早期的 token 级早退(halt head)路线已被系统否定——16 组实测实验在这套 42 层深窄架构上全部失败。当前发布的技术是 **Amoeba-DA**:2B 实测 **2.02×**(27.1 → 54.7 tok/s,RTX 4080S),1B 实测 **1.30×**。工具调用已包含(2B/1B 用 LoRA SFT,0.6B/0.3B 用原生工具模板)。详见第 5 节与 `docs/动态激活_完整实验矩阵.md`。
---
## 目录
- [1. 项目简介](#1-项目简介)
- [2. 核心创新](#2-核心创新)
- [3. 模型家族](#3-模型家族)
- [4. 使用方法](#4-使用方法)
- [5. 性能与加速](#5-性能与加速)
- [6. 训练方法](#6-训练方法)
- [7. License 与致谢](#7-license-与致谢)
- [8. 已知限制](#8-已知限制)
- [9. 引用](#9-引用)
---
## 1. 项目简介
传统 Transformer 对每个 token 都执行**全部层**的计算,无论这个 token 是简单的标点、常见的停用词,还是需要深度推理的关键字。然而直觉上,不同 token 的"难度"并不相同——大量 token 在浅层就已经可以被可靠预测。
**Amoeba** 的核心目标是:**让不同 token 走不同深度**。我们在预训练基座(MiniCPM5、Qwen3、MNN-Pocket 等)的每一层后挂一个极轻量的 **halt head**(`Linear(hidden+1, 1)`,参数量仅数万级)。推理时,每个 token 逐层累积"可以退出"的概率,一旦累积概率达到阈值就提前退出,跳过后续所有层。
设计动机与取舍:
- **按需计算**:简单 token 浅层退出,难 token 走得更深,期望在不显著掉质量的前提下节省算力。
- **端侧 / 本地优先**:在消费级显卡或端侧设备上,用可接受的质量损失换取可观的延迟下降,是划算的权衡。
- **跨架构验证**:模型族覆盖 3 个模型族(MiniCPM5 / Qwen3 / MNN)× 4 个尺寸,系统研究"动态激活收益 vs 模型规模"的 scaling 关系。
- **诚实的研究定位**:early-exit 方向"研究多、落地少",核心硬伤是掉质量。Amoeba 的差异化在于用**熵正则 + 语义一致性**的 halt 损失改善"置信度判断不准"这一痛点,并以开放、可复现的方式记录成败。
> 本项目是独立研究项目,与 OpenBMB、Alibaba、Taobao/MNN 等上游机构**无官方关联或背书**。
---
## 2. 核心创新
### 2.1 每层 halt head 与 token 级累积退出
在基座的每一层 `l` 之后挂一个 halt head:
```
score_l = Linear(hidden_size + 1, 1)( [h_l, unc_l] )
p_l = sigmoid(score_l)
```
- `h_l`:该层输出的隐藏状态;
- `unc_l`:token 级不确定性标量,`unc = tanh(-log(p_max))`,其中 `p_max` 是该位置词表分布的最大概率;
- `+1` 即把不确定性作为一个额外特征拼接到 hidden 上。
推理时按层累积退出概率:
```
remaining_0 = 1
q_l = remaining_l · p_l # 该 token 在第 l 层退出的概率
remaining_{l+1} = remaining_l · (1 - p_l)
```
当累积退出概率 `F(l) = 1 - remaining_{l+1}` 首次达到阈值 `τ` 时,该 token 退出。**阈值越高越保守(走更多层)**,详见[使用方法](#4-使用方法)。
### 2.2 每层强化训练(per-layer exit strengthening)
早期 checkpoint 暴露出一个关键问题:**基座只在最后一层被 CE 监督过,中间层的隐藏状态并不"可直接读出正确词"**,强制在浅层退出会导致 CE 爆炸(实测 L6 CE≈13.5、PPL≈7×10⁵,而末层 L42 CE≈2.39)。为此我们采用每层强化方案:
- **逐层独立 LM loss(核心)**:对多个启用出口分别计算 `CE(lm_head(norm(h_l)), y)`,并**解冻基座**让梯度真正回传到 decoder 层,逼迫中间层学会"可退出"。早期 `--freeze-base` 的训练中,这条 loss 只是"没有梯度的只读探针"——这是必须修正的范畴错误。
- **Layer dropout(放大器)**:训练时以 `p_l = D(l)·p_max` 的概率随机跳过前面的层,迫使后层学会"补位"、浅层自己承载预测信息(借鉴 LayerSkip 思想,自行实现)。
- **自蒸馏 / 语义一致性(精修)**:以最后一层 L42 的 logits / hidden 作为教师,用 KL 散度 + cosine 相似度约束中间出口,使其语义与末层对齐,让 halt head 的"何时可退"判断更可靠。
- **halt 损失**:均匀先验(避免退出分布全挤在某一层)+ 熵正则(防止决策过早塌缩成 one-hot)+ 语义一致性 + 时间惩罚。
> 核心洞察:**halt head 只是"裁判",基座中间层的表示质量才是"运动员"。运动员没练好之前,裁判无从发挥。** 因此训练重点是先让中间层真正可退出,再校准退出决策。
### 2.3 关键工程约束
- **不改 `modeling_*.py` 内部前向循环**,而是用 wrapper 持有基座并逐层 forward,避免破坏 KV cache / `generate`。
- 所有维度(`hidden_size`、层数、特殊 token id)从 config 动态读取,跨基座复用同一套 wrapper 逻辑。
---
## 3. 模型家族
| 版本 | 基座 | 架构 | 层 | hidden | 词表 | 状态 |
|---|---|---|---:|---:|---:|---|
| **Amoeba-2B** | MiniCPM5-2B | LlamaForCausalLM | 42 | 2048 | 130560 | 主线;基座权重就绪,动态激活训练与调优进行中 |
| **Amoeba-1B** | MiniCPM5-1B | LlamaForCausalLM | 24 | 1536 | 130560 | 基座权重就绪;复制流程最容易 |
| **Amoeba-0.6B** | Qwen3-0.6B | Qwen3ForCausalLM | 28 | 1024 | 151936 | 适配完成,已启动训练 |
| **Amoeba-0.3B** | MNN-Pocket-0.3B | Qwen3ForCausalLM | 28 | 896 | 65536 | 适配完成,已启动训练(小词表 / 小容量,坑最多) |
| **Amoeba-120M** | 自研小模型(testbed) | — | 16 | 768 | 4104 | 机制验证平台;基座质量受历史 4104 词表路线限制,仅用于验证动态激活机制 |
补充说明:
- **2B / 1B** 为 MiniCPM5 系列,标准 `LlamaForCausalLM`,128K 上下文,与 halt head 改造最契合。
- **0.6B / 0.3B** 为 `Qwen3ForCausalLM`(含 q_norm/k_norm),transformers 原生支持;0.3B 来自 2026-11 新发布的 MNN-Pocket,词表仅 65536。
- **120M testbed** 已验证动态激活机制本身可用(阈值 1.0→退出 16 层/全层;0.8→7.1 层;0.5→3.77 层,能按阈值自适应控制深度),但因基座质量太差(生成重复垃圾),**不用于评估早退质量损失**。
- 跨架构、跨尺寸的横向对照旨在产出 scaling 曲线:哪个尺寸早退收益最大、质量-速度权衡如何随规模变化。
---
## 4. 使用方法
### 4.1 加载基座并包装
Amoeba 以 wrapper 的形式工作:加载标准基座后,用 `AmoebaModel` 持有它并挂载每层 halt head。下面代码为**简化示意**,说明核心接口;生产实现还包含 KV cache、位置嵌入与逐层调度的完整处理。
```python
import torch
import torch.nn as nn
from transformers import AutoModelForCausalLM, AutoTokenizer
BASE = "openbmb/MiniCPM5-2B" # 按版本替换为对应基座
tok = AutoTokenizer.from_pretrained(BASE)
base = AutoModelForCausalLM.from_pretrained(
BASE,
torch_dtype=torch.bfloat16,
attn_implementation="sdpa", # 依赖 SDPA 自动因果掩码
)
L = base.config.num_hidden_layers
H = base.config.hidden_size
class AmoebaModel(nn.Module):
def __init__(self, base):
super().__init__()
self.base = base
# 每层一个 halt head:输入 = hidden + 不确定性,故为 H+1 -> 1
self.halt_heads = nn.ModuleList(
[nn.Linear(H + 1, 1) for _ in range(L)]
)
# 计算某层的退出概率 p_l(示意:h_l 为该层 hidden,p_max 为分布最大概率)
def exit_prob(self, l, h_l, p_max):
unc = torch.tanh(-torch.log(p_max.clamp_min(1e-8))) # token 级不确定性
return torch.sigmoid(self.halt_heads[l](torch.cat([h_l, unc], dim=-1)))
model = AmoebaModel(base).cuda().eval()
# 训练完成后加载 halt head 权重:
# model.halt_heads.load_state_dict(torch.load("halt_heads.pt", map_location="cpu")["halt_heads"])
```
### 4.2 动态推理(threshold 参数)
- `threshold`(记作 `τ`)是**累积退出概率阈值**:当某 token 的累积退出概率 `F(l)` 首次 ≥ τ 时退出。
- **τ 越高越保守、走越多层**:`τ=1.0` 表示永不早退(跑完整层,作为全层延迟基线);`τ` 越小越激进、越早退出。
- 阈值**不是"置信度"**,也不是质量门控,而是一个需要按任务在验证集上校准的操作点(见「已知限制」)。
```python
@torch.no_grad()
def generate_dynamic(model, input_ids, threshold=0.8, max_new_tokens=64, eos_id=1):
"""示意:逐 token 累积退出概率,达标即停。生产版需配合 KV cache。"""
out = input_ids
for _ in range(max_new_tokens):
remaining = torch.ones(out.shape[0], 1, device=out.device)
used_layers = []
hidden = None
for l, layer in enumerate(model.base.model.layers):
# 实际实现需计算 position_embeddings / attention_mask / KV cache
hidden = layer(hidden if hidden is not None else model.base.model.embed_tokens(out))
logits = model.base.lm_head(model.base.model.norm(hidden[:, -1:, :]))
p_max = logits.float().softmax(-1).max(-1).values # [B, 1]
p = model.exit_prob(l, hidden[:, -1, :], p_max) # [B, 1]
remaining = remaining * (1 - p)
if ((1 - remaining) >= threshold).all(): # 全 batch 达标
used_layers.append(l + 1)
break
nxt = logits.argmax(-1)
out = torch.cat([out, nxt], dim=-1)
if l == model.base.config.num_hidden_layers - 1:
pass # 末层必退
if (nxt == eos_id).all():
break
return out
```
经验参考(120M testbed 实测):`τ=1.0 → 平均 16 层(全层)`、`τ=0.8 → 约 7.1 层`、`τ=0.5 → 约 3.77 层`。**这些层数不能脱离质量单独解读**——必须同时看退出点上的 CE/PPL。
### 4.3 强制退出评测
为衡量"每一层单独作为出口"的质量,可强制所有样本在第 `l` 层退出,计算 CE/PPL,画出"退出层 vs 质量"曲线:
```python
@torch.no_grad()
def forced_exit_ce(model, input_ids, targets, exit_layer):
h = model.base.model.embed_tokens(input_ids)
for l, layer in enumerate(model.base.model.layers):
h = layer(h) # 示意:省略 position/mask/cache
if l == exit_layer:
logits = model.base.lm_head(model.base.model.norm(h))
return nn.functional.cross_entropy(
logits[:, :-1].float().reshape(-1, logits.size(-1)),
targets.reshape(-1),
)
raise ValueError("exit_layer 越界")
# 扫描全部层,得到强制退出 CE 曲线(L6≈13.5 ... L42≈2.39 为未强化时的基线形态)
for l in [5, 11, 17, 23, 29, 35, 41]:
print(f"L{l+1}: CE={forced_exit_ce(model, inp, tgt, l):.3f}")
```
> 注:不同基座的 `eos_id` 不同——MiniCPM5 为 `1`,Qwen3-0.6B 为 `151645`,MNN-Pocket-0.3B 为 `65512`;Qwen3 系列还需注意 tied embeddings 与 `q_norm/k_norm`。完整实现请参考项目内的 wrapper 与评测脚本。
---
## 5. 性能与加速(Amoeba-DA 实测)
### 5.1 实测加速
| 模型 | 全层贪心基线 | Amoeba-DA | 加速 | 每步平均接受 token |
|---|---:|---:|---:|---:|
| Amoeba-2B | 27.1 tok/s | 54.7 tok/s | **2.02×** | 2.61 |
| Amoeba-1B | 44.7 tok/s | 58.0 tok/s | **1.30×** | — |
2B 草稿头在 chat 留出集上的 top-1 一致率为 0.469 / 0.348 / 0.293 / 0.240(offset 2–5)。关键发现:用 **on-policy 自生成对话文本**(CE 1.31)而非离线网页语料(CE 3.71)训头,α₂ 从 0.138 提升到 0.469,加速从 1.13× 提升到 2.02×。
### 5.2 质量与一致性口径
Amoeba-DA 只在候选与基座 argmax 一致时接受。但在 **bf16** 下,批量验证与单 token 贪心对近邻(logits 差约 0.01)的舍入方向不同,因此输出**并非逐 bit 相同**:20 条中 6 条完全一致,位置 token 匹配率 **83.7%**,平均匹配前缀 75.9 token。准确说法是**统计无损**,不是逐位无损。
### 5.3 为什么否定 token 级早退
token 级早退、跳中间层、跳 attention、跳 MLP、置信度门控共 16 组实验全部失败。42 层深窄结构层间没有冗余:保留 76% 的层 CE 仍高达 11.7(≈ ln V,等同随机)。门控成本约 1.25 层(一次 `lm_head`),而可用退出深度 ≥40/42,理论天花板仅 ≈1.16×。完整数据见 `docs/动态激活_完整实验矩阵.md`。
---
## 5.5 使用注意与已知限制(部署前必读)
1. **贪心解码在长回答上会陷入重复循环**。2B 在长角色扮演中把同一句话重复 20+ 次。
请使用推荐采样参数 `temperature=0.8, top_p=0.95, repetition_penalty=1.05`。
所有能力对比都基于从官方 GGUF 模型卡恢复的 chat template(开启 `<think>`);
我们短子集贪心分数**不可与官方模型卡数字直接比较**(官方 MATH-500 94.6 等,
使用 temperature=1.0 采样与更大生成预算)。
2. **工具调用需要带工具定义的 system message**,`agent_infer.py` 已处理。
裸 chat template 直接问天气,模型会回答"没有实时数据"——这是 prompt 问题,不是能力问题。
3. **训练数据更正**:早期实验用过 CCI3-Data,但它是噪声很大的中文网页/新闻语料
(CE 3.7,而自生成对话为 1.31),**未用于最终发布的 checkpoint**。
发布模型的工具调用 SFT 使用的是从基座自生成的合成工具对话数据。
使用 OpenMathReasoning 的数学 CoT 实验会损伤 MMLU,**已丢弃**,不在发布模型中。
4. **0.6B 工具模型**:第一版 2 epoch 过拟合(loss 0.0008)导致空回复;
发布的是 `ckpt_06b_agent_v2`(1 epoch / lr 5e-5)。
5. **草稿头只随 2B/1B 发布**:0.6B/0.3B 实测 0.60× / 0.36×(变慢),不作为加速特性交付。
6. **本环境 vLLM 不可用**(0.11 与 torch 2.15+cu132 ABI 不兼容),
所有速度数据来自 HuggingFace `generate`,受 CPU/Python 限制。
---
## 6. 训练方法
Amoeba 的训练分阶段推进,核心是"先练运动员(基座中间层),再校准裁判���halt head)":
1. **复现 baseline**:先按 LayerSkip 思路自行实现 layer dropout + 逐层 exit loss,回答"改造基座能否跑通、掉多少质量"。LayerSkip 在 1.5B 上报告:exit layer 6 速度约 2×,但质量从 85.39% 掉到 82.9%(约 2.5%),末层还有约 3% 回退——这是我们要改善的基线。
2. **每层强化(核心)**:解冻基座,用 uniform / inverse-CE 权重的逐层独立 LM loss 把梯度打进 decoder 层,配合末层 CE anchor 防止灾难性遗忘;叠加 layer dropout 强化(继续预训练 `p_max≈0.1`,任务微调可升到 0.2)。
3. **语义对齐(精修)**:以末层为教师做 logits KL + hidden cosine 的自蒸馏,提升中间出口与末层的语义一致性。
4. **halt head 重校准**:基座分布改变后,冻结基座、只训 halt heads,恢复完整 halt 损失(均匀先验 / 熵正则 / 语义一致性 / 时间惩罚),并按 CALM 的 LTT/FST 思路在验证集上校准退出阈值,替换硬编码值。
5. **评测与消融**:对比强制退出 CE 曲线、退出分布、质量-速度曲线;对 B(逐层 loss)/ C(layer dropout)/ A(蒸馏)各组合做小型消融。
显存与成本方面:以 RTX 4080S 32GB + bf16 + 8-bit AdamW 计,2B 全参微调约 15GB(加冻结教师副本约 19GB),完全可行。小尺寸版本依次把 2B 上验证的方法复制到 1B → 0.6B → 0.3B。
> 实现上我们**阅读论文、理解思想后自行编码**,不复制 LayerSkip 的仓库代码(见 License 一节);同时参考 Apache-2.0 的 CALM 实现以少踩坑。
---
## 7. License 与致谢
### 7.1 权重与代码 License
- 本项目的 **Amoeba 权重以 Apache-2.0 发布**;仓库根目录包含 `LICENSE`(Apache-2.0 全文)与 `NOTICE`(列明上游版权声明)。
- 各基座 License:
| 基座 | License | 说明 |
|---|---|---|
| MiniCPM5-2B / MiniCPM5-1B | **Apache-2.0** | OpenBMB;可商用、可发布衍生模型 |
| Qwen3-0.6B | **Apache-2.0** | Alibaba/Qwen;可商用、可发布衍生模型 |
| MNN-Pocket-0.3B | **Apache-2.0** | Taobao/MNN;可商用、可发布衍生模型 |
- **LayerSkip(facebookresearch)**:代码为 **CC-BY-NC**(仅非商用研究)。我们**仅参考其论文思想**(layer dropout + exit loss),**未复制、未改写其任何代码**;需要代码参考时优先使用 Apache-2.0 的 **CALM**。论文可正常引用(citation 不受代码 license 限制)。
- **训练数据**:CCI3-Data、OpenThoughts-Agent-SFT-100K 为 Apache-2.0;`nvidia/OpenMathReasoning` 为 **CC-BY-4.0**(model card 中已署名);Mixture-of-Thoughts 的 reasoning trace 蒸馏自 DeepSeek-R1(MIT,允许商用与蒸馏),数据卡未标注 license,发布时按保守口径处理。
### 7.2 各 checkpoint 的 base 归属
| Checkpoint | 基座(base model) | 修改说明 |
|---|---|---|
| Amoeba-2B | `openbmb/MiniCPM5-2B` | 在基座上新增 token 级 halt heads(动态激活),并对基座中间层做每层强化微调 |
| Amoeba-1B | `openbmb/MiniCPM5-1B` | 同上 |
| Amoeba-0.6B | `Qwen/Qwen3-0.6B` | 同上(Qwen3ForCausalLM 架构适配) |
| Amoeba-0.3B | `MNN/MNN-Pocket-0.3B` | 同上(Qwen3ForCausalLM 架构适配,小词表 65536) |
每个 checkpoint 的 model card 均声明:`base_model`、修改说明、"This is an independent research project, not affiliated with OpenBMB / Alibaba / Taobao" 等非官方背书声明。
### 7.3 致谢
感谢 OpenBMB(MiniCPM5)、Qwen 团队(Qwen3)、MNN 团队(MNN-Pocket)开源高质量基座;感谢 Google DeepMind 的 CALM 与 Meta 的 LayerSkip 在自适应计算 / early-exit 方向上的开创性工作;感谢 CCI3、OpenThoughts、NVIDIA OpenMathReasoning、DeepSeek-R1 等开放数据与模型。
---
## 8. 已知限制
1. **动态激活质量仍在调优**:当前 checkpoint 存在退出坍缩,早退生成质量显著低于全层基线;在方法稳定前不建议生产使用,相关加速数字不可信。
2. **纯文本优先,多模态后续**:当前版本聚焦纯文本;多模态动态激活是后续方向,尚未实现。
3. **退出阈值需按任务校准**:`threshold` 是未校准的操作点,并非置信度或质量门控。同一阈值在不同任务 / 数据分布上的质量-速度表现差异很大,需在验证集上联合 (质量约束, 延迟) 扫描选择。
4. **指标口径需谨慎解读**:训练侧的"软期望退出层"与评测侧的"硬退出分位数"定义不同;报告退出层时必须同时报告该层的 CE/PPL,避免"早退=高质量"的误读。
5. **小基座额外约束**:0.3B 词表仅 65536,外部语料必须重新 tokenize 并断言 id 越界;Qwen3 系列需处理 tied embeddings 与 q_norm/k_norm;部分基座 config 的 `use_cache=false`,评测前需显式打开。
6. **长上下文 / KV cache**:早退与 KV cache 的正确配合是持续工程项;配合不佳时早退可能无法转化为实际延迟收益。
---
## 9. 引用
如本项目对您的研究有帮助,请引用相关基线工作:
- Schuster et al., **Confident Adaptive Language Modeling (CALM)**, 2022. — 置信度自适应 per-token 退出。
- Elhoushi et al., **LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding**, 2024. — layer dropout + early-exit loss + 自投机解码。
- 各基座论文与技术报告:MiniCPM5(OpenBMB)、Qwen3(Alibaba)、MNN-Pocket(Taobao/MNN)。
---
> **Amoeba** — *Go as deep as needed, no deeper.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Amoeba 模型族 License 说明(HuggingFace 发布用)
> 本文件随 Amoeba 模型权重一同发布,说明每个版本的基座来源、> 所继承的开源许可证,以及发布时需要遵守的署名与声明义务。> 配套全文见同目录下的 `APACHE-2.0.txt`(`MIT.txt` 为标准模板备用,当前各版本均不适用)。
## 1. 各版本继承的 base license
| Amoeba 版本 | 基座(base model) | 基座团队 | 继承的 License ||---|---|---|---|| Amoeba-2B | MiniCPM5-2B(OpenBMB) | OpenBMB | Apache-2.0 || Amoeba-1B | MiniCPM5-1B(OpenBMB) | OpenBMB | Apache-2.0 || Amoeba-0.6B | Qwen3-0.6B(Qwen team) | Qwen / Alibaba | Apache-2.0 || Amoeba-0.3B | MNN-Pocket-0.3B(MNN team) | MNN Team | Apache-2.0 || Amoeba-120M | 自研(Amoeba 团队从头训练) | Amoeba | Apache-2.0 |
### 1.1 Amoeba 自身的改造部分
- **halt head(逐 token 动态激活)+ 训练方法(熵正则化等)**:由 Amoeba 团队原创实现,采用 **Apache-2.0** 发布。- 因此所有基座版本(含 Amoeba-0.3B,其基座 MNN-Pocket-0.3B 同样为 Apache-2.0)的衍生权重整体均沿用 **Apache-2.0**。
## 2. 参考但未复用代码的部分
- **LayerSkip(facebookresearch)**:其代码为 **CC-BY-NC(仅非商用)**。 本项目**仅参考论文思想**(layer dropout + exit loss 的思路), **未复制、未改写其任何代码**。CC-BY-NC 代码未进入本仓库, 论文按正常学术引用(citation)署名,不受代码许可证约束。- **CALM(google-deepmind)**:Apache-2.0,可作为实现参考;如复用其 代码片段,保留原 Apache-2.0 版权头。
## 3. 数据集
- **OpenThoughts agent 数据**(如使用,open-thoughts/OpenThoughts-Agent-SFT-100K): **Apache-2.0**,按 Apache-2.0 要求保留署名与 NOTICE 即可。- 其它训练数据(如 CCI3-Data、OpenMathReasoning 等)请对照各数据卡 单独署名;CC-BY-4.0 数据(如 nvidia/OpenMathReasoning)须在 model card 致谢中写明署名。
## 4. 版权归属
- **各基座模型的版权归原作者/原团队所有** (OpenBMB、Qwen/Alibaba、MNN Team 等)。- 本仓库**只发布在基座之上的增量改造**(halt head、训练方法、衍生权重), 不声称拥有基座本身的版权,也不替换或删除基座自带的版权声明。
## 5. 发布到 HuggingFace 时的 attribution 要求
1. 在 model card frontmatter 中声明 `license`(所有版本均为 apache-2.0), 并用 `base_model:` 写明对应基座 (MiniCPM5-2B / MiniCPM5-1B / Qwen3-0.6B / MNN-Pocket-0.3B)。2. 正文明确声明本模型是基座模型的衍生工作,例如: *"This model is a derivative work of [base model] with added token-level dynamic activation (halt heads). This is an independent research project, not affiliated with OpenBMB / Alibaba / Taobao / MNN Team."*3. 保留基座权重/代码中的原始版权头与 NOTICE 声明,不删改。4. 须随附 `APACHE-2.0.txt` 全文;`MIT.txt` 仅作标准模板备用,当前发布版本均不适用。5. 引用各基座论文与相关参考文献(CALM、LayerSkip 论文仅作思想引用)。6. 遵守 Apache-2.0 第 6 条:不使用基座团队商标或暗示官方背书的名字 (如不要命名 "MiniCPM5-Amoeba-Official")。7. 对使用到的 CC-BY-4.0 数据在 model card 致谢中署名。
---
简言之:**基座版权归原作者,Amoeba 仅发布增量改造;按上表继承对应license,并在 HuggingFace model card 中完成 base_model / 修改声明 /非官方背书 / 数据署名即可合规发布。**123456789101112131415161718192021MIT License
Copyright (c) 2026 MNN Team
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE..gitattributes+1
.gitignoreAdded+8
AMOEBA_PAPER_DRAFT.docxAdded
AMOEBA_PAPER_DRAFT.pdfAdded+3
AMOEBA_PAPER_DRAFT.texAdded+731
Amoeba-0.3B/LICENSEAdded+21
Amoeba-0.3B/README.mdAdded+179
Amoeba-0.3B/halt_heads.ptAdded+3
Amoeba-0.3B/infer_with_gate.pyAdded+112
Amoeba-0.6B/LICENSEAdded+21
Amoeba-0.6B/README.mdAdded+177
Amoeba-0.6B/halt_heads.ptAdded+3
Amoeba-0.6B/infer_with_gate.pyAdded+112
Amoeba-1B/LICENSEAdded+21
Amoeba-1B/README.mdAdded+177
Amoeba-1B/amoeba_da_infer.pyAdded+89
Amoeba-1B/halt_heads.ptAdded+3
Amoeba-1B/infer_with_gate.pyAdded+112
Amoeba-1B/medusa_chat.ptAdded+3
Amoeba-2B/LICENSEAdded+21
Amoeba-2B/README.mdAdded+181
Amoeba-2B/amoeba_da_infer.pyAdded+89
Amoeba-2B/halt_heads.ptAdded+3
Amoeba-2B/infer_with_gate.pyAdded+112
Amoeba-2B/medusa_chat.ptAdded+3
DOWNLOAD.mdAdded+10
HF_MODEL_CARD_TEMPLATE.mdAdded+58
LICENSEAdded+201
MANIFEST.jsonAdded+155
README.md+93-3
README_legacy_earlyexit.mdAdded+373
README_zh.mdAdded+83
README_zh_legacy.mdAdded+320
_LICENSES/APACHE-2.0.txtAdded+201
_LICENSES/LICENSE_NOTE.mdAdded+68
_LICENSES/MIT.txtAdded+21