Surrogate#
This module presents the surrogate_obj class, which is the Python side of the escape::core::surrogate_t entity.
A surrogate is a trained artifact: it wraps a fitted network together with the feature transformations it was trained with, the names of the parameters it predicts and the coordinate template of the data it was trained on. It is the object that is meant to be shared – it can be saved with surrogate_obj.save, sent to a colleague and applied to a different model stack that uses the same parameter names.
A surrogate never trains and never owns a model stack. Training is the job of escape.core.regressor.regressor_obj, which returns a surrogate from train().
See escape.utils.regressor.transformers for the Python side of the feature transformations and escape.utils.regressor.base.nn_model.NNModel for the network contract.
- class escape.core.surrogate.surrogate_obj#
Wrapper class for a trained surrogate.
The object owns a C++ surrogate_t handle. It is normally obtained from regressor_obj.train() or from escape.loads_surrogate(), not constructed directly.
Examples#
>>> surrogate = regressor.train() >>> surrogate.apply(stack, data) >>> values = surrogate.predict(features)
- apply(data: Any, stack: Any | None = None, coord_tol: float = 1e-05)#
Predict the parameters for a data set.
With only data the predicted values are returned as a list, in the order of parameter_names. When stack is given the values are written into the matching parameters of that model stack, matched by name.
Parameters#
- datadatastack_obj or data_obj
The data to predict from
- stackmodelstack_obj, optional
Model stack whose parameters are updated in place
- coord_tolfloat, optional
Tolerance used when comparing the coordinates with the reference data, by default 1e-5
Returns#
- list of float, surrogate_matches, or None
One solution when the network returns one vector or best_only is set. Every candidate, with a probability when stack was given, otherwise.
Nonewhen stack is given and only one solution is returned, because that solution was written into the stack. Several candidates of a stack whose device isgpuare simulated in one batch per model.
Raises#
- RuntimeError
If the coordinates of data differ from the reference data while the input chain reads them
- best_only#
Whether inference returns only the best-matching candidate.
The best candidate is the one whose simulated curve agrees most closely with the measurement. apply with a model stack makes that comparison and reports a probability for every candidate. predict has no forward model, so with this setting it returns the first candidate.
- bind_python_object(observer: Any = None) None#
Bind this object (or observer) as the Python observer of the entity.
- coord_dim#
Number of coordinates that make up one data point.
1for a curveI(x),2for a mapI(x, y),3for a volumeI(x, y, z). The surrogate consumes one intensity per point, so a row of the features holds input_dim values while the same points carryinput_dim * coord_dimcoordinates.
- static from_hub(repo_id, *, revision=None, device='cpu', token=None, cache_dir=None) surrogate_obj#
Download a surrogate from a Hugging Face Hub model repository.
Needs the optional
huggingface_hubpackage (pip install escape[hub]). The files are cached locally, so a second call does not download them again.Parameters#
- repo_idstr
Repository name,
"user/name"- revisionstr, optional
Branch, tag or commit.
Noneis the default branch- devicestr, optional
Device the network is restored on, as in load
- tokenstr, optional
Access token for a private repository
- cache_dirstr, optional
Download cache.
Noneuses the Hugging Face default
Returns#
- surrogate_obj
The restored surrogate
- input_chain#
Transformers applied to the features before the network sees them.
- input_chain_specs#
Raw specs of the input chain, including the fitted state.
Unlike input_chain, which returns live transformer objects, this keeps the fitted arrays exactly as the C++ side stores them, so the chain can be rebuilt without refitting it.
- input_dim#
Number of values the surrogate consumes.
- static load(path, device='cpu') surrogate_obj#
Read a surrogate written by save.
Parameters#
- pathstr
The directory written by save, or the path of its
.jsonsidecar- devicestr, optional
Device the network is restored on, by default
"cpu". The device recorded in the artifact is informational only: a surrogate trained on a GPU opens on a machine without one. Pass"cuda"to restore straight onto a GPU.
Returns#
- surrogate_obj
The restored surrogate, ready for predict and apply
Raises#
- FileNotFoundError
If the artifact is missing
- ValueError
If the artifact is not a surrogate, was written by a newer version of the sidecar layout, or by a newer ESCAPE release, or if device is not available
Examples#
>>> surrogate = esc.surrogate_obj.load("scripts/surrogates/xrr_auto") >>> surrogate.predict(features, bounds) >>> surrogate = esc.surrogate_obj.load( ... "scripts/surrogates/xrr_auto", device="cuda" ... )
- metadata(**extra: Any) Dict[str, Any]#
Collect the metadata of the surrogate into a JSON-serializable dict.
The dictionary holds everything needed to rebuild the surrogate except the network weights and settings, which save writes to
model.safetensorsandconfig.json, and the model stack, which is written toescape_model.xml.gz. Thestackentry isNonewhen the surrogate has no stack. The ESCAPE version that wrote the artifact is recorded so that a newer artifact is rejected instead of being silently misread.Parameters#
- **extra
Additional entries stored verbatim, for example the training constants. The settings of the trainer are stored under
"training", see training.
Returns#
- dict
The metadata
Examples#
>>> meta = surrogate.metadata(iterations=1000) >>> meta["escape_version"] '0.9.8.dev237'
- model#
The network the surrogate wraps.
The surrogate owns its network: regressor_obj.train() hands every surrogate a copy, so training again does not change it. The returned wrapper reaches the Python network, so its state – for example
model.model.device– is accessible.
- name#
Name of the entity.
- nsamples#
Number of training samples the surrogate was built from.
- ntests#
Number of test samples the surrogate was built from.
- output_chain#
Transformers inverted after the network produced its output.
- output_chain_specs#
Raw specs of the output chain, including the fitted state.
- output_dim#
Number of values the surrogate produces.
- parameter_bounds#
Unscaled (min, max) bounds of the predicted parameters.
- parameter_names#
Names of the parameters the surrogate predicts, in output order.
- parameters#
List of entity parameters.
- predict(X: NDArray, bounds: Any = None, coordinates: Any = None)#
Predict the unscaled parameter values for the given features.
Parameters#
- XNDArray
Features, shape (nsamples, input_dim)
- boundsNDArray, optional
Physical prior boxes for a surrogate trained with a prior sampler (prior_boxes):
[lo_1..lo_P, hi_1..hi_P]per row, shape (nsamples, 2 * output_dim) or (1, 2 * output_dim), where a single row is used for every sample. The boxes are clipped to the global training box.Nonemeans the global box. The predictions are clamped to their box. A surrogate without prior boxes rejects explicit bounds.- coordinatesNDArray, optional
Coordinates of every curve, shape (nsamples, input_dim * coord_dim), or one row shared by all of them.
Noneuses the reference data. A surrogate that reads_coordinates needs the grid of each curve here.
Returns#
- double_array_obj or surrogate_matches
One solution per sample, shape (nsamples, output_dim), when the network returns one vector or best_only is set. Otherwise every candidate, with probability
Nonebecause comparing them needs the forward model used by apply.
- prior_boxes#
Whether the network takes a prior box per curve.
True for a surrogate trained with a prior sampler such as PriorBoxes. apply with a model stack reads the box from the current
min/maxof the stack parameters.
- push_to_hub(repo_id, *, commit_message='Upload ESCAPE surrogate', private=False, token=None, **extra: Any) str#
Upload the surrogate to a Hugging Face Hub model repository.
The directory written by save is uploaded as it is. The repository is created when it does not exist. Needs the optional
huggingface_hubpackage (pip install escape[hub]).Parameters#
- repo_idstr
Repository name,
"user/name"- commit_messagestr, optional
Message of the upload commit
- privatebool, optional
Create the repository as private, by default False
- tokenstr, optional
Access token.
Noneuses the token ofhuggingface-cli login- **extra
Additional metadata stored in the sidecar, as in save
Returns#
- str
The URL of the repository
- reads_coordinates#
Whether the network reads the coordinates of every curve after its intensities.
True for a surrogate trained with a coordinate sampler such as VariableCoordinates. It accepts data on any grid with input_dim points.
- reference_data#
The coordinate template the surrogate was trained on.
- refine#
Whether apply predicts again inside a narrower prior box.
Equivalent to refine_passes > 1. The first pass is ranked by the simulated curve. Each later pass keeps up to four candidates that differ from every better one, gives each a box of half the width of the box that produced it, and predicts again. Every pass is ranked together. This uses the prior box as a network input, so it applies to a surrogate with prior_boxes.
- refine_pass_parameters()#
Best candidate after each pass of the last refined apply.
Shape
(refine_passes, output_dim). Row 0 is the best candidate of the first pass. Empty when the last apply did not refine.
- refine_passes#
How many prediction passes apply runs.
1returns the network’s own candidates.2is the usual second pass. Each further pass halves the box again around the distinct candidates and predicts once more. The value is at least 1. Setting it above 1 turns refine on; setting it to 1 turns refine off.
- save(path, **extra: Any) str#
Write the surrogate to a directory.
The artifact is a directory laid out like a Hugging Face model:
config.json the network settings and layout model.safetensors the network weights escape_surrogate.json everything else, plain JSON escape_model.xml.gz the model stack, gzipped XML README.md a model card
A registered network with its own serialization is written to
model.bininstead of the first two files. The stack file is written only when the surrogate carries a model stack, which is the case for a surrogate produced by regressor_obj.train().Parameters#
- pathstr
Target directory. It is created if it does not exist; its last component names the model card.
- **extra
Additional metadata stored in the sidecar, for example the training constants
Returns#
- str
The path of the written sidecar
Examples#
>>> surrogate.save("scripts/surrogates/xrr", iterations=1000) '.../scripts/surrogates/xrr/escape_surrogate.json'
- score#
Goodness of fit recorded at training time (higher is better).
- segment_input_chains#
Per-segment feature chains. Empty when one chain covers every segment.
- settings#
List of entity settings.
- show(stack: Any | None = None, model_configs: Any | None = None, config: Any | None = None, **kwargs) Any#
Show the surrogate in a widget with a single Test button.
Test randomizes the parameters the surrogate predicts, generates data from the model stack, predicts the parameters back and shows the truth against the prediction.
- Args:
- stack: Model stack to generate data from. Defaults to the stack the
surrogate was trained on, which save/load preserve.
- model_configs: Model configurations to display, a single
ModelConfig instance or a list of ModelConfig instances
config: Layout configuration, a LayoutConfig instance **kwargs: Additional keyword arguments
- Returns:
SurrogateObjectLayout instance
- stack#
The model stack the surrogate was trained on, or None.
regressor_obj.train() attaches a copy of the stack it sampled from, so applying the surrogate to it leaves the training stack untouched, and save writes it next to the network, so both a freshly trained and a restored surrogate can generate data and write the prediction back without the caller passing anything. A surrogate assembled with escape.surrogate without a stack returns None.
- training#
Settings of the trainer that produced the surrogate, or None.
regressor_obj.train() records the samplers, the noise model and the prior widths (see regressor_obj.training_metadata); save and load preserve them. The widget uses them to test the surrogate under the conditions it was trained for.
- escape.core.surrogate.surrogate(model: Any, input_chain: Sequence[Any] | None = None, output_chain: Sequence[Any] | None = None, parameter_names: Sequence[str] | None = None, parameter_bounds: Sequence[Sequence[float]] | None = None, reference_data: Any | None = None, score: float = 0.0, nsamples: int = 0, ntests: int = 0, prior_boxes: bool = False, reads_coordinates: bool = False) surrogate_obj#
Rebuild a surrogate from its parts.
This is the counterpart of regressor_obj.train(): it assembles a surrogate from an already fitted network and the metadata the network was trained with, without training anything. It is what a loader uses to restore a surrogate that was saved earlier.
Parameters#
- modelnn_model_obj
The fitted network. It must already be built and fitted, for example by calling nn_model_obj.loads on a saved blob.
- input_chainsequence, optional
Transformers applied to the features before the network sees them, by default empty
- output_chainsequence, optional
Transformers inverted after the network produced its output, by default empty
- parameter_namessequence of str, optional
Names of the predicted parameters, in output order, by default empty
- parameter_boundssequence of (float, float), optional
Unscaled (min, max) of each predicted parameter, by default empty
- reference_datadata_obj, datastack_obj or list of data_obj, optional
The coordinate template the network was trained on, by default empty
- scorefloat, optional
Goodness of fit recorded at training time, by default 0.0
- nsamplesint, optional
Number of training samples, by default 0
- ntestsint, optional
Number of test samples, by default 0
- prior_boxesbool, optional
Whether the network takes a prior box per curve, with targets in
[-1, 1]within the box, by defaultFalse- reads_coordinatesbool, optional
Whether the network reads the coordinates of every curve after its intensities, by default
False
Returns#
- surrogate_obj
The assembled surrogate
Examples#
>>> net = esc.nn_model(SurrogateNet("auto")) >>> net.loads(blob) >>> surrogate = esc.surrogate(net, input_chain=[LogScaler(), MinMaxScaler()], ... parameter_names=names, prior_boxes=True)
- escape.core.surrogate.register_network(cls: Any) Any#
Make a network class loadable by surrogate_obj.load.
The class is registered under its stable
class_name(), which is what the saved artifact records. It must accept adevicekeyword argument and restore its weights withloads. Returns the class, so it can be used as a decorator.Examples#
>>> @esc.register_network ... class MyNet(NNModel): ... ...