Repository navigation
Expand file tree
/
Copy pathmethodlm_models.py
More file actions
294 lines (264 loc) · 16.6 KB
/
Copy pathmethodlm_models.py
File metadata and controls
294 lines (264 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""Model backends for MethodLM -- the discipline is the product, not the model.
The enforced protocol (pre-registration, tools, honest ledger, ternary second witness)
is identical no matter which model generates the text. A backend only has to turn
(system, messages) into a reply string. Swap the backend, keep the method.
local : Qwen-3B via llama-completion.exe -- private, offline, free (default)
claude : Anthropic API (Claude Opus 4.8) -- frontier reasoning; needs
`pip install anthropic` + credentials (ANTHROPIC_API_KEY or `ant auth login`)
messages is a list of {"role": "user"|"assistant", "content": str}, first turn user.
"""
import os
import subprocess
class LocalLlama:
kind = "local"
label = "local Qwen-3B (offline)"
def __init__(self, llama, gguf, threads=8, ctx=None):
# ctx=3072 was the original default and is too small for multi-candidate panels:
# investigate()'s transcript grows by one ADJUST exchange (~500-1000 chars) per
# candidate column, and a 7-8 column panel fills 3072 tokens of prompt by turn 8-9
# -- with 0 tokens left for the response, llama-completion.exe returns an EMPTY
# completion (not a syntax error), which investigate()'s no-progress guard reads as
# 3 consecutive unrecognized-tool turns and kills the run with no FINAL. Verified
# directly: the qwen3b.gguf here reports n_ctx_train up to 32768 when -c is left at
# its own default, so 3072 was an artificial cap, not a model limit. Override via
# METHODLM_LOCAL_CTX if a given panel is even larger; 8192 gives headroom for a
# ~10-candidate panel (ADJUST + one REFUTE re-check per candidate) at the same
# threads/batch settings.
if ctx is None:
ctx = int(os.environ.get("METHODLM_LOCAL_CTX", "8192"))
self.llama, self.gguf, self.threads, self.ctx = llama, gguf, threads, ctx
self.label = f"local {os.path.splitext(os.path.basename(gguf))[0]} (gguf)"
def generate(self, system, messages, max_tokens=230, temp=0.3):
parts = [f"<|im_start|>system\n{system}<|im_end|>"]
for m in messages:
parts.append(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>")
parts.append("<|im_start|>assistant\n")
prompt = "\n".join(parts)
p = subprocess.run([self.llama, "-m", self.gguf, "-p", prompt, "-n", str(max_tokens),
"-t", str(self.threads), "-c", str(self.ctx), "--special",
"-no-cnv", "--temp", str(temp)],
capture_output=True, text=True, encoding="utf-8", errors="replace")
return p.stdout.split("<|im_start|>assistant\n")[-1].split("<|im_end|>")[0].strip()
class ClaudeAPI:
kind = "claude"
def __init__(self, model="claude-opus-4-8"):
try:
import anthropic
except ImportError:
raise SystemExit("claude backend needs the SDK: pip install anthropic")
self.model = model
self.label = f"Claude ({model})"
try:
self._client = anthropic.Anthropic() # resolves key/profile from env
self._client.models.list(limit=1) # validate credentials up front
except Exception as e:
raise SystemExit(f"Claude unavailable (need ANTHROPIC_API_KEY): {str(e)[:70]}")
def generate(self, system, messages, max_tokens=230, temp=None):
# Opus 4.8: system is separate; temperature/thinking omitted (rejected on 4.8).
resp = self._client.messages.create(
model=self.model, max_tokens=max(max_tokens, 512), system=system,
messages=[{"role": m["role"], "content": m["content"]} for m in messages])
return "".join(b.text for b in resp.content if b.type == "text").strip()
class OllamaModel:
"""A local model served by Ollama (http://localhost:11434) -- unlike LocalLlama, no
separate binary/GGUF path management: whatever's already been `ollama pull`ed just
works, GPU-accelerated where the model fits in VRAM, transparently CPU-offloaded for
the layers that don't. Uses /api/chat (not /api/generate) since the harness's tool
loop needs real multi-turn system+messages semantics, not a single flat prompt."""
kind = "ollama"
def __init__(self, model, url=None):
import urllib.request
self._urllib = urllib.request
self.model = model
self.url = url or os.environ.get("OLLAMA_URL", "http://localhost:11434/api/chat")
self.label = f"local {model} (ollama)"
def generate(self, system, messages, max_tokens=230, temp=0.3):
import json
payload = {
"model": self.model,
"messages": [{"role": "system", "content": system}] + list(messages),
"stream": False,
"options": {"temperature": temp, "num_predict": max_tokens},
}
body = json.dumps(payload).encode("utf-8")
req = self._urllib.Request(self.url, data=body, headers={"Content-Type": "application/json"})
with self._urllib.urlopen(req, timeout=600) as resp:
return json.loads(resp.read())["message"]["content"].strip()
class HFModel:
"""A local Hugging Face causal LM (torch) -- e.g. the method-baked Qwen-0.5B."""
kind = "hf"
def __init__(self, path, label=None):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
self._torch = torch
self.tok = AutoTokenizer.from_pretrained(path)
self.model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.float32).eval()
self.label = label or f"HF ({os.path.basename(str(path))})"
def generate(self, system, messages, max_tokens=230, temp=0.0):
chat = [{"role": "system", "content": system}] + list(messages)
enc = self.tok.apply_chat_template(chat, add_generation_prompt=True,
return_tensors="pt", return_dict=True)
with self._torch.no_grad():
out = self.model.generate(**enc, max_new_tokens=max_tokens, do_sample=False)
return self.tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True).strip()
class ContrastiveQwenHF:
"""Contrastive-decoding backend: a real strong/weak Qwen2.5-Instruct pair
(default 1.5B strong vs 0.5B weak, same family/tokenizer -- Qwen2.5-0.5B-
Instruct and Qwen2.5-1.5B-Instruct), amplified via
structured_attention.contrastive_next_token_logits (Li et al. 2022:
amplified = strong + alpha*(strong - weak), masked to the strong model's
own plausible tokens). Same idea as LocalLlama/HFModel above -- turn
(system, messages) into a reply string -- so it drops straight into the
backend-selection slot; the method (PREREGISTER/tools/ledger) doesn't
change, only which model proposes each turn's tool call and verdict.
Built from, and reuses, the already-tested amplification primitive from
golden-attention/demo_contrastive_qwen.py -- this class adds a real
KV-cache (past_key_values reused across steps for BOTH models) instead
of that demo's recompute-the-whole-sequence-every-token loop, because
investigate() calls generate() repeatedly on a growing multi-turn
transcript (up to 24 turns) -- without a cache that loop is quadratic in
generated length per call and compounds across turns; with it, each new
token is one incremental forward pass per model, same as any normal
HF .generate() call.
Needs `pip install transformers` plus the (editable, not on PyPI)
structured-attention package -- tries a plain `import structured_attention`
first (already pip-installed editable in this checkout's environment);
if that fails, falls back to METHODLM_STRUCTURED_ATTENTION pointing at a
checkout of https://github.com/gbranaa4-hue/structured-attention, same
optional-path-override pattern as METHODLM_TRITKIT."""
kind = "contrastive"
def __init__(self, weak_name=None, strong_name=None, alpha=None, beta=None):
import torch
try:
from structured_attention import contrastive_next_token_logits
except ImportError:
sa_path = os.environ.get("METHODLM_STRUCTURED_ATTENTION")
if not sa_path:
raise SystemExit(
"contrastive backend needs structured_attention: "
"pip install -e /path/to/structured-attention, or set "
"METHODLM_STRUCTURED_ATTENTION=/path/to/structured-attention")
import sys
sys.path.insert(0, sa_path)
try:
from structured_attention import contrastive_next_token_logits
except ImportError as e:
raise SystemExit(f"contrastive backend: structured_attention still "
f"not importable from {sa_path}: {e}")
try:
from transformers import AutoModelForCausalLM, AutoTokenizer
except ImportError:
raise SystemExit("contrastive backend needs the SDK: pip install transformers")
self._torch = torch
self._amplify = contrastive_next_token_logits
self.weak_name = weak_name or os.environ.get("METHODLM_CD_WEAK", "Qwen/Qwen2.5-0.5B-Instruct")
self.strong_name = strong_name or os.environ.get("METHODLM_CD_STRONG", "Qwen/Qwen2.5-1.5B-Instruct")
self.alpha = alpha if alpha is not None else float(os.environ.get("METHODLM_CD_ALPHA", "1.0"))
self.beta = beta if beta is not None else float(os.environ.get("METHODLM_CD_BETA", "0.1"))
self.device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.bfloat16 if self.device == "cuda" else torch.float32
self.tok = AutoTokenizer.from_pretrained(self.strong_name)
self.weak = AutoModelForCausalLM.from_pretrained(self.weak_name, dtype=dtype).to(self.device).eval()
self.strong = AutoModelForCausalLM.from_pretrained(self.strong_name, dtype=dtype).to(self.device).eval()
eos_cfg = getattr(self.strong.generation_config, "eos_token_id", None)
self.eos_ids = set(eos_cfg) if isinstance(eos_cfg, (list, tuple, set)) else \
({eos_cfg} if eos_cfg is not None else {self.tok.eos_token_id})
self.label = (f"contrastive {self.strong_name.split('/')[-1]} vs "
f"{self.weak_name.split('/')[-1]} (alpha={self.alpha}, {self.device})")
def _sample(self, logits, temp, top_k):
torch = self._torch
if temp is None or temp <= 1e-6:
return logits.argmax(dim=-1, keepdim=True)
logits = logits / temp
finite = torch.isfinite(logits).sum(dim=-1, keepdim=True).item()
k = max(1, min(top_k, finite))
v, _ = torch.topk(logits, k)
logits = logits.masked_fill(logits < v[:, [-1]], float("-inf"))
probs = torch.softmax(logits, dim=-1)
return torch.multinomial(probs, 1)
def generate(self, system, messages, max_tokens=230, temp=0.3, top_k=40):
torch = self._torch
chat = [{"role": "system", "content": system}] + list(messages)
# tokenize=False then a separate tok(...) call, not apply_chat_template's own
# return_tensors="pt" -- that path returned a BatchEncoding instead of a plain
# tensor against this checkout's transformers version (5.12.1); same two-step
# route the already-tested demo_contrastive_qwen.py uses.
text = self.tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
input_ids = self.tok(text, return_tensors="pt").input_ids.to(self.device)
with torch.no_grad():
s_out = self.strong(input_ids, use_cache=True)
w_out = self.weak(input_ids, use_cache=True)
s_past, w_past = s_out.past_key_values, w_out.past_key_values
generated = []
for _ in range(max_tokens):
s_logits = s_out.logits[:, -1, :].float()
w_logits = w_out.logits[:, -1, :].float()
amplified = self._amplify(s_logits, w_logits, alpha=self.alpha, plausibility_beta=self.beta)
next_tok = self._sample(amplified, temp, top_k)
tok_id = int(next_tok.item())
if tok_id in self.eos_ids:
break
generated.append(tok_id)
s_out = self.strong(next_tok, past_key_values=s_past, use_cache=True)
w_out = self.weak(next_tok, past_key_values=w_past, use_cache=True)
s_past, w_past = s_out.past_key_values, w_out.past_key_values
text = self.tok.decode(generated, skip_special_tokens=True).strip()
# Real problem, found running this against investigate()'s multi-turn loop (up to 24
# turns, transcript growing every turn): each generate() call re-prefills the WHOLE
# growing conversation from scratch (no cache persists across separate calls, by
# design -- investigate() calls generate() fresh each turn), and PyTorch's CUDA
# caching allocator doesn't return freed blocks to the driver between calls. On an
# 8GB card this compounded turn over turn -- watched it go from ~1GB free after load
# to ~100MB free by turn ~13 of a single item, 100% GPU util but barely progressing
# (allocator thrashing/fragmentation, not real compute). del the local references and
# empty_cache() explicitly once per turn so the freed blocks actually go back; small,
# fixed per-turn cost, but keeps a multi-turn run from starving itself out by the time
# a panel has many candidate columns.
del s_out, w_out, s_past, w_past, input_ids
if self.device == "cuda":
torch.cuda.empty_cache()
return text
def get_model(name, here):
name = (name or "local").lower()
# The real llama-completion.exe + DLLs + GGUF files are a multi-GB local build, not
# something to duplicate into every checkout that imports methodlm.py -- optional override
# for when they live somewhere other than next to this file (e.g. mesh_rag_server.py imports
# methodlm.py from the canonical repo, but the actual binary/GGUFs only exist in llama_demo).
# Defaults to `here` (unchanged behavior) if unset.
bin_dir = os.environ.get("METHODLM_LOCAL_BIN_DIR", here)
llama = os.path.join(bin_dir, "bin", "llama-completion.exe")
if name in ("local", "qwen", "llama", "qwen3b", "3b"):
return LocalLlama(llama, os.path.join(bin_dir, "qwen3b.gguf"))
if name in ("qwen05b", "qwen0.5b", "0.5b", "small"):
return LocalLlama(llama, os.path.join(bin_dir, "qwen.gguf"))
if name in ("baked", "method-baked", "baked05b"):
# Same "the real weights live in llama_demo, not next to this file" situation as
# the llama.cpp binary/GGUFs above -- reuse the same bin_dir override rather than
# inventing a second env var for the same real problem.
return HFModel(os.path.join(bin_dir, "method_baked_v2"), "method-baked Qwen-0.5B")
# Any already-`ollama pull`ed model, GPU-accelerated with automatic CPU offload for
# what doesn't fit in VRAM -- no separate binary/GGUF path management like LocalLlama.
# "ollama:<tag>" is the general form; a couple of real, currently-installed models get
# short aliases since they're the ones actually used for the harness benchmark.
ollama_aliases = {"qwen7b": "qwen2.5-coder:7b", "qwen2.5-coder-7b": "qwen2.5-coder:7b",
"qwen14b": "qwen2.5-coder:14b", "qwen2.5-coder-14b": "qwen2.5-coder:14b",
# official Microsoft BitNet b1.58 2B-4T -- real ternary {-1,0,+1}
# weights (not the 4-bit-quantized-down-to-"1-bit"-branding kind), pulled
# via hf.co/microsoft/bitnet-b1.58-2B-4T-gguf since the locally-downloaded
# bitnet.gguf used a since-removed llama.cpp quant type (TYPE_IQ4_NL_4_4)
# and can no longer be loaded by any current build.
"bitnet": "hf.co/microsoft/bitnet-b1.58-2B-4T-gguf"}
if name in ollama_aliases:
return OllamaModel(ollama_aliases[name])
if name.startswith("ollama:"):
return OllamaModel(name.split(":", 1)[1])
if name in ("contrastive", "cd", "contrastive-qwen", "cdqwen"):
# real 1.5B-vs-0.5B Qwen2.5-Instruct pair, amplified via
# structured_attention.contrastive_next_token_logits -- see
# ContrastiveQwenHF's docstring above for the full rationale.
return ContrastiveQwenHF()
frontier = {"claude": "claude-opus-4-8", "opus": "claude-opus-4-8",
"sonnet": "claude-sonnet-5", "haiku": "claude-haiku-4-5", "api": "claude-opus-4-8"}
if name in frontier:
return ClaudeAPI(frontier[name])
raise SystemExit(f"unknown model backend '{name}' -- use: qwen3b|qwen05b|baked|qwen7b|qwen14b|ollama:<tag>|contrastive|opus|sonnet|haiku")