Text Generation
Transformers
Safetensors
GGUF
lfm3
liquid
depth-loop
training-free
custom_code
conversational
Instructions to use vaultpls/LFM3-1.7B-Looped with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use vaultpls/LFM3-1.7B-Looped with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="vaultpls/LFM3-1.7B-Looped", 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", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("vaultpls/LFM3-1.7B-Looped", 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 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:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped: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:Q8_0 # Run inference directly in the terminal: llama cli -hf vaultpls/LFM3-1.7B-Looped: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:Q8_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf vaultpls/LFM3-1.7B-Looped:Q8_0
Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Llama new
- LM Studio
- Jan
- vLLM
How to use vaultpls/LFM3-1.7B-Looped 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" # 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", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- SGLang
How to use vaultpls/LFM3-1.7B-Looped 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" \ --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", "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" \ --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", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Ollama
How to use vaultpls/LFM3-1.7B-Looped with Ollama:
ollama run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Unsloth Desktop
- Pi
How to use vaultpls/LFM3-1.7B-Looped 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: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:Q8_0" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use vaultpls/LFM3-1.7B-Looped with Docker Model Runner:
docker model run hf.co/vaultpls/LFM3-1.7B-Looped:Q8_0
- Lemonade
How to use vaultpls/LFM3-1.7B-Looped with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull vaultpls/LFM3-1.7B-Looped:Q8_0
Run and chat with the model
lemonade run user.LFM3-1.7B-Looped-Q8_0
List all available models
lemonade list
- Hermes Agent
How to use vaultpls/LFM3-1.7B-Looped 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: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:Q8_0
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use vaultpls/LFM3-1.7B-Looped 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: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: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/tfl.py from vaultpls/LFM3-1.7B-Looped: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/vaultpls/LFM3-1.7B-Looped/resolve/main/scripts/tfl.py
- Command line
-
hf download hf://vaultpls/LFM3-1.7B-Looped/scripts/tfl.py
-
curl -L -o tfl.py https://huggingface.co/vaultpls/LFM3-1.7B-Looped/resolve/main/scripts/tfl.py
24.1 kB
| #!/usr/bin/env python3 | |
| """Training-free looped LFM3: repeat a mid-stack window with damped residual steps. | |
| Implements the "run x layers K times, 1/K of a step per pass" wrapper from | |
| arXiv 2605.23872 (training-free looped transformers) as a *static* graph: | |
| the window is physically duplicated and every application's residual output is | |
| damped by alpha, so the result is a plain deeper HF model that supports | |
| generate()/KV-cache with no runtime wrapper. | |
| Why the damping goes in the sandwich norms | |
| ------------------------------------------ | |
| Each LFM3 layer is h' = h + post_op_norm(op(pre_norm(h))) + post_ffn_norm(ffn(...)). | |
| Scaling o_proj/out_proj/w2 does NOT damp the branch: the post-norm is RMSNorm, which | |
| divides out the scale. Scaling `post_operator_norm.weight` / `post_ffn_norm.weight` | |
| by alpha scales the branch output by exactly alpha, which is the step damping. | |
| alpha=1/reps, reps=2 -> damped Euler K=2: x <- x + 1/2 (g(x) - x), twice | |
| alpha=1.0, reps=2 -> naive loop (control: paper says this degrades) | |
| alpha=0.75, reps=1 -> static equivalent of the paper's K=2 RK beta=0.5 | |
| Subcommands: identity | ppl | grid | bake | gsm8k | |
| """ | |
| import argparse, copy, json, math, os, re, sys, time | |
| import torch | |
| import torch.nn as nn | |
| BASE = os.environ.get("LFM3_BASE", "base-model") | |
| DATA = os.environ.get("LFM3_DATA", "data") | |
| def load(path=None, dtype=torch.bfloat16): | |
| path = path or BASE | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True) | |
| m = AutoModelForCausalLM.from_pretrained( | |
| path, trust_remote_code=True, dtype=dtype, attn_implementation="sdpa", device_map={"": 0}) | |
| return m, tok | |
| def _damp(layer, alpha): | |
| if alpha == 1.0: | |
| return | |
| with torch.no_grad(): | |
| layer.post_operator_norm.weight.mul_(alpha) | |
| layer.post_ffn_norm.weight.mul_(alpha) | |
| def scale_q(m, beta): | |
| """Multiply every attention query projection by beta = global attention temperature.""" | |
| with torch.no_grad(): | |
| for lay in m.model.layers: | |
| if not hasattr(lay, "self_attn"): | |
| continue # LFM3 alternates: conv layers have no attention | |
| q = lay.self_attn.q_proj | |
| q.weight.mul_(beta) | |
| if getattr(q, "bias", None) is not None: | |
| q.bias.mul_(beta) | |
| return m | |
| def scale_all_post(m, gamma): | |
| """Scale every layer's residual branch output by gamma (global residual gain).""" | |
| with torch.no_grad(): | |
| for lay in m.model.layers: | |
| lay.post_operator_norm.weight.mul_(gamma) | |
| lay.post_ffn_norm.weight.mul_(gamma) | |
| return m | |
| def conv_loop(m, a, b, alpha=0.5): | |
| """Repeat ONLY the shortconv sublayer inside [a,b], damped alpha per pass. | |
| Attention layers in the window are left untouched (LFM3 alternates conv/attn).""" | |
| n = 0 | |
| for lay in m.model.layers[a:b + 1]: | |
| if hasattr(lay, "self_attn"): | |
| continue | |
| def make(layer, al=alpha): | |
| def fwd(hidden_states, position_embeddings=None, attention_mask=None, | |
| position_ids=None, past_key_values=None, seq_idx=None, **kw): | |
| res = hidden_states | |
| h = layer.conv(layer.operator_norm(res), past_key_values=past_key_values, | |
| attention_mask=attention_mask, seq_idx=seq_idx) | |
| h = layer.post_operator_norm(h) | |
| mid = res + al * h | |
| h2 = layer.conv(layer.operator_norm(mid), past_key_values=past_key_values, | |
| attention_mask=attention_mask, seq_idx=seq_idx) | |
| h2 = layer.post_operator_norm(h2) | |
| out = mid + al * h2 | |
| f = layer.feed_forward(layer.ffn_norm(out)) | |
| f = layer.post_ffn_norm(f) | |
| return out + f | |
| return fwd | |
| lay.forward = make(lay) | |
| n += 1 | |
| print(f"conv_loop: patched {n} conv sublayers in [{a},{b}] alpha={alpha}", flush=True) | |
| return m | |
| def build_multi(ops): | |
| """Several loop windows in one model. ops: list of (a, b, reps, alpha), applied from | |
| the highest start index down so that earlier indices stay valid while later ones shift. | |
| Disjoint windows compose; overlapping ones are not checked.""" | |
| m, tok = load() | |
| inner = m.model | |
| n0 = len(inner.layers) | |
| for a, b, reps, alpha in sorted(ops, key=lambda o: -o[0]): | |
| types = list(inner.config.layer_types) | |
| chunk = list(inner.layers[a:b + 1]) | |
| for lay in chunk: | |
| _damp(lay, alpha) | |
| new = [] | |
| for r in range(reps - 1): | |
| for j, lay in enumerate(chunk): | |
| new.append(copy.deepcopy(lay)) | |
| inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:])) | |
| inner.config.layer_types = (types[:b + 1] | |
| + [types[a + j] for _ in range(reps - 1) for j in range(len(chunk))] | |
| + types[b + 1:]) | |
| assert len(inner.layers) == len(inner.config.layer_types) | |
| inner.config.num_hidden_layers = len(inner.layers) | |
| m.config.num_hidden_layers = inner.config.num_hidden_layers | |
| m.config.layer_types = inner.config.layer_types | |
| for pos, lay in enumerate(inner.layers): | |
| if hasattr(lay, "self_attn"): | |
| lay.self_attn.layer_idx = pos | |
| if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"): | |
| lay.conv.layer_idx = pos | |
| m.eval() | |
| return m, tok | |
| def build(window=(10, 13), reps=2, alpha=None, gains=None): | |
| """Return a plain HF model: window [a,b] executed `reps` times, each application | |
| damped by `alpha` (default 1/reps = K equal sub-steps of the same total update). | |
| `gains` overrides per-application damping, e.g. [0.5, 1.0] = RK2 midpoint.""" | |
| if gains is not None: | |
| reps = len(gains) | |
| alpha = (1.0 / reps) if alpha is None else float(alpha) | |
| if gains is None: | |
| gains = [alpha] * reps | |
| assert len(gains) == reps | |
| m, tok = load() | |
| inner = m.model | |
| a, b = window | |
| chunk = list(inner.layers[a:b + 1]) | |
| types = list(inner.config.layer_types) | |
| n0 = len(inner.layers) | |
| # damp every application, including the original window | |
| for lay in chunk: | |
| _damp(lay, gains[0]) | |
| new, new_types = [], [] | |
| for r in range(reps - 1): | |
| for j, lay in enumerate(chunk): | |
| c = copy.deepcopy(lay) | |
| if gains[r + 1] != gains[0]: | |
| # copy carries the first pass's scale; rescale to this pass's gain | |
| with torch.no_grad(): | |
| c.post_operator_norm.weight.mul_(gains[r + 1] / gains[0]) | |
| c.post_ffn_norm.weight.mul_(gains[r + 1] / gains[0]) | |
| new.append(c) | |
| new_types.append(types[a + j]) | |
| inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:])) | |
| inner.config.layer_types = types[:b + 1] + new_types + types[b + 1:] | |
| inner.config.num_hidden_layers = n0 + len(new) | |
| m.config.num_hidden_layers = inner.config.num_hidden_layers | |
| m.config.layer_types = inner.config.layer_types | |
| # layer_idx must equal the layer's POSITION: the KV cache and the per-layer | |
| # metadata arrays are indexed by it, so a mid-stack insertion shifts every | |
| # later layer and every copy must take its own slot. | |
| for pos, lay in enumerate(inner.layers): | |
| if hasattr(lay, "self_attn"): | |
| lay.self_attn.layer_idx = pos | |
| if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"): | |
| lay.conv.layer_idx = pos | |
| m.eval() | |
| return m, tok | |
| # ---------------------------------------------------------------- reference wrapper | |
| class RefLoop: | |
| """Independent implementation of the same math without duplicating weights: | |
| scale the two sandwich-norm outputs, then run the window `reps` times.""" | |
| def __init__(self, model, window, reps, alpha): | |
| self.model, self.reps, self.alpha = model, reps, alpha | |
| self.a, self.b = window | |
| self.handles = [] | |
| for i in range(self.a, self.b + 1): | |
| lay = model.model.layers[i] | |
| for mod in (lay.post_operator_norm, lay.post_ffn_norm): | |
| self.handles.append(mod.register_forward_hook(self._hook)) | |
| def _hook(self, module, args, out): | |
| return out * self.alpha | |
| def run(self, model_layer_loop): | |
| return model_layer_loop(self.reps) | |
| def remove(self): | |
| for h in self.handles: | |
| h.remove() | |
| def ref_forward(model, ids, window, reps, alpha): | |
| """Compose pre-loop layers, then the window x reps, then post-loop layers.""" | |
| inner = model.model | |
| a, b = window | |
| ref = RefLoop(model, window, reps, alpha) | |
| h = inner.embed_tokens(ids) | |
| pos = torch.arange(ids.shape[1], device=ids.device).unsqueeze(0) | |
| pe = {t: inner.rotary_emb(h, position_ids=pos, layer_type=t) for t in inner.rotary_emb.layer_types} | |
| modeling = sys.modules[inner.__class__.__module__] | |
| cm = modeling.create_masks_by_layer_type(config=inner.config, inputs_embeds=h, attention_mask=None, | |
| past_key_values=None, position_ids=pos) | |
| def run(i): | |
| nonlocal h | |
| lt = inner.config.layer_types[i] | |
| h = inner.layers[i](h, attention_mask=cm[lt], position_embeddings=pe.get(lt), | |
| position_ids=pos, past_key_values=None, seq_idx=None) | |
| for i in range(a): | |
| run(i) | |
| for _ in range(reps): | |
| for i in range(a, b + 1): | |
| run(i) | |
| for i in range(b + 1, len(inner.layers)): | |
| run(i) | |
| ref.remove() | |
| return inner.embedding_norm(h) | |
| # ---------------------------------------------------------------- data / metrics | |
| class TextDS(torch.utils.data.Dataset): | |
| def __init__(self, path, tok, ctx, max_windows=None): | |
| ids = [] | |
| with open(path, "r", encoding="utf-8", errors="ignore") as f: | |
| buf = [] | |
| for line in f: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| buf.append(line) | |
| if len(buf) >= 64: | |
| ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"]) | |
| buf = [] | |
| if max_windows and len(ids) >= max_windows * ctx: | |
| break | |
| if buf: | |
| ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"]) | |
| self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)] | |
| if max_windows: | |
| self.windows = self.windows[:max_windows] | |
| def __len__(self): | |
| return len(self.windows) | |
| def __getitem__(self, i): | |
| w = self.windows[i] | |
| return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)} | |
| class StreamDS(torch.utils.data.Dataset): | |
| """Whole-file tokenisation (single stream), the way llama-perplexity reads it. | |
| TextDS's 64-line joining inflates PPL and is not comparable across models.""" | |
| def __init__(self, path, tok, ctx, n=None, max_windows=None): | |
| n = n or max_windows | |
| ids = tok(open(path, "r", encoding="utf-8", errors="ignore").read(), add_special_tokens=False)["input_ids"] | |
| self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)][:n] | |
| def __len__(self): | |
| return len(self.windows) | |
| def __getitem__(self, i): | |
| w = self.windows[i] | |
| return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)} | |
| def ppl(model, ds, n_batches=16, bs=2): | |
| model.eval() | |
| dl = torch.utils.data.DataLoader(ds, batch_size=bs, shuffle=False) | |
| tot, cnt = 0.0, 0 | |
| for i, b in enumerate(dl): | |
| if i >= n_batches: | |
| break | |
| ids = b["input_ids"].cuda() | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| out = model(input_ids=ids, labels=ids) | |
| tot += out.loss.float().item() * ids.numel() | |
| cnt += ids.numel() | |
| return math.exp(tot / cnt) | |
| def gsm8k_rows(n=100): | |
| rows, txt = [], open(os.path.join(DATA, "gsm8k-test.txt")).read() | |
| for block in txt.split("\n\n"): | |
| mm = re.search(r"Question: (.*?)\nAnswer: (.*)", block, re.S) | |
| if not mm: | |
| continue | |
| gold = re.search(r"####\s*([\-\d\.,]+)", mm.group(2)) | |
| if gold: | |
| rows.append((mm.group(1).strip(), gold.group(1).replace(",", "").strip())) | |
| if len(rows) >= n: | |
| break | |
| return rows | |
| def last_number(s): | |
| nums = re.findall(r"-?\d[\d,]*\.?\d*", s.replace("$", "")) | |
| return nums[-1].replace(",", "").rstrip(".") if nums else None | |
| def run_gsm8k(model, tok, rows, max_new=512): | |
| ok = 0 | |
| for q, gold in rows: | |
| msgs = [{"role": "user", "content": q + "\nAnswer with the final number on its own line."}] | |
| text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) | |
| ids = tok(text, return_tensors="pt").input_ids.cuda() | |
| out = model.generate(ids, max_new_tokens=max_new, do_sample=False, temperature=None, | |
| top_p=None, top_k=None, pad_token_id=tok.pad_token_id or tok.eos_token_id) | |
| pred = last_number(tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True)) | |
| ok += pred is not None and abs(float(pred) - float(gold)) < 0.01 | |
| return ok / len(rows) | |
| def arc_rows(config="ARC-Easy", n=500, shots=0): | |
| from datasets import load_dataset | |
| d = load_dataset("allenai/ai2_arc", config, split="test") | |
| pre = "" | |
| if shots: | |
| tr = load_dataset("allenai/ai2_arc", config, split="train") | |
| for r in tr.select(range(min(shots, len(tr)))): | |
| ans = r["choices"]["text"][r["choices"]["label"].index(r["answerKey"])] | |
| pre += f"Question: {r['question']}\nAnswer: {ans}\n\n" | |
| rows = [] | |
| for r in d: | |
| lab, txt = r["choices"]["label"], r["choices"]["text"] | |
| if r["answerKey"] not in lab: | |
| continue | |
| rows.append((r["question"], lab, txt, lab.index(r["answerKey"]))) | |
| if len(rows) >= n: | |
| break | |
| return rows, pre | |
| def run_arc(model, tok, rows, pre="", score="mean", dump=False): | |
| """ARC multiple-choice, base-LM style: score each choice *text* as the continuation | |
| of "Question: ...\\nAnswer:" and take the argmax of the (optionally length-normalised) | |
| log-probability.""" | |
| per, alls = [], [] | |
| for q, lab, txt, gold in rows: | |
| pid = tok(pre + "Question: " + q + "\nAnswer:", return_tensors="pt").input_ids.cuda() | |
| scores = [] | |
| for t in txt: | |
| cid = tok(" " + t, add_special_tokens=False, return_tensors="pt").input_ids.cuda() | |
| out = model(input_ids=torch.cat([pid, cid], dim=1), use_cache=False) | |
| lp = torch.log_softmax(out.logits[0, pid.shape[1] - 1:pid.shape[1] - 1 + cid.shape[1]].float(), -1) | |
| s = lp[range(cid.shape[1]), cid[0]] | |
| scores.append(s.mean().item() if score == "mean" else s.sum().item()) | |
| del out | |
| per.append(int(max(range(len(txt)), key=lambda i: scores[i]) == gold)) | |
| alls.append(scores) | |
| return (per, alls) if dump else per | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("cmd", choices=["identity", "ppl", "grid", "gsm8k", "bake", "arc", "sweep"]) | |
| ap.add_argument("--window", default="10,13") | |
| ap.add_argument("--base", action="store_true", help="evaluate the unmodified checkpoint") | |
| ap.add_argument("--reps", type=int, default=2) | |
| ap.add_argument("--alpha", type=float, default=None) | |
| ap.add_argument("--n-pll", type=int, default=16) | |
| ap.add_argument("--gsm", type=int, default=80) | |
| ap.add_argument("--arc-config", default="ARC-Easy") | |
| ap.add_argument("--arc-n", type=int, default=400) | |
| ap.add_argument("--shots", type=int, default=0) | |
| ap.add_argument("--stream", action="store_true") | |
| ap.add_argument("--multi", default=None, help="a,b,reps,alpha;... several loop windows") | |
| ap.add_argument("--gains", default=None, help="comma list, per-pass damping e.g. 0.5,1.0") | |
| ap.add_argument("--qscale", type=float, default=1.0, help="global query scale = attention temperature") | |
| ap.add_argument("--postscale", type=float, default=1.0, help="global residual branch gain") | |
| ap.add_argument("--convloop", default=None, help="a,b,alpha: run only the shortconv sublayer twice inside [a,b]") | |
| ap.add_argument("--arc-score", default="mean", choices=["mean", "sum"]) | |
| ap.add_argument("--out", default="out-tfl") | |
| ap.add_argument("--data-dir", default=os.environ.get("LFM3_DATA", "data"), | |
| help="dir with wikitext-test.txt / gsm8k-test.txt / gsm8k-train-chat.txt") | |
| ap.add_argument("--base-model", default=os.environ.get("LFM3_BASE", "base-model"), | |
| help="HF dir of the unmodified checkpoint (default $LFM3_BASE)") | |
| args = ap.parse_args() | |
| global BASE, DATA | |
| BASE = args.base_model | |
| DATA = args.data_dir | |
| a, b = [int(x) for x in args.window.split(",")] | |
| window = (a, b) | |
| if args.cmd == "identity": | |
| base, tok = load() | |
| ids = torch.randint(1000, 60000, (1, 128), device="cuda") | |
| with torch.no_grad(): | |
| ref = base(input_ids=ids).logits.float() | |
| # same weights, no extra copy -> must be exact | |
| dup, _ = build(window, reps=1, alpha=1.0) | |
| with torch.no_grad(): | |
| got = dup(input_ids=ids).logits.float() | |
| d = (ref - got).abs().max().item() | |
| print(f"build(window={window}, reps=1, alpha=1) vs base: max|dlogit| = {d:.3e}") | |
| del dup | |
| torch.cuda.empty_cache() | |
| # reference wrapper: run the same window reps times with alpha damping | |
| for alpha in (1.0, 0.5, 1 / 3): | |
| h_ref = ref_forward(base, ids, window, args.reps, alpha).float() | |
| damp, _ = build(window, reps=args.reps, alpha=alpha) | |
| with torch.no_grad(): | |
| h_dup = damp.model(input_ids=ids).last_hidden_state.float() | |
| dd = (h_ref - h_dup).abs().max().item() | |
| print(f"alpha={alpha:.3f}: wrapper vs static dup max|d| = {dd:.3e}") | |
| del damp | |
| torch.cuda.empty_cache() | |
| return | |
| if args.cmd in ("ppl", "bake", "arc", "gsm8k"): | |
| if args.base: | |
| m, tok = load() | |
| m.eval() | |
| tag = "base" | |
| elif args.multi: | |
| ops = [] | |
| for spec in args.multi.split(";"): | |
| aa, bb, rr, al = [float(x) for x in spec.split(",")] | |
| ops.append((int(aa), int(bb), int(rr), al)) | |
| m, tok = build_multi(ops) | |
| tag = "multi:" + "+".join(f"{o[0]}-{o[1]}x{o[2]}@{o[3]:.2f}" for o in ops) | |
| else: | |
| gains = [float(x) for x in args.gains.split(",")] if args.gains else None | |
| m, tok = build(window, reps=args.reps, alpha=args.alpha, gains=gains) | |
| tag = (f"{args.window} gains={gains}" if gains | |
| else f"{args.window} x{args.reps} alpha={1/args.reps if args.alpha is None else args.alpha}") | |
| if args.qscale != 1.0: | |
| scale_q(m, args.qscale) | |
| tag += f" q*{args.qscale}" | |
| if args.postscale != 1.0: | |
| scale_all_post(m, args.postscale) | |
| tag += f" post*{args.postscale}" | |
| if args.convloop: | |
| ca, cb, cal = [float(x) for x in args.convloop.split(",")] | |
| conv_loop(m, int(ca), int(cb), cal) | |
| tag += f" convloop{args.convloop}" | |
| if args.cmd == "ppl": | |
| DS = StreamDS if args.stream else TextDS | |
| wt = DS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| ood = StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, args.n_pll * 2) if args.stream else TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| print(json.dumps({"tag": tag, "wikitext": round(ppl(m, wt, args.n_pll), 4), | |
| "gsm8k_text": round(ppl(m, ood, args.n_pll), 4)})) | |
| return | |
| if args.cmd == "grid": | |
| cfg = [ | |
| ("base", None, 1, 1.0), | |
| ("naive K2 @[10-13]", (10, 13), 2, 1.0), | |
| ("damped K2 @[10-13]", (10, 13), 2, 0.5), | |
| ("damped K3 @[10-13]", (10, 13), 3, 1 / 3), | |
| ("step0.75 @[10-13]", (10, 13), 1, 0.75), | |
| ("damped K2 @[8-11]", (8, 11), 2, 0.5), | |
| ("damped K2 @[12-15]", (12, 15), 2, 0.5), | |
| ("damped K2 @[11-12]", (11, 12), 2, 0.5), | |
| ("damped K2 @[9-12]", (9, 12), 2, 0.5), | |
| ] | |
| tok = None | |
| rows = [] | |
| for tag, w, reps, alpha in cfg: | |
| t0 = time.time() | |
| if w is None: | |
| m, tok = load() | |
| m.eval() | |
| else: | |
| m, tok = build(w, reps=reps, alpha=alpha) | |
| wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| r = {"tag": tag, "layers": m.config.num_hidden_layers, | |
| "wikitext": round(ppl(m, wt, args.n_pll), 4), | |
| "gsm8k_text": round(ppl(m, ood, args.n_pll), 4), "s": round(time.time() - t0, 1)} | |
| print(json.dumps(r), flush=True) | |
| rows.append(r) | |
| del m | |
| torch.cuda.empty_cache() | |
| json.dump(rows, open(os.path.join(args.out, "grid.json"), "w"), indent=1) | |
| return | |
| if args.cmd == "sweep": | |
| m, tok = load() | |
| m.eval() | |
| wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2) | |
| names = [] | |
| for i in range(a, b + 1): | |
| names += [m.model.layers[i].post_operator_norm.weight, m.model.layers[i].post_ffn_norm.weight] | |
| orig = [t.detach().clone() for t in names] | |
| for alpha in (1.0, 1.25, 1.5, 0.9, 0.85, 0.75, 0.7, 0.6, 0.5, 0.4, 0.3): | |
| with torch.no_grad(): | |
| for t, o in zip(names, orig): | |
| t.copy_(o).mul_(alpha) | |
| print(json.dumps({"alpha": alpha, "wikitext": round(ppl(m, wt, args.n_pll), 4), | |
| "gsm8k_text": round(ppl(m, ood, args.n_pll), 4)}), flush=True) | |
| with torch.no_grad(): | |
| for t, o in zip(names, orig): | |
| t.copy_(o) | |
| return | |
| if args.cmd == "bake": | |
| outdir = os.path.join(args.out, f"baked-{a}_{b}-x{args.reps}@{ (1/args.reps if args.alpha is None else args.alpha):.3f}".replace("/", "") ) | |
| m.save_pretrained(outdir) | |
| tok.save_pretrained(outdir) | |
| for f in ("modeling_lfm3.py", "configuration_lfm3.py", "lfm3_conv.py", "chat_template.jinja"): | |
| src = os.path.join(BASE, f) | |
| if os.path.exists(src): | |
| import shutil | |
| shutil.copy2(src, os.path.join(outdir, f)) | |
| print("baked ->", outdir, "layers:", m.config.num_hidden_layers) | |
| return | |
| if args.cmd == "arc": | |
| rows, pre = arc_rows(args.arc_config, args.arc_n, args.shots) | |
| t0 = time.time() | |
| per, lps = run_arc(m, tok, rows, pre, args.arc_score, dump=True) | |
| acc = sum(per) / len(per) | |
| print(f"{tag}: {args.arc_config} {args.shots}-shot acc_norm {acc*100:.1f}% over {len(per)} ({time.time()-t0:.0f}s)", flush=True) | |
| key = f"arc-{args.arc_config}-{args.arc_n}-{args.shots}shot-{args.arc_score}-{tag}".replace(" ", "").replace(",", "_").replace("=", "") | |
| json.dump({"per": per, "lp": lps, "gold": [r[3] for r in rows], "n_opt": [len(r[2]) for r in rows]}, | |
| open(os.path.join(args.out, key + ".json"), "w")) | |
| return | |
| if args.cmd == "gsm8k": | |
| rows = gsm8k_rows(args.gsm) | |
| t0 = time.time() | |
| acc = run_gsm8k(m, tok, rows) | |
| print(f"{tag}: GSM8K {acc*100:.1f}% over {len(rows)} ({time.time()-t0:.0f}s)", flush=True) | |
| return | |
| if __name__ == "__main__": | |
| main() | |