rlmesh
Rust SDK for RLMesh model-environment evaluation workflows.
use rlmesh::prelude::*;RLMesh connects a model to an environment over gRPC. This crate is the Rust facade over the transport, wire, and runtime crates. RLMesh uses the same nouns and constructs in every language, following each language’s conventions. Use this crate to serve or drive environments and models from Rust.
The two roles
-
Serve an environment. Implement
Env(orVectorEnv) in Gymnasium shape and host it withEnvServer, or implementEnvFactoryand callEnvFactoryExt::serve. -
Serve a model. Implement
Policy(or write a predict closure), build aModelfrom it, and host it withModel::serve. -
Run a model against an env.
Model::run(orrun) drives episodes on the native loop and returns aRunResult;RunHooksobserve it.Model::session(orsession) returns aSessionto drive by hand.
Use RemoteEnv when you want to step an environment server directly.
Options structs
Optional arguments use options structs with documented defaults
(EnvServerOptions, ServeOptions, EnvFactoryServeOptions).
Build them with ..Default::default(): by project policy appending an
options field is a minor change, and a full struct literal without ..
is unsupported.
Errors
Fallible operations return Result, an alias for Result<T, Error>.
Each Error variant identifies an error class:
Error::class reports the exact class as an ErrorClass, whose
ErrorClass::is_subclass_of tests class inheritance. Display
formats the error message. The two domain failures are
Error::Environment (carrying an ErrorCode) and Error::Model
(a failure your Policy raised, carrying a ModelErrorCode). Both
carry an is_recoverable flag surfaced by Error::is_recoverable,
which is false for every other variant.
Example: serve an environment
use rlmesh::prelude::*;
use rlmesh::spaces::{self, BoxOptions, Discrete, DiscreteOptions};
use rlmesh::{EnvServer, EnvServerOptions};
struct Cartpole {
observation_space: Space,
action_space: Space,
}
impl Env for Cartpole {
fn observation_space(&self) -> Space { self.observation_space.clone() }
fn action_space(&self) -> Space { self.action_space.clone() }
fn reset(&mut self, _seed: Option<i64>, _options: Option<&InfoDict>)
-> rlmesh::Result<(Value, InfoDict)>
{
Ok((self.observation_space.sample()?, InfoDict::new()))
}
fn step(&mut self, _action: Option<Value>)
-> rlmesh::Result<(Value, f64, bool, bool, InfoDict)>
{
Ok((self.observation_space.sample()?, 1.0, false, false, InfoDict::new()))
}
}
let env = Cartpole {
observation_space: spaces::Box::new(-1.0, 1.0, [4], BoxOptions::default())?.into(),
action_space: Discrete::new(2, DiscreteOptions::default())?.into(),
};
let server = EnvServer::new(
env,
EnvServerOptions { address: Some("tcp://127.0.0.1:0".into()), ..Default::default() },
)?;
println!("listening on {}", server.address());
server.serve()Example: serve a model
use rlmesh::prelude::*;
use rlmesh::{Model, ModelOptions, ModelServeOptions};
/// Counts its predicts per episode in the episode's state.
#[derive(Default)]
struct Counter;
impl Policy for Counter {
const CONTEXT: Corners = Corners::PREDICT;
fn predict_with_context(&mut self, _observation: Value, context: &mut PredictContext<'_>)
-> rlmesh::Result<Value>
{
*context.state.get_or_insert_with("predicts", || 0u64)? += 1;
Ok(Value::Int(0))
}
}
let model = Model::new(Counter, ModelOptions::default())?;
model.serve("tcp://127.0.0.1:50051", ModelServeOptions::default())?;
// A closure is a policy too.
let greedy = Model::new(|_observation: Value| Ok(Value::Int(0)), ModelOptions::default())?;Modules
- rlmesh::adaptersPreviewDeclarative adapter specifications, resolution and per-step transforms.
- rlmesh::envPreviewEnv authoring and serving: Gymnasium-shaped environments,
EnvServer,EnvFactoryand the remote clients. - rlmesh::extPreviewAdditional native utilities and interoperability features.
- rlmesh::recorderPreviewPortable evaluation bundles.
- rlmesh::serve_optionsPreviewTransport lifecycle policy shared by the env and model servers.
- rlmesh::spacesPreviewSpaces and their samplers.
- rlmesh::specsPreviewThe read-only contract an env endpoint serves.
- rlmesh::typesPreviewValue and metadata types (also at the crate root), predict contexts, model spec arguments, per-episode state and model load-key declarations.
Structs
- BuildInfoPreviewThe identity of this build.
- CornersPreviewA set of predict corners, with C's
RLMESH_CORNER_*bit values: which corners aPolicywrites (Policy::CORNERS) and which read the context (Policy::CONTEXT). - DescribablePreviewWhat can be described: a model or env factory type, or an instance.
- DescribeJsonOptionsPreviewOptions for
describe_json. - DescribeOptionsPreviewOptions for
describe. - EnvTargetPreviewThe env argument of a run or session: an address, a served
EnvServer, a borrowedRemoteEnv/RemoteVectorEnv, or a borrowed local env, vector env or factory. - EnvironmentErrorPreviewA failure reported by the environment when serving a request.
- EpisodeResultPreviewThe outcome of one episode.
- FrameSourcesPreviewImage roles and the render source reachable through one env or context.
- InvalidArgumentErrorPreviewAn invalid argument value, address or options field (
ValueError), or a failed adapter resolution (AdapterResolutionError, aValueErrorsubclass) whenadapter_resolutionis set. - ModelPreviewA loaded model built from a
Policyor predict closure. - ModelErrorPreviewA failure reported by a model (
ModelException). - ModelOptionsPreviewOptions for
Model::new. - ModelServeOptionsPreviewOptions for
Model::serve, including cancellation and native extras. - ModelTargetPreviewThe model argument of
runandsession: a borrowedModel, a borrowedRemoteModelorRANDOM_SAMPLE. - RandomSamplePreviewThe random baseline: a model that samples the env's action space.
- ReaderPreviewA shared observation reader, resolved once against a connected contract.
- RemoteModelPreviewA served model (policy) to bind envs to.
- RemoteModelOptionsPreviewOptions for connecting to a served model: the same as
RemoteEnvOptionswithoutworkflow_edition. - RenderFnPreviewA borrowed render callable with construction identity.
- RunOptionsPreviewOptions for
runandModel::run. - RunResultPreviewThe result of a run.
- SessionPreviewA model bound to one env.
- SessionOptionsPreviewOptions for
sessionandModel::session. - SessionRunOptionsPreviewThe keywords of
Session.run. - StepEventPreviewOne env step of a run, passed to
RunHooks::on_step. - TelemetryRowPreviewOne aggregated metric series of a run.
- TensorPreviewAn immutable n-dimensional array with shared storage.
- ToDlpackOptionsPreviewOptions for
Tensor::to_dlpack. - ViewPreviewLive display options.
- WarningPreviewOne warning.
- WithContextPreviewA predict closure that reads the context.
Enums
- BuildSourcePreviewWhere a build's cohort came from.
- DTypePreviewAn element dtype, with its wire spelling (
"float32", ...). - DescribeKindPreviewThe target kind used by
describe. - DevicePreviewDevice a tensor's storage lives on, mirroring DLPack's
DLDeviceType. - ErrorPreviewThe error type for every fallible operation in this crate.
- ErrorClassPreviewThe exact class of an
Error, using RLMesh's error-class vocabulary. - ErrorCodePreviewClassifies an
EnvironmentErrorreported by an environment. - ModelErrorCodePreviewClassifies a
ModelErrorreported by a model. - ReadItemPreviewA role or a single-role model input leaf to extract from an observation.
- ViewBackendPreviewWhere to display live frames.
- ViewFormatPreviewHTTP image encoding.
- ViewHoldPreviewHow long a successful session retains its final frame.
- WarningCategoryPreviewA warning category.
Traits
- PolicyPreviewA model's declarations, predict operations and lifecycle hooks.
- RunContextPreviewWhat a run exposes to its hooks.
- RunHooksPreviewObserver callbacks for a run.
Functions
- build_info()PreviewThis build's identity.
- current_workflow_edition()PreviewThe bare
YYYY.MMworkflow edition this build runs at: the value to paste into a declaration, the same on every build of that edition. - describe()Preview
obj's metadata envelope. - describe_json()Preview
obj's canonical envelope string. - predict_seed()PreviewThe per-predict sampling seed: a reproducible mix of the episode's reset seed and the re-plan ordinal within that episode.
- run()PreviewDrive
modelagainstenvto completion. - run_async()PreviewThe async twin of
run. - session()PreviewBind
modeltoenv. - session_async()PreviewThe async twin of
session. - set_warning_handler()PreviewInstall the process-wide warning handler;
Nonerestores the default (stderr, each distinct warning once). - with_context()PreviewWrap a closure that takes the per-episode context as a policy.
Type aliases
- ReadFnPreviewAn observation-bound read callback carried by
StepEvent. - ResultPreviewThe result type used throughout this crate:
Result<T, Error>. - WarningHandlerPreviewA warning handler: returns
Errto fail the operation that warned.
Constants
- DESCRIBE_METADATA_KEYPreviewThe key a serialized describe envelope travels under (
rlmesh.describe.v1). - DESCRIBE_SCHEMA_VERSIONPreviewThe describe envelope's schema version.
- ENV_RESET_OPTIONS_KEYPreviewKey under which an env declares, in its contract metadata, which reserved reset-option keys it wants delivered (a list of strings).
- NO_ADAPTERPreviewDisable adapter resolution.
- RANDOM_SAMPLEPreviewThe random action-sampling baseline.
- VERSIONPreviewThis crate's version, in SemVer (
0.1.0-rc.12).