Text Generation
Transformers
Safetensors
GGUF
lfm3
liquid
depth-loop
recurrent-depth
distillation
custom_code
conversational
Instructions to use vaultpls/LFM3-1.7B-Looped-Distilled with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="vaultpls/LFM3-1.7B-Looped-Distilled", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("vaultpls/LFM3-1.7B-Looped-Distilled", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("vaultpls/LFM3-1.7B-Looped-Distilled", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use vaultpls/LFM3-1.7B-Looped-Distilled with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
- Llama new
- LM Studio
- Jan
- vLLM
How to use vaultpls/LFM3-1.7B-Looped-Distilled with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "vaultpls/LFM3-1.7B-Looped-Distilled" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped-Distilled", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
- SGLang
How to use vaultpls/LFM3-1.7B-Looped-Distilled 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 "vaultpls/LFM3-1.7B-Looped-Distilled" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped-Distilled", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "vaultpls/LFM3-1.7B-Looped-Distilled" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "vaultpls/LFM3-1.7B-Looped-Distilled", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Ollama
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Ollama:
ollama run hf.co/vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
- Unsloth Desktop
- Pi
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Docker Model Runner:
docker model run hf.co/vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
- Lemonade
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Run and chat with the model
lemonade run user.LFM3-1.7B-Looped-Distilled-Q8_0
List all available models
lemonade list
- Hermes Agent
How to use vaultpls/LFM3-1.7B-Looped-Distilled with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use vaultpls/LFM3-1.7B-Looped-Distilled with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "vaultpls/LFM3-1.7B-Looped-Distilled:Q8_0" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Download scripts/distill_bridge_static.py from vaultpls/LFM3-1.7B-Looped-Distilled: direct link, hf CLI and curl.
- Browser
- Download file 9.57 kB
-
https://huggingface.co/vaultpls/LFM3-1.7B-Looped-Distilled/resolve/main/scripts/distill_bridge_static.py
- Command line
-
hf download hf://vaultpls/LFM3-1.7B-Looped-Distilled/scripts/distill_bridge_static.py
-
curl -L -o distill_bridge_static.py https://huggingface.co/vaultpls/LFM3-1.7B-Looped-Distilled/resolve/main/scripts/distill_bridge_static.py
9.57 kB
| #!/usr/bin/env python3 | |
| """Distill the static+bridge teacher into a bridge-free static 28-layer student. | |
| Teacher: published static loop [8,11]x2 alpha=0.5 + rank-64 bridge (the 500-step | |
| checkpoint). Student: the same static loop, no bridge, with LoRA on the copied | |
| layers and four copy-level gates. Targets: the teacher's final hidden states on | |
| a wikitext/GSM8K mix plus next-token CE. If the student matches, it is a plain | |
| 28-layer checkpoint that converts to GGUF with no custom op. | |
| """ | |
| import argparse, json, math, os, random, sys, time | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.utils.data import DataLoader | |
| os.environ.setdefault("LFM3_BASE", "/home/vault/lfm3/base-model") | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import tfl | |
| import retrofit_bridge_static as rbs | |
| DATA = "/home/vault/lfm3/train/data" | |
| def gate_hook(module, args, output): | |
| h = args[0] | |
| g = 1.0 + torch.tanh(module._student_gate_raw) | |
| return h + g.to(output.dtype) * (output - h) | |
| def build_student(gate_init=0.0, gates=True): | |
| m, tok = tfl.build((8, 11), reps=2, alpha=0.5) | |
| if gates: | |
| for c in m.model.layers[12:16]: | |
| raw = nn.Parameter(torch.tensor(float(gate_init), device=m.device)) | |
| c._student_gate_raw = raw | |
| c.register_forward_hook(gate_hook) | |
| return m, tok | |
| def add_lora(m, rank=64): | |
| from peft import LoraConfig, get_peft_model | |
| cfg = LoraConfig(r=rank, lora_alpha=rank * 2, lora_dropout=0.0, bias="none", | |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj", | |
| "in_proj", "out_proj", "w1", "w2", "w3"]) | |
| m = get_peft_model(m, cfg) | |
| for p in m.parameters(): | |
| p.requires_grad_(False) | |
| for n, p in m.named_parameters(): | |
| is_copy = any(f".layers.{i}." in n for i in range(12, 16)) | |
| if (is_copy and "lora_" in n) or "_student_gate_raw" in n: | |
| p.requires_grad_(True) | |
| m.print_trainable_parameters() | |
| return m | |
| def teacher_hidden(teacher, tok, n_per=250, ctx=1024, data="mix"): | |
| wt = tfl.TextDS(os.path.join(DATA, "wikitext-train.txt"), tok, ctx, max_windows=n_per) | |
| datasets = [wt] | |
| if data != "wiki": | |
| datasets.append(tfl.TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, ctx, max_windows=n_per)) | |
| windows, hs = [], [] | |
| for ds in datasets: | |
| for i in range(len(ds)): | |
| ids = ds[i]["input_ids"].unsqueeze(0).cuda() | |
| with torch.no_grad(): | |
| h = teacher.model(input_ids=ids).last_hidden_state | |
| windows.append(ds[i]["input_ids"]) | |
| hs.append(h[0].to(torch.bfloat16).cpu()) | |
| print(f"teacher hidden: {len(windows)} windows x {ctx} = {len(windows)*ctx/1e6:.1f}M tokens") | |
| return windows, hs | |
| def train(args): | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| teacher, tok = rbs.build(alpha=0.5, rank=64) | |
| ck = torch.load(args.teacher_ckpt, map_location="cpu") | |
| miss, unexp = teacher.load_state_dict(ck["state"], strict=False) | |
| print("teacher loaded", ck["step"], "missing", len(miss), "unexpected", len(unexp)) | |
| teacher.eval() | |
| for p in teacher.parameters(): | |
| p.requires_grad_(False) | |
| windows, hs = teacher_hidden(teacher, tok, args.windows, args.ctx, args.data) | |
| del teacher | |
| torch.cuda.empty_cache() | |
| student, _ = build_student(gates=bool(args.gates)) | |
| student = add_lora(student, args.rank) | |
| if args.grad_ckpt: | |
| student.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) | |
| student.enable_input_require_grads() | |
| print("gradient checkpointing: on") | |
| base = student.get_base_model() | |
| V = base.config.vocab_size | |
| trainable = [p for p in student.parameters() if p.requires_grad] | |
| g_lora = [p for n, p in student.named_parameters() if p.requires_grad and "lora_" in n] | |
| g_gate = [p for n, p in student.named_parameters() if p.requires_grad and "_student_gate_raw" in n] | |
| print(f"param groups: lora {len(g_lora)} @ {args.lr}, gates {len(g_gate)} @ {args.gate_lr}") | |
| pg = [{"params": g_lora, "lr": args.lr}] | |
| if g_gate: | |
| pg.append({"params": g_gate, "lr": args.gate_lr}) | |
| opt = torch.optim.AdamW(pg, betas=(0.9, 0.95), weight_decay=0.0) | |
| sched = torch.optim.lr_scheduler.LambdaLR( | |
| opt, lambda s: min(1.0, (s + 1) / max(1, args.warmup)) * | |
| (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(1.0, s / max(1, args.steps)))))) | |
| student.train() | |
| t0 = time.time(); run_ce = run_mse = 0.0 | |
| os.makedirs(args.out, exist_ok=True) | |
| for step in range(1, args.steps + 1): | |
| idx = [random.randrange(len(windows)) for _ in range(args.bs)] | |
| ids = torch.stack([windows[i] for i in idx]).cuda() | |
| ht = torch.stack([hs[i] for i in idx]).cuda().float() | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| h = base.model(input_ids=ids).last_hidden_state | |
| logits = base.lm_head(h) | |
| ce = F.cross_entropy(logits[:, :-1].reshape(-1, V), ids[:, 1:].reshape(-1)) | |
| mse = F.mse_loss(h.float(), ht) / (ht.pow(2).mean() + 1e-6) | |
| loss = ce + args.mse * mse | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(trainable, 1.0) | |
| opt.step(); sched.step(); opt.zero_grad(set_to_none=True) | |
| run_ce += ce.item(); run_mse += mse.item() | |
| if step % 20 == 0: | |
| gates = [round(float(1 + torch.tanh(g.detach())), 4) for g in g_gate] | |
| gs = f" gates {gates}" if gates else "" | |
| print(f"step {step:4d} CE {run_ce/20:.4f} MSE {run_mse/20:.4f} " | |
| f"lr {sched.get_last_lr()[0]:.2e}{gs} {(time.time()-t0)/step:.2f}s/it", flush=True) | |
| run_ce = run_mse = 0.0 | |
| if step % args.eval_every == 0 or step == args.steps: | |
| student.eval() | |
| ev_wt = tfl.StreamDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=32) | |
| ev_gs = tfl.StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=32) | |
| print(f" [eval] wiki PPL {tfl.ppl(student, ev_wt, 16):.4f} gsm-text PPL {tfl.ppl(student, ev_gs, 16):.4f}", flush=True) | |
| student.train() | |
| save(student, tok, args.out, step) | |
| save(student, tok, args.out, args.steps) | |
| print("saved", args.out) | |
| def save(m, tok, outdir, step): | |
| os.makedirs(outdir, exist_ok=True) | |
| sd = {k: v.detach().cpu() for k, v in m.state_dict().items() | |
| if "lora_" in k or "_student_gate_raw" in k} | |
| torch.save({"step": step, "state": sd}, os.path.join(outdir, "ckpt.pt")) | |
| tok.save_pretrained(outdir) | |
| def eval_ckpt(args): | |
| student, tok = build_student(gates=bool(args.gates)) | |
| student = add_lora(student, args.rank) | |
| ckpath = args.ckpt or os.path.join(args.out, "ckpt.pt") | |
| ck = torch.load(ckpath, map_location="cpu") | |
| miss, unexp = student.load_state_dict(ck["state"], strict=False) | |
| print("student loaded", ck["step"], "missing", len(miss), "unexpected", len(unexp)) | |
| student.eval() | |
| ev_wt = tfl.StreamDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=32) | |
| ev_gs = tfl.StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=32) | |
| print(json.dumps({"tag": "distilled", "wikitext": round(tfl.ppl(student, ev_wt, 16), 4), | |
| "gsm8k_text": round(tfl.ppl(student, ev_gs, 16), 4)})) | |
| if args.arc: | |
| rows, pre = tfl.arc_rows(args.arc_config, args.arc, 5) | |
| t0 = time.time() | |
| per, lps = tfl.run_arc(student, tok, rows, pre, "mean", dump=True) | |
| print(f"distilled: {args.arc_config} 5-shot {sum(per)/len(per)*100:.1f}% over {len(per)} ({time.time()-t0:.0f}s)") | |
| json.dump({"per": per, "lp": lps}, open(os.path.join(args.out, f"arc-{args.arc_config}-distilled.json"), "w")) | |
| if args.gsm: | |
| rows = tfl.gsm8k_rows(args.gsm) | |
| t0 = time.time() | |
| per = tfl.run_gsm8k(student, tok, rows, dump=True) | |
| print(f"distilled: GSM8K {sum(per)/len(per)*100:.1f}% over {len(rows)} ({time.time()-t0:.0f}s)") | |
| json.dump(per, open(os.path.join(args.out, "gsm-distilled.json"), "w")) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("cmd", choices=["train", "eval"]) | |
| ap.add_argument("--out", default="/home/vault/lfm3/train/out-distill") | |
| ap.add_argument("--teacher-ckpt", default="/home/vault/lfm3/train/out-static-bridge/ckpt.pt") | |
| ap.add_argument("--steps", type=int, default=500) | |
| ap.add_argument("--bs", type=int, default=2) | |
| ap.add_argument("--ctx", type=int, default=1024) | |
| ap.add_argument("--windows", type=int, default=250, help="windows per corpus") | |
| ap.add_argument("--data", choices=["mix", "wiki"], default="mix") | |
| ap.add_argument("--lr", type=float, default=3e-4) | |
| ap.add_argument("--gate-lr", type=float, default=5e-3) | |
| ap.add_argument("--rank", type=int, default=64) | |
| ap.add_argument("--mse", type=float, default=1.0) | |
| ap.add_argument("--warmup", type=int, default=40) | |
| ap.add_argument("--eval-every", type=int, default=250) | |
| ap.add_argument("--gates", type=int, default=1) | |
| ap.add_argument("--grad-ckpt", type=int, default=1) | |
| ap.add_argument("--ckpt", default=None) | |
| ap.add_argument("--arc", type=int, default=0) | |
| ap.add_argument("--arc-config", default="ARC-Easy") | |
| ap.add_argument("--gsm", type=int, default=0) | |
| args = ap.parse_args() | |
| if args.cmd == "train": | |
| train(args) | |
| else: | |
| eval_ckpt(args) | |
| if __name__ == "__main__": | |
| main() | |