runtime_session.h#
Sessions, including subgraphs, read directly usable initializer storage from
the immutable source graph. No ownership mode is required. The graph and its
backing buffers must outlive the session and its initializer views, including
when supplied through SetInitializers.
Host initializers are not copied into the execution allocator for CPU execution
(kCPU or the default kUndefined device). Raw storage and native float,
double, int32, int64 and uint64 fields can be borrowed; representations requiring
decoding, including strings, still use normal tensor conversion. This host
borrowing rule does not implement transfers to another device.
Initializer views do not own the source model. C++ callers keep it alive through all such views, including returned or retained results. Ownerless externally borrowed buffers cannot be retained. Python bindings retain the source model when exporting initializer views.
Kernel preparation#
Construction fixes a non-null ValueStore owner, creating a private store
unless RuntimeSessionOptions::value_store explicitly supplies one.
Preparation separates declaration from execution:
DeclarePreparations(context)resolves and tunes the planned kernels and records their immutable work without seeding or reading initializer payloads. AKernelPreparationcontains its metadata ininfo, aKernelPreparationInfodescribing source inputs, a representation, output slots and dependency indices, alongside a memory estimator and an execution callable.ExecutePreparations(context, memory_limit)executes ready declarations whose dependencies and source tensors are available and whose estimated peak fits the budget. It does not load or seed missing initializers. The overload takingchanged_sourcesschedules only their indexed consumers, newly satisfied dependencies and work unblocked by a larger budget. Source hints never bypass availability, intermediate-provenance or tuning validation.preparation_readiness_checks()reports candidate inspections.Prepare(context)seeds available initializers and executes ready work without running inference or requiring example feeds.pending_preparations()exposes metadata-only diagnostics for deferred work, including unavailable sources and budget-limited work. Diagnostics copy the declaration’sinfoand add the session index and current tuning status. They contain no execution callables, remain readable after session destruction, and do not force deferred branches to run.EstimatePreparationMemory(context, index)estimates a declaration by its diagnostic index without exporting its session-borrowing callbacks.awaits_runtime_tuningdistinguishes work whose input type is not yet known well enough to resolve its tuning profile.
Kernel declaration callables borrow their kernel/model state and remain session-owned. Session entry points enforce dependency, readiness, and admission checks before execution. Unknown input types defer tuning rather than selecting an undefined-type profile. Resolution uses the declaration-time registry snapshot once the actual input becomes available, before packing or the affected inference consumer executes. A later registry update does not change that snapshot.
An explicit preparation entry point permits loading and packing before the first real input arrives:
RuntimeSession session(model); // model and its buffers remain alive
RuntimeContext context;
session.Prepare(context); // no guessed input tensor or inference
context.Set("x", real_input);
session.Run(context);
Existing callers can retain lazy initialization:
RuntimeSession session(model);
RuntimeContext context;
context.Set("x", real_input);
session.Run(context); // initializes and prepares before replay
context.Put("x", next_input, RuntimeEventKind::kInput);
session.Run(context); // reuses resolved kernels and packed values
Immutability and availability are separate facts. An external initializer can
be known immutable before its bytes are loaded; this permits declaration, not
early payload access. Gemm declares packing for a constant B initializer.
An initializer that is also a graph input, or a value supplied by the caller
before initialization, remains overridable and is not statically prepared.
Missing dynamic inputs are checked by inference, not invented by preparation.
Initializer overrides must be supplied before kernel initialization, whether
initialization starts through declaration, explicit preparation, or the first
inference. Initializers exposed as graph inputs remain mutable throughout.
Each entry point installs the session’s store into the RuntimeContext; it
never adopts a context’s previous store. If, Loop, Scan,
SequenceMap, and model-local function sessions inherit the parent’s owner.
Their sessions remain deferred until their branch, iteration, or function call
is entered: preparing the root does not execute control flow, bind fictitious
function arguments, or eagerly prepare every possible branch. Immutable
captures and immutable function arguments propagate when those child sessions
are created.
Ready publication occurs only after a preparation succeeds. A preparation failure is sticky: subsequent preparation or execution rethrows it rather than retrying partially completed work. Calls on one session/context, and calls on sessions sharing a store, must be serialized.
Declarations that depend on a node-produced value remain deferred during explicit preparation. Inference executes their producers first, then drains ready work and enforces readiness immediately before each affected consumer. A same-named intermediate already present in the context is not evidence that its producer has executed. Missing sources or incomplete dependencies prevent the consumer from running. Once all declarations are complete, warm replay does not redispatch preparation work.
A kernel binds a store-specific ValueStore::Slot with a stable integer
index during initialization. After publication, BindForRead validates it
once and returns a store-pointer/index binding. Gemm retains this binding
for direct warm reads: ordinary ExecutionPlan replay does not wait on
readiness, acquire a preparation mutex, or repeat a string-keyed lookup.
Repeated nodes using the same immutable matrix and packing representation
share the published preparation rather than repacking it.
RuntimeSession::prepared_bytes reports live buffer sizes in the static
store’s allocators, including allocated but unpublished values and preparations
created by nested sessions. It excludes retained free capacity, execution/I/O
arenas. Explicitly sharing a store
between otherwise independent sessions also shares this accounting: it is
not a per-session partition. All sessions sharing one store must serialize
their runs. Contexts may keep the owner alive after a session is destroyed.
value_store() returns a reference, available even before the first run.
Use value_store_owner() when passing shared ownership to options or a
nested session. Const session/context access returns const ValueStore&
or std::shared_ptr<const ValueStore>; initialization-time mutation and
sharing a mutable owner require a non-const session/context.
The store does not itself schedule asynchronous loading, track generations, or evict prepared values. Ordinary preparation calls are synchronous.
Owning external-weight loading#
runtime_session_loader.h provides LoadedRuntimeSession for orchestrated
loading. Unlike a borrowing RuntimeSession, this wrapper owns the parsed
ModelProto and destroys its session before releasing the model. Keep the
wrapper alive while using its session or any initializer-backed result views.
Its model() accessor is const; loaded source payloads remain immutable.
#include "onnx_core/runtime/runtime_session_loader.h"
RuntimeContext context;
RuntimeLoadOptions loading;
loading.overlap_preparation = true; // false selects serial read/prepare
loading.memory_limit = 256 * 1024 * 1024;
LoadedRuntimeSession loaded("model.onnx", context, {}, loading);
context.Set("x", real_input); // only after loading/preparation
loaded.session().Run(context);
The loader parses metadata and finalizes external attribute/function and
nested-graph payloads before kernel resolution. Root-session preparation is
then declared without touching unavailable external initializer payloads.
Overlap mode uses one I/O worker and a one-tensor look-ahead: reading the next
weight can overlap seeding and packing the previous weight on the caller’s CPU
executor. Serial mode reads all external payloads before preparation on the
caller, with no I/O worker.
Only the caller mutates RuntimeContext and ValueStore. Nested
external payloads are loaded, but this does not eagerly execute or prepare
their deferred branch/function sessions.
Successful construction completes all ready root preparations; an
insufficient admission budget raises an exception instead of silently
postponing that work until inference. This root readiness guarantee does not
claim that deferred child sessions have already been initialized. Root
declarations requiring runtime feeds or node-produced values remain visible
through pending_preparations() and complete before their inference consumers.
RuntimeLoadStatistics reports source bytes, a conservative conversion
reserve, logical peak admitted bytes, external tensor count, and bounded queue
occupancy. memory_limit is an admission budget, not an operating-system RSS
limit: source payloads remain owned by the model, and persistent packed buffers
remain in the store. Proto metadata, parser allocations, executor pools, and
inference allocations are outside this budget. The loader requires explicit
external tensor lengths and validates them against fixed-width types and
dimensions before admitting reads; it does not accept unbounded file-remainder
reads.
Peak admission includes the source and temporary work of each executed
declaration, including dependent preparations executed in the same drain.
RuntimeSession::preparation_peak_bytes() exposes the executor’s peak
preparation reservation, excluding the loader’s separate source/conversion
reservation.
The optional trace callback receives RuntimeLoadEvent phase,
tensor name, and steady_clock nanosecond timestamp. Events distinguish
declaration, read start/finish, preparation start/finish, and completion.
Callbacks can run on the caller or I/O thread and must be thread-safe; they must
not mutate the context/model or block waiting for later loader work.
The finished preparation event reports prepared_bytes_added; a positive
value witnesses actual static-buffer preparation rather than a no-ready
drain. Intersecting read intervals with those positive-growth preparation
intervals demonstrates genuine packing/I/O overlap, not merely the presence
of an overlap option.
Loading is synchronous, not a detached task or future, and exposes no
asynchronous cancellation handle. Exceptions stop further scheduling, join the
I/O worker, and propagate to the caller. Cancellation during cleanup does not
interrupt a read already in progress: cleanup waits for it to return.
A trusted external_reader override must
therefore finish or throw, honor the admitted length, and modify only the
requested tensor’s raw payload.
Preparation benchmark#
The self-contained bench_session_preparation target generates a real
external-data FLOAT Gemm chain using standard C++ APIs. By default it creates
eight distinct 1024-by-1024 matrices and sixteen Gemm nodes, reusing each
matrix twice. No helper script, downloaded model, or example inference feed is
needed for loading/preparation.
cmake -S . -B build -DONNX_LIGHT_BUILD_BENCHMARKS=ON
cmake --build build --target bench_session_preparation --parallel 6
./build/bench_session_preparation --directory bench-preparation-data --iterations 3
--directory must name a new directory; generated files are removed on
exit. Without this flag, the benchmark creates its named directory beneath
std::filesystem::temp_directory_path(). --weights and --dimension
configure the workload (at most 512 MiB of source weights). Mode order
alternates across iterations.
The benchmark reports last-external-read latency (model_load_ms, including
intervening packing), total load-to-ready latency (load_ready_ms), summed
preparation time
(packing_ms, including dispatch/publication), and first and warm inference
latencies. The first inference feed is supplied only after the loader returns.
It checks finite, numerically equivalent serial/overlap outputs, one shared
packing per distinct matrix, and unchanged store size/output on warm replay.
Packing time and overlap include only intervals whose finished event reports
positive prepared_bytes_added, excluding no-ready calls; the summed delta
must match the final packed allocation size.
Logical admission peak and queue occupancy are reported separately from process-lifetime peak RSS, available on Linux/macOS (zero otherwise). RSS includes model generation and earlier measurements, so it is not an isolated per-mode peak. Read/preparation interval intersections and an example timestamp pair document observed overlap. Generated files are likely already in the OS page cache, tracing adds overhead, and these measurements do not represent cold-disk loading or imply a guaranteed speedup.
Declares :cpp:class:RuntimeSession, a reusable execution session that separates kernel initialization from execution.
:cpp:class:RuntimeSession binds a precomputed :cpp:class:ExecutionPlan (which already carries the node list it drives) and, on its first :cpp:func:Run, resolves every executed node’s kernel once against the supplied :cpp:class:RuntimeContext; subsequent runs reuse the cached kernels. Every entry point that runs a node list — model callers (via :cpp:func:RegisterModelFunctions followed by their own :cpp:class:RuntimeSession), :cpp:class:SubgraphSession, the model-local function call helper, and the If / Loop / Scan control-flow kernels — constructs one of these sessions (over the graph’s or function’s cached :cpp:class:ExecutionPlan) and calls :cpp:func:Run a single time.
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace core
-
namespace runtime
-
struct KernelTuningResolutionStatistics#
- #include <runtime_session.h>
Reports the one-time kernel tuning work performed by a runtime session.
Public Functions
-
inline uint64_t TotalDurationNs() const noexcept#
Returns the measured cold tuning duration.
-
bool operator==(const KernelTuningResolutionStatistics&) const = default#
Public Members
-
uint64_t snapshot_duration_ns = 0#
Time spent capturing the immutable registry generation.
-
uint64_t resolution_duration_ns = 0#
Time spent resolving execution-specific profiles from that generation.
-
size_t tunable_kernels = 0#
Number of kernels that exposed a defined tuning key.
-
size_t resolved_profiles = 0#
Number of tunable kernels for which registered parameters were found.
-
inline uint64_t TotalDurationNs() const noexcept#
-
class RuntimeSession#
- #include <runtime_session.h>
A reusable execution session that binds a precomputed :cpp:class:
ExecutionPlanand separates the runtime lifecycle into three explicit phases:Construction — the session records the
planit will drive. The node list is recovered from :cpp:func:ExecutionPlan::nodes, so the session no longer needs the nodes (nor a :cpp:class:RuntimeContext) passed separately.Kernel initialization — the first :cpp:func:
Runresolves the kernel for every node the plan executes once (against the session’s model-local functions, explicit context-local functions, control-flow handlers, context-local and global custom kernels, then the static :cpp:func:KernelDispatchTableof the supplied :cpp:class:RuntimeContext), builds the resulting per-node kernel instance, and caches it. Any unsupported operator is rejected here rather than mid-run. It also records the external inputs the scheduled nodes read (:cpp:func:required_inputs) so :cpp:func:Runcan verify they are supplied before executing.Execution — :cpp:func:
Runreplays the plan, invoking each pre-resolved kernel instance and releasing intermediates as scheduled. It may be called more than once (e.g. to re-run the same graph with fresh inputs) without redoing the per-node dispatch lookup or re-constructing the concrete per-node kernel objects.
Global and context-local factories (including adapted callbacks) follow this same lifecycle. Registration replacement or removal only affects future resolutions, including child sessions not yet initialized. A new input shape does not change kernel identity: the existing kernel adapts its internal plan/workspace or explicitly rejects an unsupported change. The original graph/model and its nodes and functions must remain alive and unchanged until the session and its kernels are destroyed; adapters do not copy or serialize nodes. Factories must return independent mutable kernel state for each resolution. Independent sessions and contexts may run concurrently with thread-safe user callbacks and immutable shared parameters, but runs on the same session/context must be serialized by the caller. Sessions explicitly sharing a ValueStore must also serialize their runs.
This mirrors how an inference runtime prepares an executable graph once and then runs it repeatedly. Every caller that needs to run a node list builds one of these sessions over the list’s :cpp:class:
ExecutionPlanand calls :cpp:func:Runon it.Subclassed by onnx_light::core::runtime::SubgraphSession
Public Functions
-
explicit RuntimeSession(const ModelProto &model, int verbose = 0)#
Builds a session over an :cpp:class:
ExecutionPlanthe session owns, constructed frommodel’s graph (:cpp:func:ModelProto::graph). Use this when no precomputed plan is available: the session builds and owns the plan itself, so a caller can create a runnable session from a model alone (without first building an :cpp:class:ExecutionPlan). Kernel resolution is still deferred to the first :cpp:func:Run. Kernel opsets come frommodel.opset_import; missing domains, duplicate imports, unsupported versions, and conflicting legacy context opsets are rejected.- Parameters:
model – Model whose graph drives execution. The model (and the graph it owns) must remain immutable and outlive the session and its initializer views. The plan and directly usable initializer payloads borrow the model’s storage.
verbose – Verbosity level used by :cpp:func:
Runfor its progress lines.0(the default) leaves verbosity to the :cpp:class:RuntimeContext.
-
RuntimeSession(const ModelProto &model, RuntimeSessionOptions options)#
-
RuntimeSession(ModelProto &model, RuntimeSessionOptions options)#
-
explicit RuntimeSession(const ExecutionPlan &plan, int verbose = 0)#
Builds a session over
plan. Kernel resolution is deferred to the first :cpp:func:Run(which supplies the :cpp:class:RuntimeContextthe kernels are resolved against). A standalone plan (or bare graph) uses the caller’s legacy :cpp:func:RuntimeContext::kernel_ctxopset. Nested sessions inherit the active model/function imports instead.- Parameters:
plan – Precomputed execution / release schedule. Its node list (:cpp:func:
ExecutionPlan::nodes) drives execution. The plan (and the graph / function it was built from) must outlive the session.verbose – Verbosity level used by :cpp:func:
Runfor its progress lines.0(the default) leaves verbosity to the :cpp:class:RuntimeContext.
-
RuntimeSession(const ExecutionPlan &plan, RuntimeSessionOptions options)#
-
explicit RuntimeSession(const FunctionProto &function, RuntimeSessionOptions options = {})#
Builds a session over a function with its own opset imports.
-
RuntimeSession(const FunctionProto &function, const OpsetImports *inherited_opset_imports, RuntimeSessionOptions options = {}, const FunctionMap *model_functions = nullptr)#
Builds a nested function session. An empty function import list inherits
inherited_opset_importswithout copying it.model_functionsborrows the enclosing model session’s lookup for nested calls.
-
RuntimeSession(const ModelProto &model, RuntimeValueMap initial, RuntimeSessionOptions options = {})#
Builds a session owning graph-declared persistent values initialized from
initial.
-
~RuntimeSession()#
-
RuntimeSession(const RuntimeSession&) = delete#
-
RuntimeSession &operator=(const RuntimeSession&) = delete#
-
void Run(RuntimeContext &rt)#
Executes the plan once against
rt: on the first call it resolves and caches the kernel for every scheduled node (rejecting unsupported operators) and records the external inputs those nodes read; every call then verifiesrtsupplies each of those required inputs and runs each scheduled node using its resolved kernel. When :cpp:func:RuntimeContext::release_intermediatesis enabled onrt, it additionally frees each intermediate whose last reference has been reached, as scheduled by the plan; when disabled, every intermediate the plan would have released instead stays observable inrtafterRunreturns. Safe to call repeatedly on the same session.The allocator attached to
rt(:cpp:func:RuntimeContext::allocator) is captured once, on the first call, as the session’s unique allocator. After each scheduled node executes, every tensor it produced that is allocator-backed (:cpp:func:Tensor::has_allocation) is verified to be owned by that same allocator, catching kernels that allocate their output from the wrong allocator (or from none at all). This verification is skipped when :cpp:func:allow_external_output_allocatorsis enabled, so a kernel may legitimately return an output allocated outside the common allocator.- Parameters:
rt – In/out runtime context used both to resolve the kernels (function registry / custom kernels) and to exchange tensors.
- Throws:
std::invalid_argument – if the plan references an out-of-range node index, if any executed node cannot be dispatched, if
rtdoes not define one of the plan’s required external inputs, or if a node produces an output tensor backed by an allocator other than the session’s.
-
shapes::PeakMemoryEstimate ComputePeakMemory(size_t node_index, const std::vector<symbolic::SymShape> &input_shapes) const#
Returns additional memory for a resolved node’s implementation. Requires Prepare, DeclarePreparations or Run first. Later global or local registration changes do not affect this estimate. Uses the resolution device. This per-node estimate does not include nested graphs, persistent preparations, declared inputs/outputs, or runtime overhead, and is not a session admission bound.
-
void DeclarePreparations(RuntimeContext &rt)#
Resolves and tunes kernels and declares work without seeding or reading payloads.
-
void Prepare(RuntimeContext &rt)#
Seeds available initializers and completes ready work without running inference.
-
void ExecutePreparations(RuntimeContext &rt, size_t memory_limit = std::numeric_limits<size_t>::max())#
Drains ready work within a peak-byte budget without seeding initializer payloads. Calls on this session and sessions sharing its store must be serialized.
-
void ExecutePreparations(RuntimeContext &rt, size_t memory_limit, std::span<const std::string> changed_sources)#
Revisits only consumers of changed sources and newly satisfied dependencies. Source names are scheduling hints; availability and provenance are still checked.
-
inline size_t preparation_readiness_checks() const noexcept#
Returns the number of pending declarations inspected for readiness.
-
std::vector<KernelPreparationInfo> pending_preparations() const#
Returns deferred declarations, including unavailable sources and budget-limited work.
-
KernelPreparationMemory EstimatePreparationMemory(const RuntimeContext &rt, size_t preparation_index) const#
Estimates one declaration’s peak bytes while retaining its callables in this session.
-
inline size_t preparation_peak_bytes() const noexcept#
Returns the peak admitted store, source and work bytes of executed preparations.
-
RuntimeValueMap Run(RuntimeContext &rt, const RuntimeValueMap &feeds, const TaskCompletion *completion = nullptr)#
Runs in the supplied context and commits persistent feedback only on success.
The session owns its persistent state. Current feeds name whole graph inputs and cannot override retained inputs. Repeated calls reuse this session’s kernels and the supplied context’s allocators directly. Bound inputs and exported outputs are removed from the context on return, including on failure; unrelated values and recorded events are preserved.
An optional pending completion is a single-use cancellation/publication gate. Cancellation before publication leaves the retained values unchanged.
-
void Reset(RuntimeValueMap initial)#
Replaces persistent values to start a new sequence, retaining cached kernels.
-
PersistentValueState &persistent_state()#
Returns the session-owned persistent state; rejects stateless sessions.
-
const PersistentValueState &persistent_state() const#
-
inline const RuntimeParameters ¶meters() const noexcept#
Model-independent execution parameters (e.g. the requested degree of parallelism, :cpp:var:
RuntimeParameters::num_threads) applied to the nodes this session runs.
-
inline const CpuExecutionPolicy &cpu_execution_policy() const noexcept#
Returns the CPU execution policy this session requests, either the one supplied at construction or the one derived from :cpp:func:
parameters.
-
const std::shared_ptr<CpuExecutor> &cpu_executor()#
Returns the shared CPU executor this session leases, acquiring it from :cpp:func:
GlobalCpuExecutorRegistryon first use. Sessions whose resolved policies are compatible share one executor; incompatible policies get distinct pools. :cpp:func:Runinstalls it on the calling thread so every parallel region a kernel launches uses exactly these participants. Like the rest of the session state, the first acquisition is not synchronized: a session is prepared and run by one thread at a time, while distinct sessions may run concurrently on a shared executor.Returns: The leased executor, never null.
-
inline bool has_explicit_cpu_execution_policy() const noexcept#
Returns whether the CPU execution policy was supplied by the caller rather than derived from :cpp:func:
parameters. A session with a derived policy that runs inside another session’s run (a subgraph, a model-local function, or any nested session) reuses the executor already installed on the :cpp:class:RuntimeContextinstead of leasing a second pool.
-
inline int verbose() const noexcept#
Verbosity level requested for :cpp:func:
Run. When non-zero, it overrides :cpp:func:RuntimeContext::verbosefor this session’s progress lines without mutating the context itself.
-
inline const std::vector<std::string> &required_inputs() const noexcept#
Returns the external input names the scheduled nodes read (the inputs that must be present in the :cpp:class:
RuntimeContextbefore :cpp:func:Run). Populated during kernel initialization; empty until the first :cpp:func:Run.
-
std::vector<std::string> used_kernels() const#
Returns the normalized
"<domain>:<op_type>"identifiers of the kernels resolved by this session, in execution order. Repeated operators are preserved because each node owns a distinct kernel instance. The list is empty until the first :cpp:func:Runinitializes the kernels.
-
inline uint64_t tuning_generation() const noexcept#
Returns the immutable tuning-registry generation captured while kernels were initialized, or
0before the first :cpp:func:Run.
-
inline const KernelTuningResolutionStatistics &tuning_resolution_statistics() const noexcept#
Returns the cold tuning work recorded during first-run kernel initialization.
-
size_t prepared_bytes() const noexcept#
Returns live allocation bytes in this session’s static preparation store, including nested sessions and any other sessions explicitly sharing it. Includes allocated but unpublished values; excludes execution/I/O arenas, dynamic prepared-object residency, and retained free-buffer capacity.
-
inline ValueStore &value_store() noexcept#
Returns the non-null static preparation store fixed at construction. Kernels publish during initialization and use stable slots during replay. This is not the invocation value directory.
-
inline const ValueStore &value_store() const noexcept#
-
inline const std::shared_ptr<ValueStore> &value_store_owner() noexcept#
Returns the owner to share explicitly with another session or nested kernel.
-
inline std::shared_ptr<const ValueStore> value_store_owner() const noexcept#
Returns a read-only shared owner without permitting preparation mutation.
-
inline bool check_shapes() const noexcept#
Enables or disables concrete-shape validation. When enabled, :cpp:func:
Runchecks that the concrete shape of every tensor carrying a declared (possibly symbolic) shape — the graph inputs, outputs andvalue_inforecorded by :cpp:func:SetDeclaredShapes— is consistent with that declaration: a concretedim_valuemust match exactly, and every symbolicdim_parammust resolve to the same concrete value everywhere it appears during a single :cpp:func:Run. Disabled by default so the hot path stays free of the extra checks. Declared shapes are populated automatically when the session is built from a :cpp:class:ModelProto; a session built from an :cpp:class:ExecutionPlanalone must call :cpp:func:SetDeclaredShapesfor the check to have anything to validate.
-
inline bool allow_external_output_allocators() const noexcept#
When
true, :cpp:func:Rundoes not require a node’s allocator-backed outputs to be owned by the session’s unique allocator, so a kernel may return an output allocated outside the common allocator. Whenfalse(the default), such an output is rejected. See :cpp:member:RuntimeSessionOptions::allow_external_output_allocators.
-
inline const std::shared_ptr<ParallelRegionCollector> ¶llel_region_collector() const noexcept#
Returns the optional collector retained by this session.
-
inline ParallelRegionReport parallel_region_report() const#
Returns an owning profiling snapshot, or an empty report when profiling is disabled.
-
void SetDeclaredShapes(const GraphProto &graph)#
Records the declared tensor element types and (possibly symbolic) shapes carried by
graph’s inputs, outputs andvalue_info. Element types are used to resolve tuning keys for inputs not yet produced; shapes are used by :cpp:func:Runwhen :cpp:func:check_shapesis enabled. Only tensor-typed values are recorded. Calling this replaces any previously recorded declarations for the listed names.graphis read but not retained, so it need not outlive the session.
-
void SetInitializers(const GraphProto &graph)#
Records
graphas the source of read-only initializer views. A session built from a model or graph calls this automatically; callers constructing a session from an :cpp:class:ExecutionPlanmay call it once before the first :cpp:func:Run. The graph and its backing storage must remain immutable and outlive the session and its initializer views.
-
void SetConsumableInitializers(GraphProto &graph)#
Grants exclusive payload ownership before initialization. Metadata remains available; successfully replaced single-consumer raw payloads are removed from graph and context. The caller must not reuse/share the model or construct new sessions from it afterward.
-
inline size_t consumed_initializer_bytes() const noexcept#
Public Static Functions
-
static std::vector<std::string> CollectExternalInputs(const utils::RepeatedProtoField<NodeProto> &nodes)#
Returns the list of input names referenced by
nodesthat are not produced as outputs by any node in the same list — i.e. the external dependencies of the node set. Subgraph attributes (GRAPH/GRAPHS) are inspected recursively. The returned list preserves first-seen order and contains no duplicates; empty input names are skipped.
-
static std::vector<std::string> CollectNodeInputs(const NodeProto &node)#
Returns the full list of tensor / sequence names a single
nodedepends on at runtime: the names referenced bynode.input()(skipping empty optional-input slots) plus every external input of the subgraph attributes (GRAPH/GRAPHS) attached tonode. The returned list preserves first-seen order and contains no duplicates.
Protected Functions
-
inline void SetNestedExecution() noexcept#
Marks a function or control-flow body as nested in its caller’s invocation.
Constructs a session over a bare :cpp:class:
GraphProto, owning the resulting :cpp:class:ExecutionPlanindefault_plan_. Used by :cpp:class:SubgraphSessionso a control-flow subgraph can be a :cpp:class:RuntimeSessionwith the same default resolution behavior as a top-level graph session. Immutable input names refer to this graph’s scope, after caller binding and shadow filtering.
-
std::unique_ptr<KernelBase> ResolveNodeKernel(const NodeProto &node, RuntimeContext &rt, const std::string &domain, const std::string &op_type, const KernelContext &kernel_context, const std::unordered_set<std::string> &preparable_inputs) const#
Default node-kernel resolution used during :cpp:func:
InitializeKernels, so :cpp:class:RuntimeSessionand derived sessions that reuse the base initialization path share the same default resolution behavior. Builds and returns the ready-to-invoke kernel instance fornode.
Private Functions
-
RuntimeSession(const ModelProto &model, RuntimeSessionOptions options, GraphProto *consumable)#
-
void InitializeKernels(RuntimeContext &rt, const std::unordered_set<std::string> &preparable_inputs)#
Resolves and builds the kernel instance for every node the plan executes, resolving against
rt, and records the external inputs those nodes read in :cpp:member:required_inputs_.
-
void ExecutePreparationsImpl(RuntimeContext &rt, size_t memory_limit, const std::unordered_set<std::string> &available_outputs)#
-
void QueuePreparation(size_t index)#
-
void ConsumePreparationSources(size_t index, RuntimeContext &rt)#
-
int32_t TuningElementType(const NodeProto &node, const KernelBase &kernel, const RuntimeContext &rt, const std::unordered_set<std::string> *available_outputs = nullptr) const#
-
void ResolveDeferredTuning(size_t node_index, RuntimeContext &rt, const std::unordered_set<std::string> &available_outputs, bool at_consumer = false)#
-
void ResolveKernelValueSlots(RuntimeContext &rt)#
-
const OpsetImports *EffectiveOpsetImports() const noexcept#
-
const FunctionMap *EffectiveModelFunctions() const noexcept#
-
std::unordered_set<std::string> SeedInitializers(RuntimeContext &rt) const#
Seeds missing initializer names and returns the names installed by this session.
-
void VerifyOutputAllocators(const NodeProto &node, RuntimeContext &rt) const#
Normalizes every raw tensor output of
nodeinto the arena implied by that output slot’s role: a declared graph output (a name present in :cpp:member:output_names_set_) is normalized into :cpp:member:session_io_allocator_when an I/O allocator is attached, every other (intermediate) output into :cpp:member:session_allocator_. This is output-slot routing: a node producing both a declared output and an intermediate keeps each value in its own arena. Called after a node’s kernel has run, once :cpp:member:session_allocator_has been captured.
-
bool ProducesDeclaredOutput(const NodeProto &node) const#
Returns whether
nodeproduces at least one declared graph output (a name present in :cpp:member:output_names_). Used by :cpp:func:Runto route that node’s kernel invocation through the I/O allocator instead of the execution allocator.
-
void VerifyDeclaredShape(const std::string &name, const RuntimeContext &rt, core::shapes::ShapesContext &bindings) const#
Verifies, when :cpp:func:
check_shapesis enabled, that the concrete shape of the tensor stored undernameinrt(if any) matches the declared :cpp:class:core::symbolic::SymShaperecorded in :cpp:member:declared_shapes_. Concrete dimensions must match exactly; symbolic dimensions are resolved againstbindings(a :cpp:class:core::shapes::ShapesContextbinding each symbolic expression to the concrete value it first resolved to during the current :cpp:func:Run), so an inconsistent reuse of the same symbol is rejected. Names without a recorded declaration, or not currently present as a tensor, are ignored.
-
void MaterializeBorrowedOutputs(RuntimeContext &rt) const#
Detaches every graph output present in
rtfrom any external memory it borrows: for each name in :cpp:member:output_names_whose tensor is a borrowed view (:cpp:func:Tensor::is_borrowed), the entry is replaced with an owned deep copy (:cpp:func:Tensor::ToOwned). A graph output can borrow into the model (e.g. aConstantreading its value’sraw_dataor an initializer passed straight through), which would dangle once the model is released; owning the bytes keeps the output valid independently of the model’s lifetime. Called at the end of :cpp:func:Run. Only runs when :cpp:member:output_names_is populated (sessions built from a :cpp:class:ModelProto/ :cpp:class:GraphProto).
Private Members
-
ExecutionPlan default_plan_#
Plan owned by the session, referenced by :cpp:member:
plan_when the session is constructed from a :cpp:class:ModelProtoor :cpp:class:FunctionProto(no external plan supplied). Left empty (and unused) when a plan is passed in through the plan-taking constructor.
-
const ExecutionPlan &plan_#
-
std::optional<OpsetImports> owned_opset_imports_#
Imports declared directly by a model or function. Subgraphs and functions without imports borrow their enclosing session’s immutable map instead.
-
const OpsetImports *inherited_opset_imports_ = nullptr#
-
FunctionMap model_functions_#
Borrowed definitions from the model; nested sessions borrow this map from their parent.
-
const FunctionMap *inherited_model_functions_ = nullptr#
-
std::shared_ptr<ValueStore> value_store_#
-
std::unique_ptr<PersistentValueState> persistent_state_#
-
std::vector<PreparedKernel> kernels_#
-
std::vector<KernelPreparation> preparations_#
-
size_t preparation_memory_limit_ = 0#
-
size_t preparation_store_bytes_ = 0#
-
size_t preparation_readiness_checks_ = 0#
-
size_t pending_preparation_count_ = 0#
-
size_t pending_tuning_count_ = 0#
-
size_t preparation_peak_bytes_ = 0#
-
const GraphProto *initializer_graph_ = nullptr#
-
std::unordered_map<std::string, ConsumableInitializer> consumable_initializers_#
-
size_t consumed_initializer_bytes_ = 0#
-
std::optional<StructTypeCatalogue> struct_type_catalogue_#
-
std::shared_ptr<const QuantizationParameterCatalogue> quantization_parameters_#
-
std::unordered_set<std::string> inherited_immutable_inputs_#
Captured or bound immutable names, excluding locally defined graph values.
-
std::optional<KernelTuningRegistrySnapshot> tuning_snapshot_#
One immutable registry generation shared by every kernel in this session. Kernels copy resolved values during initialization; retaining the snapshot also makes the generation available for diagnostics.
-
KernelTuningResolutionStatistics tuning_resolution_statistics_#
-
std::vector<uint32_t> action_value_slots_#
Stable RuntimeContext slot for each action’s primary name. Nameless actions carry
UINT32_MAX.
-
uint64_t value_directory_identity_ = 0#
-
std::unordered_map<std::string, core::symbolic::SymShape> declared_shapes_#
Declared (possibly symbolic) shapes keyed by tensor name, populated by :cpp:func:
SetDeclaredShapesand consulted by :cpp:func:Runwhen :cpp:member:check_shapes_is enabled.
-
std::unordered_map<std::string, int32_t> declared_tensor_types_#
Declared tensor element types keyed by value name, populated by :cpp:func:
SetDeclaredShapesand consulted during kernel tuning when the selected input is an intermediate not yet present in the runtime context.
-
std::vector<std::string> output_names_#
Names of the graph’s declared outputs, populated from the :cpp:class:
ModelProto/ :cpp:class:GraphProtothe session is built from (empty for a session built from a bare :cpp:class:ExecutionPlan). Consulted by :cpp:func:MaterializeBorrowedOutputsso borrowed graph outputs are detached from the model before :cpp:func:Runreturns.
-
std::unordered_set<std::string> output_names_set_#
Same names as :cpp:member:
output_names_, indexed for O(1) membership checks by :cpp:func:ProducesDeclaredOutputand :cpp:func:VerifyOutputAllocators.
-
bool kernels_initialized_ = false#
-
bool check_shapes_ = false#
When
true, :cpp:func:Runvalidates concrete tensor shapes against the declarations in :cpp:member:declared_shapes_.
-
bool allow_external_output_allocators_ = false#
When
true, :cpp:func:Runskips the per-node output allocator check (see :cpp:func:VerifyOutputAllocators), allowing outputs allocated outside the session’s common allocator.
-
bool route_declared_outputs_to_io_ = true#
-
bool materialize_outputs_ = true#
-
RuntimeParameters parameters_#
-
CpuExecutionPolicy cpu_execution_#
Requested CPU execution policy, derived from :cpp:member:
parameters_when the caller did not supply one.
-
bool cpu_execution_explicit_ = false#
Whether :cpp:member:
cpu_execution_was requested explicitly. A session with a derived policy nested inside another session’s run reuses the enclosing executor instead of leasing a second pool.
-
bool cpu_execution_counters_ = false#
Whether this session enables optional executor dispatch counters.
-
std::shared_ptr<ParallelRegionCollector> parallel_region_collector_#
Optional bounded profiling collector installed for each run.
-
std::shared_ptr<CpuExecutor> cpu_executor_#
Lease on the shared executor, acquired on first use by :cpp:func:
cpu_executor.
-
int verbose_ = 0#
Verbosity level used by :cpp:func:
Runwhen non-zero.
-
RawBufferAllocator *session_allocator_ = nullptr#
Execution allocator of the current :cpp:func:
Runinvocation.
-
RawBufferAllocator *session_io_allocator_ = nullptr#
I/O allocator of the current :cpp:func:
Runinvocation. When non-null, :cpp:func:Runroutes the kernel invocation of any node that produces a declared graph output (see :cpp:member:output_names_set_) through this allocator instead of :cpp:member:session_allocator_.
-
struct ConsumableInitializer#
Public Members
-
TensorProto *tensor#
-
TensorProto *tensor#
-
struct PreparedKernel#
A node’s kernel instance built once during :cpp:func:
InitializeKernels, together with the normaliseddomainandop_typefused into a single"<domain>:<op_type>"key (the same format used to look the kernel up in the :cpp:func:KernelDispatchTable) so :cpp:func:Runnever has to recompute or re-store them separately.
-
struct RuntimeSessionOptions#
- #include <runtime_session.h>
Construction-time settings for :cpp:class:
RuntimeSession.Sessions are intended to be built once and reused, so these values stay fixed for the session’s lifetime.
Public Members
-
RuntimeParameters parameters = {}#
-
std::optional<CpuExecutionPolicy> cpu_execution = std::nullopt#
Requested CPU execution policy. When empty, the session derives its policy from :cpp:var:
RuntimeParameters::num_threadsand leaves worker placement to the operating system (:cpp:enumerator:CpuAffinityPolicy::kNone), matching ONNX Runtime’s default. A caller that wants pinned workers, another spin policy, or nested parallelism supplies the policy explicitly.
-
bool cpu_execution_counters = false#
Enables optional executor dispatch counters for inspection.
-
std::shared_ptr<ParallelRegionCollector> parallel_region_collector = nullptr#
Optional bounded collector retained and installed for every session run.
-
int verbose = 0#
-
bool check_shapes = false#
-
bool allow_external_output_allocators = false#
When
false(the default), :cpp:func:RuntimeSession::Runverifies that every allocator-backed output a node produces is owned by the session’s unique allocator, rejecting a kernel that allocates its output from a different allocator (or from none at all). Whentrue, that check is skipped so a kernel may legitimately return an output allocated outside the common allocator.
-
size_t persistent_tensor_initial_capacity = 32#
Initial capacity along a kernel’s append axis for contiguous persistent tensors. Zero disables append reservations; kernels use their ordinary allocation path.
-
std::shared_ptr<ValueStore> value_store = nullptr#
Static preparation store shared with nested graph and model-local function sessions. When omitted, construction creates a private store independent of runtime contexts. Supplying an owner explicitly shares preparations and their allocation accounting. Runs of sessions sharing one store must be serialized.
-
std::unordered_set<std::string> immutable_inputs = {}#
Immutable names inherited from a caller after binding function inputs.
-
bool consume_initializers = false#
Transfers initializer payloads to preparations. The supplied model must not be reused.
-
RuntimeParameters parameters = {}#
-
struct KernelTuningResolutionStatistics#
-
namespace shapes#
-
namespace runtime
-
namespace core
See runtime_session_loader.h for the owning loader API reference.