Text Generation
Transformers
Safetensors
llama
amoeba
speculative-decoding
small-language-model
text-generation-inference
Run this model with HF Jobs
Run leexamp/Amoeba-1B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/leexamp/Amoeba-1B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/leexamp/Amoeba-1B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/leexamp/Amoeba-1B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/leexamp/Amoeba-1B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use leexamp/Amoeba-1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use leexamp/Amoeba-1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="leexamp/Amoeba-1B")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("leexamp/Amoeba-1B") model = AutoModelForCausalLM.from_pretrained("leexamp/Amoeba-1B", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use leexamp/Amoeba-1B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "leexamp/Amoeba-1B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "leexamp/Amoeba-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/leexamp/Amoeba-1B
- SGLang
How to use leexamp/Amoeba-1B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "leexamp/Amoeba-1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "leexamp/Amoeba-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "leexamp/Amoeba-1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "leexamp/Amoeba-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use leexamp/Amoeba-1B with Docker Model Runner:
docker model run hf.co/leexamp/Amoeba-1B
Upload 10 files
Browse filesFiles changed (10)
- LICENSEAdded+21
- README.md+17-3
- amoeba_da_infer.pyAdded+89
- config.jsonAdded+35
- generation_config.jsonAdded+13
- infer_with_gate.pyAdded+112
- medusa_chat.ptAdded+3
- model.safetensorsAdded+3
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+17
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;用户可自行调整版权信息。123---license: apache-2.0---1234567891011121314151617---library_name: transformerslicense: apache-2.0pipeline_tag: text-generationtags:- amoeba- speculative-decoding- small-language-model---# Amoeba-1BPart of the [Amoeba release](https://github.com/leexamp/Amoeba). Base: 1B. Size: 2061 MB.**Amoeba-DA speedup:** 1.30x. Token agreement on 2B is 0.734; we claim downstream capability preservation, not bit-exact losslessness.All weights Apache-2.0. Full empirical study (including negative results): see the paper in the GitHub repo. CCI3 dirty corpus was not used in released training.
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))1234567891011121314151617181920212223242526272829303132333435{ "architectures": [ "LlamaForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 0, "dtype": "bfloat16", "eos_token_id": [ 1, 130073 ], "head_dim": 128, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 4608, "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama", "num_attention_heads": 16, "num_hidden_layers": 24, "num_key_value_heads": 2, "pad_token_id": 1, "pretraining_tp": 1, "rms_norm_eps": 1e-06, "rope_parameters": { "rope_theta": 5000000, "rope_type": "default" }, "tie_word_embeddings": false, "transformers_version": "5.24.0", "use_cache": false, "vocab_size": 130560}12345678910111213{ "_from_model_config": true, "bos_token_id": 0, "do_sample": true, "eos_token_id": [ 1, 130073 ], "pad_token_id": 1, "temperature": 0.9, "top_p": 0.95, "transformers_version": "5.24.0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# -*- 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 25169839123version https://git-lfs.github.com/spec/v1oid sha256:3a3aee573572bfbf8a963d88c43e511372e33dae1881d48b20fde66140fae36csize 21612909441234567891011121314151617{ "add_prefix_space": null, "backend": "tokenizers", "bos_token": "<s>", "clean_up_tokenization_spaces": false, "eos_token": "</s>", "is_local": true, "legacy": true, "local_files_only": false, "model_max_length": 1000000000000000019884624838656, "pad_token": "</s>", "sp_model_kwargs": {}, "spaces_between_special_tokens": false, "tokenizer_class": "TokenizersBackend", "unk_token": "<unk>", "use_default_system_prompt": false}LICENSEAdded+21
README.md+17-3
amoeba_da_infer.pyAdded+89
config.jsonAdded+35
generation_config.jsonAdded+13
infer_with_gate.pyAdded+112
medusa_chat.ptAdded+3
model.safetensorsAdded+3
tokenizer.jsonAdded
tokenizer_config.jsonAdded+17