debajyotidasgupta's picture
MindFlow reproduction bundle
448d6a5 verified
Raw
History Blame Contribute Delete
5.99 kB
"""Mind supernet + topic-aware controller (Sec 4.2 / 4.3).
Mind supernet M (Def 4.3): layer-wise operator inclusion probabilities
pi_l(O) = p(O | Pi_<l, x_t) in (0,1).
Controller Q_phi (Eq. 10) samples a flow G layer by layer; the joint over flows
is the product of per-operator Bernoullis (Eq. 7). Optimised by REINFORCE
(Eq. 13). We parameterise pi_l(O | x_t) = sigmoid(w_{l,O} . e(x_t) + b_{l,O})
with e(x_t) a frozen sentence embedding of the topic -> genuinely topic-aware,
small and optimisable.
"""
from __future__ import annotations
import threading
import numpy as np
import torch
import torch.nn as nn
from functools import lru_cache
from .operators import REFINE_OPS, EXIT, OPERATORS, OP_COST
CTRL_OPS = REFINE_OPS + [EXIT] # operators the controller decides per layer
OP_INDEX = {o: i for i, o in enumerate(CTRL_OPS)}
# Hard cap on the number of refinement operators in a flow. Without it, REINFORCE
# drives inclusion probabilities up and flows grow unbounded (runtime + cost blow up).
# The paper's flows (Fig. 3) are ~3-5 operators; we cap total refine ops accordingly.
MAX_FLOW_OPS = 5
MAX_OPS_PER_LAYER = 2
_embedder = None
_embedder_lock = threading.Lock()
_encode_lock = threading.Lock()
def get_embedder():
global _embedder
if _embedder is None:
with _embedder_lock: # thread-safe single load (avoid concurrent init segfault)
if _embedder is None:
from sentence_transformers import SentenceTransformer
_embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
return _embedder
def encode(texts, normalize=True):
"""Single choke-point for all SentenceTransformer encodes. Serialized with a
lock because concurrent torch forwards from worker threads segfault on macOS."""
with _encode_lock:
return get_embedder().encode(list(texts), normalize_embeddings=normalize)
@lru_cache(maxsize=4096)
def embed_topic(topic: str):
e = encode([topic])[0]
return tuple(float(x) for x in e)
class MindSupernet(nn.Module):
def __init__(self, emb_dim=384, n_layers=3, init_bias=-0.4, seed=0):
super().__init__()
self.n_layers = n_layers
self.n_ops = len(CTRL_OPS)
g = torch.Generator().manual_seed(seed)
# topic-conditioned linear head per (layer, op)
self.W = nn.Parameter(0.02 * torch.randn(n_layers, self.n_ops, emb_dim, generator=g))
# bias: modest prior to include refine ops, discourage early Exit
b = torch.full((n_layers, self.n_ops), float(init_bias))
b[:, OP_INDEX[EXIT]] = -1.0
self.b = nn.Parameter(b)
def logits(self, e_x: torch.Tensor) -> torch.Tensor:
# e_x: [emb_dim] -> [n_layers, n_ops]
return torch.einsum("lod,d->lo", self.W, e_x) + self.b
def probs(self, topic: str) -> torch.Tensor:
e = torch.tensor(embed_topic(topic), dtype=torch.float32)
return torch.sigmoid(self.logits(e)) # [L, n_ops] in (0,1)
# ---- stochastic sampling (training) -------------------------------------
def sample_flow(self, topic, rng: np.random.Generator, temperature=1.0):
"""Sample a thinking flow. Returns (op_sequence, layers) where op_sequence is
the linear execution order of refinement operators (Generate is prepended by
the executor); layers is list of per-layer chosen CTRL_OPS subsets."""
p = self.probs(topic).detach().numpy()
if temperature != 1.0:
# temperature on the odds
p = 1.0 / (1.0 + ((1 - p) / np.clip(p, 1e-6, 1)) ** (1.0 / temperature))
layers, seq = [], []
for l in range(self.n_layers):
chosen = [o for o in CTRL_OPS if rng.random() < p[l, OP_INDEX[o]]]
layers.append(chosen) # full Bernoulli sample -> used by log_prob (Eq. 7)
exit_here = EXIT in chosen
# execution order: top ops by prob, capped per-layer and by total flow length
refine = sorted([o for o in chosen if o != EXIT], key=lambda o: -p[l, OP_INDEX[o]])
refine = refine[:MAX_OPS_PER_LAYER][: max(0, MAX_FLOW_OPS - len(seq))]
seq.extend(refine)
if exit_here or len(seq) >= MAX_FLOW_OPS:
break
return seq, layers
# ---- deterministic top-p rollout (deployment / eval) --------------------
def rollout_flow(self, topic, threshold=0.6):
p = self.probs(topic).detach().numpy()
layers, seq = [], []
for l in range(self.n_layers):
order = sorted(CTRL_OPS, key=lambda o: -p[l, OP_INDEX[o]])
cum, chosen = 0.0, []
for o in order:
chosen.append(o)
cum += p[l, OP_INDEX[o]]
if cum >= threshold:
break
layers.append(chosen)
exit_here = EXIT in chosen
refine = [o for o in chosen if o != EXIT][:MAX_OPS_PER_LAYER][: max(0, MAX_FLOW_OPS - len(seq))]
seq.extend(refine)
if exit_here or len(seq) >= MAX_FLOW_OPS:
break
return seq, layers
# ---- log Q_phi(G | x) (Eq. 7 / 10) --------------------------------------
def log_prob(self, topic, layers) -> torch.Tensor:
e = torch.tensor(embed_topic(topic), dtype=torch.float32)
logit = self.logits(e) # [L, n_ops]
logp = torch.tensor(0.0)
used = len(layers)
for l in range(used):
chosen = set(layers[l])
for o in CTRL_OPS:
pi = torch.sigmoid(logit[l, OP_INDEX[o]])
pi = torch.clamp(pi, 1e-6, 1 - 1e-6)
if o in chosen:
logp = logp + torch.log(pi)
else:
logp = logp + torch.log(1 - pi)
return logp
def flow_cost(self, seq):
return float(sum(OP_COST.get(o, 1.0) for o in seq)) + 1.0 # +1 for Generate
def flow_signature(seq):
return "Generate -> " + (" -> ".join(seq) if seq else "(exit)")