Generic ask/tell GP surrogate engine: botorch fit / predict / ask
with budget-constrained pickers, plus an MCP server scaffold.
The engine sees only numbers. Every output axis is maximized; axis 0 is the primary objective. Clients transform on their side (negate to minimize, log to tame dynamic range) and keep their units to themselves. It is the ask half of ask/tell: no optimization loop, no job submission, no history storage -- the client owns those and hands the engine the full history on every call.
Needs Python >= 3.11 (botorch's floor). Check pip --version — it names
the interpreter it belongs to; an older one fails misleadingly with
No matching distribution found for botorch>=0.18.
pip install "git+https://github.com/oksuzian/surrokit" # engine
pip install "surrokit[mcp] @ git+https://github.com/oksuzian/surrokit" # + MCP scaffold
pip install --no-deps "git+https://github.com/oksuzian/surrokit" # env already has torch/botorchNot on PyPI yet, so plain pip install surrokit does not work. From a
checkout: pip install -e ".[mcp]".
On Mu2e/FNAL machines the interpreter you want is ana 2.8.0 (Python
3.12, botorch 0.18.1); the login shell's python/pip are 3.9 and
cannot install botorch at all:
source /cvmfs/mu2e.opensciencegrid.org/setupmu2e-art.sh
pyenv ana 2.8.0 # always name the version -- bare `pyenv ana` is 2.7.0
python -m pip install --no-deps "git+https://github.com/oksuzian/surrokit"In a shell that also launches Mu2e jobs, use the interpreter path
(/cvmfs/mu2e.opensciencegrid.org/env/ana/2.8.0/bin/python) instead of
activating: pyenv's python/pip wrappers re-prepend the env's
site-packages and libs into every child process and shadow muse's ROOT.
pip install ships the package only, so the example comes from a clone
(it runs straight from it, installed or not):
git clone https://github.com/oksuzian/surrokit && cd surrokit
python examples/stopping_target.py # the whole library, one run
python examples/stopping_target.py --plot # + the GP map as a PNGOne example, three acts on real data: 90 Geant4-simulated Mu2e stopping-target geometries (10 knobs), maximizing signal-to-background while holding beam-flash damage under the deployed target's budget.
fit/predict— the GP over the measured designs.ask— what to simulate next. The best measured design is over budget;constrained_maxproposes the highest-signal geometries the GP believes stay under it.- MCP — the same two problems served over stdio (the script re-runs
itself with
--serve) and called back by a client.suggestreturns the picks act 2 computed in-process, byte for byte.
Problem(bounds_lo, bounds_hi, int_dims=(), noise=None, constraint=None, features=None)— the search box.noise= ABSOLUTE per-axis sigma, which pins a fixed-noise GP; strongly recommended when you have replicate measurements, since a free-noise fit can erase a real optimum.features= an optional function of the knobs whose outputs the GP gets as extra inputs; see "Tell the GP what you know" below.Constraint(axis, min, k_sigma=1.0)— lower bound on one output axis, feasible whenmean - k_sigma*sigma >= min. Honored ONLY by theconstrained_maxpicker;fit,predict, and the other pickers ignore it. A GP-belief margin, not a measured one -- picks can still land over.fit(problem, X, Y, Ysigma=None) -> model;predict(model, X) -> (mean, sigma).Ysigma(optional, the shape ofY, every entry finite and > 0) is one ABSOLUTE sigma per row and output axis: it replacesnoise's broadcast, so a point measured more precisely counts for more. As withnoise, GPyTorch raises a variance below 1e-6 of the output's variance to that floor, with a warning: sigmas below about 1/1000 of the output's spread all weigh the same.fitfits the GP hyperparameters from 5 starts (botorch'spick_best_of_all_attempts): the default start, then 4 drawn from the hyperparameter priors; the best MAP objective wins. The draws use a fixed seed in a forked RNG, sofitis deterministic and leaves torch's global RNG untouched. Each fit logs, at INFO, the noise and the lengthscales per output and input, in normalized units (each input's box spans 1): a lengthscale well above 1 means the GP treats that output as flat along that input.ask(problem, X, Y, q=5, picker="hybrid", seed=0, pending=None, min_spacing=0.10, pool=16384, hv_frac=0.6, Ysigma=None) -> list[list]— stateless: refits per call. Pickers:qnehvi | qlnei | qnparego | hybrid | constrained_max.seedis used verbatim in every RNG stream (derive per-round seeds on your side). Fewer than 2 rows falls back to a Sobol draw.pendingrows are conditioned on but never returned.askseeds torch's GLOBAL RNG (torch.manual_seed) for stateless determinism; reseed after the call if you rely on ambient torch RNG state.hybridmixesqnehviandqnparego: for q > 1,round(hv_frac*q)picks come fromqnehviand the rest fromqnparego; for q = 1 the one pick comes fromqnehviwith probabilityhv_frac, elseqnparego, decided byseedalone. Each acquisition is optimized from 20 restarts over 1024 raw samples (Ax's defaults).- Errors:
InfeasibleError,NotEnoughData,ValueError, and botorch'sModelFittingErrorwhen every fit start fails — the library never prints (logger"surrokit"), reads the environment, or exits.
Maximize objective f, keep metric g <= budget — feed the engine
-log10(g) and constrain it above -log10(budget):
import math
from surrokit import Problem, Constraint, ask
prob = Problem(bounds_lo=(0, 0), bounds_hi=(1, 10),
constraint=Constraint(axis=1, min=-math.log10(budget)))
Y = [[f_i, -math.log10(g_i)] for f_i, g_i in observations]
picks = ask(prob, X, Y, q=5, picker="constrained_max", seed=run_seed)When the response depends on a quantity you can compute from the knobs
(a volume, a mass, a ratio), pass it as features. The GP gets it as an
extra input and does not have to learn it from the rows. The pickers
still search, and return, the knobs alone.
def volume(X): # (..., n, d) -> (..., n, k)
return (X[..., 0] ** 2 * X[..., 1]).unsqueeze(-1)
prob = Problem(bounds_lo=(1, 1), bounds_hi=(5, 20), features=volume)- Torch in, torch out, and differentiable: the acquisition optimizer takes gradients through it. Flat regions (a clipped value) are fine.
- It must keep leading batch dimensions: index with
X[..., i], neverX[:, i]. - Knobs arrive in your units. Each feature is scaled by its range over a fixed sample of the knob box, so the scaling does not depend on the history.
fitraisesValueErrorfor a wrong output shape, a non-finite value inside the box, or a feature that is constant over the box.- A plain function works in-process.
features=None(the default) leaves the fit exactly as it was.
make_server(adapter) turns any two-method adapter into an MCP server
with the tools list_problems, predict, suggest, stats, refit
— callable by Claude Code, Claude Desktop, or any MCP client:
# my_server.py
from surrokit import Problem
from surrokit.mcp_scaffold import make_server
class MyAdapter:
def problems(self):
# name -> search space
return {"toy": Problem(bounds_lo=(0.0, 0.0), bounds_hi=(1.0, 10.0))}
def history(self, name):
# observed rows: X (n, d), Y (n, m) — every axis maximized —
# plus free-form metadata served by stats()
X = [[0.2, 3.0], [0.8, 7.0]]
Y = [[1.1, 2.5], [1.4, 2.1]]
return X, Y, {"objectives": ["f", "-log10(g)"]}
server = make_server(MyAdapter(), name="my-surrogate")
if __name__ == "__main__":
server.run("stdio")Register it with a client (e.g. a Claude Code .mcp.json):
{
"mcpServers": {
"my-surrogate": {
"command": "python",
"args": ["/path/to/my_server.py"]
}
}
}Then ask it to "list the problems", "predict at x=[0.5, 5]", or "suggest
5 points with picker qlnei, seed 7". Everything is pure computation over
the history your adapter serves; nothing is submitted or written.
make_server also takes middleware=, forwarded to MCPServer.
The adapter's problems() dict IS the problem set: nothing outside it
is servable, and the engine never sees your names, units, or files --
only the Problem and the X, Y your history() returns. list_problems
reports per problem dims, bounds_lo/hi, int_dims, axes, n_rows,
and constrained (a Constraint is attached -- meaningful only under
constrained_max).
If your adapter also defines suggest(name, q, picker, round_idx, pending), the suggest tool delegates to it instead of the generic
stateless ask -- use this when MCP picks must match your production
loop's vocabulary, history policy, and seed derivation exactly.
history(name) may return a fourth item, one sigma per row and output
axis (or None): every fit the server makes (behind predict, refit
and the generic suggest) uses it as Ysigma. The server reuses a
fitted model while the row count is unchanged, so call refit after
changing a row or its sigma in place. The returned server runs any
transport the mcp SDK supports:
server.run("stdio") or server.run("streamable-http") for a visible
process with a URL.
examples/stopping_target.py --serve is one of these, and the example's
third act is a client for it. Point that client at somebody else's
server with --server-cmd; add --plot and it Sobol-sweeps the box
through predict and draws the GP's trade-off map.
Mu2eBO is the real-world adapter —
surrogate/adapter.py + surrogate/mcp_server.py serve its Bayesian
optimization leaderboards (7 detector-geometry search spaces) this way.