debajyotidasgupta's picture
MindFlow reproduction bundle
448d6a5 verified
Raw
History Blame Contribute Delete
6.17 kB
"""LLM client for MindFlow reproduction.
Backbone-substitution: the paper does not state its backbone LLM; per the ICML
challenge's backend-substitution clause we use open models served via Hugging
Face Inference Providers (hosted inference). All calls go through a disk cache so
runs are cheap, reproducible and resumable.
"""
from __future__ import annotations
import os, json, time, hashlib, threading, re
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor, as_completed
from huggingface_hub import InferenceClient
CACHE_DIR = os.environ.get("MINDFLOW_CACHE", os.path.join(os.path.dirname(__file__), "..", "..", "llm_cache"))
os.makedirs(CACHE_DIR, exist_ok=True)
# Inference backend. Primary path: a self-hosted vLLM OpenAI-compatible endpoint on a
# Vast.ai GPU (HF Jobs AND HF Inference Providers both return 402 / no credit).
# Set MINDFLOW_LLM_BASE=http://<ip>:<port>/v1 to route all calls to the served model.
LLM_BASE = os.environ.get("MINDFLOW_LLM_BASE", "").strip() or None
SERVED_MODEL = os.environ.get("MINDFLOW_LLM_MODEL", "qwen")
# Logical model roster (used for cache separation + emulated judge panel). When
# LLM_BASE is set every logical name maps to the single SERVED_MODEL; a 3-judge
# panel is emulated by distinct seeds + order randomization + judge temperature>0.
GEN_MODEL = os.environ.get("MINDFLOW_GEN_MODEL", "Qwen/Qwen2.5-72B-Instruct")
JUDGE_MODELS = os.environ.get(
"MINDFLOW_JUDGE_MODELS",
"Qwen/Qwen2.5-72B-Instruct,meta-llama/Llama-3.3-70B-Instruct,Qwen/Qwen2.5-32B-Instruct",
).split(",")
_stats_lock = threading.Lock()
STATS = {"calls": 0, "cache_hits": 0, "prompt_tokens": 0, "completion_tokens": 0, "errors": 0}
def _key(model, messages, temperature, max_tokens, seed):
h = hashlib.sha256(
json.dumps([model, messages, temperature, max_tokens, seed], sort_keys=True).encode()
).hexdigest()
return h
def _cache_path(k):
return os.path.join(CACHE_DIR, k + ".json")
_clients = {}
_clients_lock = threading.Lock()
def _client(model):
key = "__served__" if LLM_BASE else model
with _clients_lock:
if key not in _clients:
if LLM_BASE:
_clients[key] = InferenceClient(base_url=LLM_BASE, api_key="EMPTY", timeout=180)
else:
_clients[key] = InferenceClient(model=model, token=os.environ.get("HF_TOKEN") or None, timeout=180)
return _clients[key]
def chat(messages, model=None, temperature=0.7, max_tokens=1200, seed=None, retries=4):
"""Single chat completion with disk cache + retry. Returns text."""
model = model or GEN_MODEL
# cache key keeps the *logical* model name (so emulated judges cache separately)
k = _key(model, messages, temperature, max_tokens, seed)
p = _cache_path(k)
if os.path.exists(p):
with _stats_lock:
STATS["cache_hits"] += 1
return json.load(open(p))["content"]
api_model = SERVED_MODEL if LLM_BASE else model
last = None
for attempt in range(retries):
try:
cli = _client(model)
kwargs = dict(model=api_model, messages=messages, temperature=temperature, max_tokens=max_tokens)
if seed is not None:
kwargs["seed"] = seed
r = cli.chat_completion(**kwargs)
content = r.choices[0].message.content or ""
usage = getattr(r, "usage", None)
with _stats_lock:
STATS["calls"] += 1
if usage:
STATS["prompt_tokens"] += getattr(usage, "prompt_tokens", 0) or 0
STATS["completion_tokens"] += getattr(usage, "completion_tokens", 0) or 0
json.dump({"model": model, "content": content}, open(p, "w"))
return content
except Exception as e: # noqa
last = e
with _stats_lock:
STATS["errors"] += 1
time.sleep(min(2 ** attempt, 20) + 0.5)
raise RuntimeError(f"chat failed for {model}: {last}")
def chat_json(messages, model=None, temperature=0.5, max_tokens=1200, seed=None, retries=4):
"""Chat that must return JSON. Retries with a repair nudge; returns dict."""
out = chat(messages, model=model, temperature=temperature, max_tokens=max_tokens, seed=seed, retries=retries)
obj = extract_json(out)
if obj is None:
# one repair attempt (non-cached temp bump)
rep = messages + [
{"role": "assistant", "content": out[:500]},
{"role": "user", "content": "Your reply was not valid JSON. Reply with ONLY the JSON object, no prose, no code fences."},
]
out = chat(rep, model=model, temperature=0.2, max_tokens=max_tokens, seed=(seed or 0) + 1)
obj = extract_json(out)
return obj if obj is not None else {}
def extract_json(text):
if not text:
return None
text = text.strip()
# strip code fences
m = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL)
if m:
text = m.group(1).strip()
# find first balanced { ... }
start = text.find("{")
if start == -1:
return None
depth = 0
for i in range(start, len(text)):
c = text[i]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
cand = text[start : i + 1]
try:
return json.loads(cand)
except Exception:
try:
return json.loads(cand.replace("\n", " "))
except Exception:
return None
return None
def parallel_map(fn, items, workers=8):
"""Run fn over items concurrently, preserving order."""
results = [None] * len(items)
with ThreadPoolExecutor(max_workers=workers) as ex:
futs = {ex.submit(fn, it): i for i, it in enumerate(items)}
for f in as_completed(futs):
results[futs[f]] = f.result()
return results
def reset_stats():
with _stats_lock:
for k in STATS:
STATS[k] = 0
def get_stats():
with _stats_lock:
return dict(STATS)