Standalone threading#
The implementation is shared by the existing proto/runtime facades. It does not require ONNX model types; see Threading implementation and ownership.
Configuration and visibility#
Defines
-
ONNX_THREADS_API#
I/O batch adapter#
-
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 utils
-
class ThreadPool#
- #include <thread_pool.h>
Thread pool used to parallelize delayed block loading.
Manages a fixed set of worker threads that pull jobs from a shared queue. Call Start() to launch workers, SubmitTask() to enqueue work, and Wait() to block until all submitted jobs have completed and the workers have stopped. The pool can be restarted by calling Start() again after Wait() returns. Clear() resets internal state when the pool is idle (not started).
Public Functions
-
ThreadPool()#
Initializes the thread pool in a stopped, idle state.
-
~ThreadPool()#
Destroys the thread pool by calling Wait().
Blocks until all pending jobs have finished executing, then stops and joins all worker threads. If the pool has already been stopped, this is a no-op.
-
void Start(int32_t num_threads)#
Starts the pool, deferring worker-thread creation until the first task.
The pool is marked started immediately, but the worker threads are only spawned lazily on the first SubmitTask() call. A parse/serialize that never submits a delayed block (typically a small model whose tensor blocks all stay below the parallelization threshold) therefore never pays the cost of creating and joining threads, keeping load/save latency minimal.
- Parameters:
num_threads – Number of worker threads to create. Any negative value (for example
-1) is treated as a request to use the value returned bystd::thread::hardware_concurrency().
-
void SubmitTask(std::function<void()> &&job)#
Submits a callable job for asynchronous execution.
If no worker threads have been started, the job is queued and will be run inline when Wait() is called.
- Parameters:
job – Callable to execute.
-
void Wait()#
Blocks until all submitted jobs have finished executing, then stops and joins all worker threads.
If no workers were started, runs any queued jobs inline on the calling thread. If a submitted job throws, Wait() rethrows the first captured exception on the caller thread after all workers have been joined. After Wait() returns, the pool is in a stopped state and can be restarted with Start().
-
inline size_t GetThreadCount() const#
Returns the number of worker threads the pool has (or will lazily spawn).
-
inline bool IsStarted() const#
Returns whether the pool has been started (workers may start lazily).
Private Functions
-
void WaitImpl(bool rethrow_exceptions)#
-
ThreadPool()#
-
class ThreadPool#
-
namespace utils
Queued workers#
-
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 utils
-
class WorkerPool#
- #include <worker_pool.h>
Persistent fixed-size worker pool.
Workers remain available across calls to WaitIdle() and stop only when Shutdown() is called.
Public Functions
-
WorkerPool()#
-
explicit WorkerPool(int32_t num_threads)#
-
~WorkerPool()#
-
WorkerPool(const WorkerPool&) = delete#
-
WorkerPool &operator=(const WorkerPool&) = delete#
-
void Start(int32_t num_threads)#
Starts persistent workers. A negative count uses hardware concurrency.
-
void WaitIdle()#
Waits for all queued work and rethrows the first task exception.
-
void Shutdown()#
Drains pending work and permanently joins the current worker set.
-
size_t GetThreadCount() const#
-
bool IsStarted() const#
Private Functions
-
void WorkerLoop()#
Friends
- friend class ThreadPool
-
WorkerPool()#
-
class WorkerPool#
-
namespace utils
Parallel regions#
Persistent thread pool and block-parallel iteration helper for element-wise kernels.
-
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
Functions
-
int64_t ParallelForThreadCount() noexcept#
Returns the number of participating threads :cpp:func:
ParallelFormay use.When a :cpp:class:
CpuExecutoris installed on the calling thread (see :cpp:class:CpuExecutorScope), the executor’s effective participant count is returned so the reported value describes the workers that actually run the graph. Outside any executor scope it resolves to one participant per detected physical core, falling back to the detected logical-core count and thenstd::thread::hardware_concurrency(). The result is always>= 1and counts the calling thread, which always participates in the work.Returns: The effective participant count, always at least
1.
-
ThreadPool &GlobalThreadPool()#
Returns the process-wide :cpp:class:
ThreadPoolused by :cpp:func:ParallelFor.The pool is constructed on first use with
ParallelForThreadCount() - 1worker threads (the calling thread makes up the last participant) and lives for the remainder of the process. Threads are therefore created once and reused across everyParallelForcall. Afterfork(), the child abandons the inherited pool without joining its vanished workers and creates a child-owned pool on first use. References obtained beforefork()must not be reused in the child; call this function again instead.Returns: A reference to the shared thread pool.
-
template<typename Fn>
void ParallelFor(int64_t total, int64_t minimum_elements, Fn fn, std::string_view label = {}, std::source_location location = std::source_location::current())# Splits the half-open range
[0, total)into contiguous blocks and invokesfn(begin, end)once per block.Blocks are processed on the :cpp:class:
CpuExecutorinstalled on the calling thread, or on the shared :cpp:func:GlobalThreadPoolwhen the caller runs outside any executor scope (up to :cpp:func:ParallelForThreadCountparticipants, including the calling thread). Whentotalis belowminimum_elementsor only one thread is available, the whole range is processed inline on the calling thread, sofnmust be safe to call once with the full range. The three-argument overload accepts a kernel-specificminimum_elements; the two-argument overload below uses :cpp:var:kParallelForMinimumElements. Every block is disjoint and covers the range exactly once, so the observable result is independent of the number of threads: kernels that only map input elements to output elements (no cross-element accumulation) stay bit-exact.fnis invoked concurrently from several threads and must therefore only touch data disjoint per block (typically writingoutput[begin, end)frominput[begin, end)). It must not throw.- Parameters:
total – Number of iterations. Values
<= 0are a no-op.minimum_elements – Minimum iterations required for parallel execution. Must be positive.
fn – Callable invoked as
fn(int64_t begin, int64_t end)for each block, covering[begin, end).
Variables
-
constexpr int64_t kParallelForMinimumElements = 1 << 15#
Iteration count below which :cpp:func:
ParallelForruns the whole range inline on the calling thread. Waking worker threads for tiny ranges costs more than the work they save, so small tensors stay single-threaded.
-
constexpr int64_t kParallelForGrainSize = kParallelForMinimumElements#
Backward-compatible name for the crossover threshold, not a per-block grain.
-
class ThreadPool#
- #include <parallel_for.h>
A persistent pool of worker threads that stay alive between parallel regions.
Unlike spawning fresh
std::threadobjects per call, the workers are created once and briefly spin before parking on a condition variable. Nearby regions therefore avoid scheduler wakeup latency without busy-waiting indefinitely. After a region that needs only part of the pool, only its participating workers spin; unused workers remain parked.The pool exposes a single primitive, :cpp:func:
Run, that executes a set of indexed blocks: block0runs on the calling thread and each selected worker receives one remaining block. It deliberately offers no reduction/combine step: callers write disjoint output ranges, so results are independent of how blocks map to threads (bit-exact). The pool handles several scenarios:no workers available (single core): every block runs inline on the caller;
a single block: runs inline without touching the workers;
nested calls from inside a running block: run inline by default, or use idle workers when bounded nested admission is enabled;
concurrent calls from unrelated threads: serialized so one region runs at a time, each still internally parallel.
Public Types
-
using TaskFn = void (*)(void*, int64_t)#
Type-erased block callable:
fn(context, block_index).
Public Functions
-
explicit ThreadPool(int64_t num_workers)#
Creates a pool with
num_workersparked worker threads.- Parameters:
num_workers – Number of worker threads to spawn. Values
<= 0create a pool with no workers, in which case :cpp:func:Runexecutes every block on the caller.
-
ThreadPool(int64_t num_workers, ThreadPoolOptions options)#
Creates a pool with explicit startup and spin behavior.
-
ThreadPool(const ThreadPool&) = delete#
-
ThreadPool &operator=(const ThreadPool&) = delete#
-
~ThreadPool()#
-
inline int64_t worker_count() const noexcept#
Returns the number of worker threads (the calling thread is not counted).
Returns: The worker-thread count,
>= 0.
-
template<typename Fn>
inline void Run(int64_t num_blocks, Fn &&fn)# Runs
fn(block)for everyblockin[0, num_blocks), then blocks until all blocks finish.Unless
ThreadPoolOptions::allow_nested_parallelismis enabled, block0runs on the calling thread and selected workers receive the remaining blocks by index. Only as many parked workers as there are worker blocks are notified, andnum_blocksmust not exceedworker_count() + 1when workers are used; :cpp:func:ParallelForenforces this. With nested parallelism enabled, blocks are striped across the admitted caller and idle workers, sonum_blocksmay exceed the participant count.fnis invoked concurrently and must only touch data disjoint per block; it must not throw.- Parameters:
num_blocks – Number of blocks to run. Values
<= 0are a no-op.fn – Callable invoked as
fn(int64_t block).
-
int64_t RunBounded(int64_t maximum_participants, void *context, void (*function)(void*, int64_t, int64_t))#
Runs up to
maximum_participantsblocks on the caller and idle workers. The callback receives its block index and the admitted block count, and must not throw. Unrelated callers serialize; nested callers never wait for worker admission. Calls from another pool execute inline to avoid cross-pool lock inversion. RequiresThreadPoolOptions::allow_nested_parallelism. Returns the admitted participant count.
Public Static Functions
-
static inline bool InParallelRegion() noexcept#
Returns whether the calling thread is executing a pool region.
Private Functions
-
void StopAndJoin() noexcept#
-
bool SpinForWork(uint64_t last_generation, int64_t worker_index) const noexcept#
-
void WorkerLoop(int64_t worker_index)#
-
void BoundedWorkerLoop(int64_t worker_index)#
Private Members
-
ThreadPoolOptions options_#
-
void *task_ctx_ = nullptr#
-
int64_t num_blocks_ = 0#
-
int64_t started_workers_ = 0#
Private Static Functions
-
static ThreadPool *&CurrentBoundedPool() noexcept#
-
static bool &InPoolFlag() noexcept#
-
static bool InPool() noexcept#
-
struct ThreadPoolOptions#
- #include <parallel_for.h>
Configures worker startup and spin-before-park behavior for a :cpp:class:
ThreadPool.Public Types
Public Members
-
uint64_t spin_iterations = 1000000#
Number of relax iterations before parking.
-
uint64_t spin_duration_ns = 0#
Duration in nanoseconds to spin before parking. Used only when
spin_iterationsis zero.
-
WorkerStartFn worker_start = nullptr#
Optional callback invoked once by every worker before accepting work.
-
void *worker_start_context = nullptr#
Context passed to :cpp:var:
worker_start.
-
bool allow_nested_parallelism = false#
Enables bounded nested admission on idle workers of this pool.
-
uint64_t spin_iterations = 1000000#
-
namespace detail
Typedefs
-
using ParallelRangeFn = void (*)(void*, int64_t, int64_t)#
Functions
-
void ParallelForErased(int64_t total, int64_t minimum_elements, void *task_ctx, ParallelRangeFn task_fn)#
-
void ParallelForErasedProfiled(int64_t total, int64_t minimum_elements, void *task_ctx, ParallelRangeFn task_fn, ParallelRegionCollector *collector, std::string_view label, std::source_location location)#
-
using ParallelRangeFn = void (*)(void*, int64_t, int64_t)#
-
int64_t ParallelForThreadCount() noexcept#
-
namespace runtime
-
namespace core
CPU descriptor#
-
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 platform#
Enums
-
enum class CpuFeature : uint8_t#
Identifies an instruction-set capability usable by the current process.
The numeric values are stable to keep CpuFeatureSet::bits() and CpuFeatureName serialization stable across releases.
Values:
-
enumerator kSse2#
-
enumerator kSse41#
-
enumerator kSse42#
-
enumerator kAvx#
-
enumerator kFma#
-
enumerator kAvx2#
-
enumerator kAvx512F#
-
enumerator kAvx512Bw#
-
enumerator kAvx512Vl#
-
enumerator kNeon#
-
enumerator kDotProduct#
-
enumerator kSve#
-
enumerator kSve2#
-
enumerator kSse2#
Functions
-
std::string_view CpuFeatureName(CpuFeature feature) noexcept#
Returns the stable serialized name of a CPU feature.
Returns: The lowercase feature name.
-
std::optional<CpuFeature> CpuFeatureFromName(std::string_view name) noexcept#
Parses a stable CPU feature name.
Returns: The feature, or
std::nulloptfor an unknown name.
-
CpuDescriptor DetectCpuDescriptor()#
Detects processor properties visible to the current process.
Returns: A descriptor whose unavailable fields remain unknown.
-
const CpuDescriptor &GetCpuDescriptor()#
Returns the processor descriptor detected once for the current process.
Returns: The immutable process-wide descriptor.
-
struct CpuDescriptor#
- #include <cpu_descriptor.h>
Describes immutable properties of the processor visible to the process.
Optional values remain absent when the operating system or architecture cannot report them reliably.
Public Functions
-
bool operator==(const CpuDescriptor&) const = default#
Public Members
-
CpuFeatureSet features#
-
bool operator==(const CpuDescriptor&) const = default#
-
class CpuFeatureSet#
- #include <cpu_descriptor.h>
Stores a compact set of CPU instruction-set capabilities.
Public Functions
-
constexpr CpuFeatureSet() = default#
-
inline explicit constexpr CpuFeatureSet(uint64_t bits)#
-
inline constexpr void Add(CpuFeature feature)#
Adds a feature to the set.
-
inline constexpr bool Has(CpuFeature feature) const#
Returns whether the set contains a feature.
Returns:
truewhen the feature is present.
-
inline constexpr bool ContainsAll(CpuFeatureSet other) const#
Returns whether every feature in another set is present.
Returns:
truewhen all requested features are present.
-
inline constexpr bool Intersects(CpuFeatureSet other) const#
Returns whether this set and another set share a feature.
Returns:
truewhen at least one feature is shared.
-
inline constexpr uint64_t bits() const#
Returns the underlying stable bit mask.
-
constexpr bool operator==(const CpuFeatureSet&) const = default#
Private Members
-
uint64_t bits_ = 0#
Private Static Functions
-
static inline constexpr uint64_t FeatureBit(CpuFeature feature)#
-
constexpr CpuFeatureSet() = default#
-
struct CpuSelector#
- #include <cpu_descriptor.h>
Selects processors using stable identifiers rather than display names.
Empty optional fields and an empty model list are wildcards. Thread limits require an explicit effective thread count when matching.
Public Functions
-
bool Matches(const CpuDescriptor &processor, std::optional<uint32_t> effective_threads = std::nullopt) const#
Returns whether a processor and execution thread count satisfy the selector.
Returns:
truewhen every specified criterion matches.
-
bool Matches(const CpuDescriptor &processor, std::optional<uint32_t> effective_threads = std::nullopt) const#
-
enum class CpuFeature : uint8_t#
-
namespace platform#
-
namespace core
CPU execution policy#
Requested and resolved CPU execution policy for a runtime session.
Defines the requested policy and its immutable topology-derived resolution, independently of any model runtime.
-
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
Enums
-
enum class CpuSpinPolicy#
Controls how a waiting worker or caller spins before parking.
Spinning applies both to workers waiting for a new generation and to the caller waiting for worker completion. The default bounds the spin and eventually parks.
Values:
-
enumerator kAdaptive#
Bounded, topology-derived spin that eventually parks.
-
enumerator kFixedIterations#
Spin for an explicit number of iterations before parking.
-
enumerator kFixedDuration#
Spin for an explicit duration in nanoseconds before parking.
-
enumerator kParkImmediately#
Park immediately without spinning.
-
enumerator kAdaptive#
-
enum class CpuAffinityPolicy#
Controls how workers are placed on the process-visible logical processors.
Values:
-
enumerator kNone#
Do not pin workers; a successful no-affinity policy.
-
enumerator kPhysicalCores#
One logical processor per physical core.
-
enumerator kPerformanceCores#
Prefer performance cores when the topology can identify them.
-
enumerator kPhysicalThenSmt#
One logical processor per physical core, then SMT siblings.
-
enumerator kExplicit#
Pin workers to an explicit CPU set.
-
enumerator kNone#
Functions
-
std::vector<CpuLogicalProcessor> ProcessVisibleLogicalProcessors()#
Returns stable identifiers for the logical processors currently available to this process.
The returned set reflects process affinity restrictions such as Linux cpusets. It is empty when the operating system cannot expose stable logical processor identifiers.
Returns: The process-visible logical processors in increasing identifier order.
-
uint32_t DefaultCpuParticipantCount() noexcept#
Returns the default number of CPU participants available to this process.
The count prefers process-visible physical cores, then process-visible logical processors, and falls back to machine topology when process affinity cannot be queried. The result is always at least
1.Returns: The default number of CPU participants.
-
uint32_t DetectedPhysicalCoreCount() noexcept#
Returns the detected physical core count for the process-visible topology.
Falls back to the platform CPU descriptor when the topology cannot be read, matching the detection :cpp:func:
ResolveCpuExecutionPolicyuses to bound :cpp:enumerator:CpuAffinityPolicy::kPhysicalCoresparticipant counts.Returns: The detected physical core count, or
0when it cannot be determined.
-
ResolvedCpuExecutionPolicy ResolveCpuExecutionPolicy(const CpuExecutionPolicy &request)#
Resolves a requested CPU execution policy into an immutable resolution.
Resolution validates the request deterministically and derives the effective participant count and worker placement from the process-visible topology. Fallbacks taken when a requested topology feature is unavailable are recorded in :cpp:var:
ResolvedCpuExecutionPolicy::diagnosticsrather than failing.The following requests fail with :cpp:class:
std::invalid_argument:a negative :cpp:var:
CpuExecutionPolicy::num_threads;a spin budget that is zero for a fixed policy or non-zero for the adaptive or park-immediately policy;
a :cpp:enumerator:
CpuAffinityPolicy::kExplicitpolicy with an empty CPU set, duplicate identifiers, or an identifier outside the process-visible set;a non-explicit affinity policy that supplies a CPU set;
an explicit CPU set whose size conflicts with a positive requested thread count.
Returns: The immutable resolution derived from the request.
- Parameters:
request – The requested policy.
Variables
-
constexpr uint64_t kDefaultAdaptiveSpinIterations = 10000#
Default number of adaptive spin iterations recorded before parking.
-
struct CpuExecutionPolicy#
- #include <cpu_execution_policy.h>
Requested per-session CPU execution policy.
Names are illustrative and may change during API review. The policy is resolved into an immutable :cpp:class:
ResolvedCpuExecutionPolicyby :cpp:func:ResolveCpuExecutionPolicy.Public Functions
-
bool operator==(const CpuExecutionPolicy&) const = default#
Public Members
-
int32_t num_threads = 0#
Requested number of participants, including the calling thread.
0(default): use a topology-derived default.1: serial, no worker threads.> 1: request exactly this many participants.< 0: rejected.
-
CpuSpinPolicy spin_policy = CpuSpinPolicy::kAdaptive#
Requested spin-before-park policy.
-
uint64_t spin_budget = 0#
Iterations for :cpp:enumerator:
CpuSpinPolicy::kFixedIterationsor nanoseconds for :cpp:enumerator:CpuSpinPolicy::kFixedDuration. Must be0for the adaptive and park-immediately policies.
-
CpuAffinityPolicy affinity_policy = CpuAffinityPolicy::kNone#
Requested affinity policy.
-
std::vector<CpuLogicalProcessor> cpu_set#
Explicit participant CPU set, required and only allowed for :cpp:enumerator:
CpuAffinityPolicy::kExplicit. The first processor is assigned to the calling participant; the remaining processors are assigned to workers.
-
bool allow_nested_parallelism = false#
Allows nested regions to use idle workers from the same executor without exceeding the resolved participant limit. Defaults to inline nesting, which is usually more efficient.
-
bool operator==(const CpuExecutionPolicy&) const = default#
-
struct CpuLogicalProcessor#
- #include <cpu_execution_policy.h>
Identifies a logical processor by a stable operating-system identifier.
Identifiers must come from the process-visible CPU set and are never inferred from adjacency. The wrapper keeps the vocabulary extensible without changing every call site.
Public Functions
-
bool operator==(const CpuLogicalProcessor&) const = default#
-
bool operator==(const CpuLogicalProcessor&) const = default#
-
struct ResolvedCpuExecutionPolicy#
- #include <cpu_execution_policy.h>
Immutable resolution of a :cpp:class:
CpuExecutionPolicy.The resolution describes the workers that actually execute the graph. It is derived deterministically from the request and the process-visible topology.
Public Functions
-
bool operator==(const ResolvedCpuExecutionPolicy&) const = default#
Public Members
-
CpuExecutionPolicy request#
The request this resolution was derived from.
-
uint32_t effective_threads = 1#
Effective number of participants, including the calling thread. Always
>= 1.
-
std::optional<CpuLogicalProcessor> caller_processor#
Explicit calling-participant assignment, absent when the caller is not pinned by this policy.
-
std::vector<CpuLogicalProcessor> worker_processors#
Explicit worker processor assignment, empty when no pinning is applied. Its size is at most
effective_threads - 1.
-
bool uses_smt = false#
Whether the resolution relies on SMT siblings.
-
bool uses_efficiency_cores = false#
Whether the resolution relies on efficiency cores.
-
ResolvedSpinPolicy spin#
Resolved spin and park policy.
-
bool allow_nested_parallelism = false#
Allows nested regions to use idle workers within effective_threads.
-
bool operator==(const ResolvedCpuExecutionPolicy&) const = default#
-
struct ResolvedSpinPolicy#
- #include <cpu_execution_policy.h>
Immutable resolution of a spin policy.
Exactly one of :cpp:var:
iterationsand :cpp:var:duration_nsis non-zero for the fixed policies; both are0for the park-immediately policy.Public Functions
-
bool operator==(const ResolvedSpinPolicy&) const = default#
Public Members
-
CpuSpinPolicy policy = CpuSpinPolicy::kAdaptive#
Resolved spin policy class.
-
uint64_t iterations = 0#
Resolved spin iterations before parking, or
0when not iteration-based.
-
uint64_t duration_ns = 0#
Resolved spin duration in nanoseconds before parking, or
0when not duration-based.
-
bool operator==(const ResolvedSpinPolicy&) const = default#
-
enum class CpuSpinPolicy#
-
namespace runtime
-
namespace core
CPU executor#
Shared CPU executor and compatible-pool registry.
-
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
Typedefs
-
using ParallelRangeFn = void (*)(void*, int64_t, int64_t)#
Type-erased range callable:
function(context, begin, end).
-
using CpuParallelBlockFn = void (*)(void*, int64_t)#
Type-erased block callable used by an external CPU dispatcher.
-
using CpuParallelDispatchFn = void (*)(void *dispatch_context, int64_t num_blocks, void *block_context, CpuParallelBlockFn block_function)#
Dispatches indexed blocks through an externally owned worker pool.
The callback must synchronously invoke
block_function(block_context, i)exactly once for everyiin[0, num_blocks)before returning.
Functions
-
CpuExecutorKey MakeCpuExecutorKey(const ResolvedCpuExecutionPolicy &policy)#
Returns the immutable sharing key for a resolved policy.
Returns: The behavior-only executor key.
- Parameters:
policy – The resolved CPU policy.
-
CpuExecutor *CurrentCpuExecutor() noexcept#
Returns the executor installed on the calling thread.
A session installs its leased executor for the duration of a run so portable helpers dispatch through it instead of a hidden process-wide pool.
Returns: The installed executor, or
nullptrwhen the thread runs outside any executor scope.
-
CpuExecutorRegistry &GlobalCpuExecutorRegistry()#
Returns the process-wide executor registry.
Returns: The bounded process-owned registry.
Variables
-
constexpr size_t kDefaultCpuExecutorRegistryCapacity = 8#
Default maximum number of simultaneously live executor pools.
-
class CpuExecutor#
- #include <cpu_executor.h>
Executes range work on one caller and a persistent set of workers.
Instances are obtained from :cpp:class:
CpuExecutorRegistry. Concurrent regions sharing an executor serialize dispatch metadata while their surrounding inference calls remain independent. Nested regions execute inline by default. Withallow_nested_parallelism, they may admit idle workers from this same pool, never exceeding its effective participant limit. Admission does not wait for busy workers; a saturated pool therefore executes nesting inline.Public Functions
-
CpuExecutor(const CpuExecutor&) = delete#
-
CpuExecutor &operator=(const CpuExecutor&) = delete#
-
~CpuExecutor()#
-
uint32_t effective_threads() const noexcept#
Returns the effective participant count, including the caller.
-
const ResolvedCpuExecutionPolicy &policy() const noexcept#
Returns the immutable resolved policy.
-
const CpuExecutorKey &key() const noexcept#
Returns the immutable registry-sharing key.
-
uint64_t instance_id() const noexcept#
Returns the process-local identity of this executor instance.
Compatible sessions that share one lease observe the same identifier. The identifier is diagnostic only and must not be persisted as a tuning or cache key.
-
void EnableCounters()#
Enables optional dispatch counters. Repeated calls preserve existing counts.
-
bool counters_enabled() const noexcept#
Returns whether optional dispatch counters are enabled.
-
CpuExecutorCounters counters() const noexcept#
Returns a consistent snapshot of the optional dispatch counters.
-
CpuParallelPlan PlanParallelFor(int64_t total, const CpuLoopCost &cost, uint32_t maximum_participants = 0) const noexcept#
Plans a loop from its per-iteration memory and compute cost.
The model compares serial execution with warm-pool dispatch, divided loop work, and coordination for each additional participant. It also chooses a task grain large enough to keep dispatch overhead bounded.
maximum_participants == 0uses the session limit.
-
CpuParallelPlan PlanParallelFor(int64_t total, const CpuLoopCost &cost, const CpuParallelConstraints &constraints) const noexcept#
Plans a loop with explicit kernel participant constraints.
-
void ParallelFor(int64_t total, int64_t minimum_elements, void *context, ParallelRangeFn function, uint32_t maximum_participants = 0, ParallelRegionCollector *collector = nullptr, std::string_view label = {}, std::source_location location = std::source_location::current())#
Executes contiguous ranges covering
[0, total).maximum_participants == 0uses the session limit. A positive value may lower but never raise that limit. Work belowminimum_elements, single-iteration work, and work with only one available participant run inline. Executors inherited acrossforkare rejected.- Parameters:
total – Number of iterations. Values
<= 0are a no-op.minimum_elements – Minimum iterations required for parallel execution. Must be positive.
context – Opaque context passed to
function.function – Range callback, which must not throw.
maximum_participants – Optional kernel-specific participant limit.
-
void ParallelFor(int64_t total, const CpuLoopCost &cost, void *context, ParallelRangeFn function, uint32_t maximum_participants = 0, ParallelRegionCollector *collector = nullptr, std::string_view label = {}, std::source_location location = std::source_location::current())#
Executes a loop using :cpp:func:
PlanParallelFor.
-
void ParallelFor(int64_t total, const CpuLoopCost &cost, void *context, ParallelRangeFn function, const CpuParallelConstraints &constraints, ParallelRegionCollector *collector = nullptr, std::string_view label = {}, std::source_location location = std::source_location::current())#
Executes a cost-aware loop with explicit kernel participant constraints.
Public Static Functions
-
static std::unique_ptr<CpuExecutor> CreateExternal(uint32_t maximum_participants, CpuParallelDispatchFn dispatch)#
Creates an executor that delegates parallel blocks to an external worker pool.
The executor never creates worker threads.
maximum_participantslimits the number of blocks submitted for one region and must be positive. The dispatcher must remain valid until the returned executor is destroyed. Each invocation supplies its transient dispatcher context through :cpp:class:CpuExecutorDispatchScope.Returns: An executor backed by
dispatch.
Private Functions
-
explicit CpuExecutor(ResolvedCpuExecutionPolicy policy)#
-
CpuExecutor(ResolvedCpuExecutionPolicy policy, CpuParallelDispatchFn dispatch)#
Friends
- friend class CpuExecutorRegistry
-
CpuExecutor(const CpuExecutor&) = delete#
-
struct CpuExecutorCounters#
- #include <cpu_executor.h>
Snapshot of optional executor dispatch counters.
Public Functions
-
bool operator==(const CpuExecutorCounters&) const = default#
Public Members
-
uint64_t dispatches = 0#
Number of ParallelFor dispatches, including inline dispatches.
-
uint64_t nested_inline_dispatches = 0#
Number of dispatches that ran inline because they were nested.
-
uint64_t limited_inline_dispatches = 0#
Number of dispatches that ran inline for size or participant limits.
-
bool operator==(const CpuExecutorCounters&) const = default#
-
class CpuExecutorDispatchScope#
- #include <cpu_executor.h>
Installs the transient context used by an external executor dispatch.
The binding is thread-local, composes across nested scopes, and does not own either pointer. It separates an invocation-specific runtime context from the persistent :cpp:class:
CpuExecutor.Public Functions
-
CpuExecutorDispatchScope(CpuExecutor *executor, void *dispatch_context) noexcept#
-
CpuExecutorDispatchScope(const CpuExecutorDispatchScope&) = delete#
-
CpuExecutorDispatchScope &operator=(const CpuExecutorDispatchScope&) = delete#
-
~CpuExecutorDispatchScope()#
-
CpuExecutorDispatchScope(CpuExecutor *executor, void *dispatch_context) noexcept#
-
struct CpuExecutorKey#
- #include <cpu_executor.h>
Identifies every resolved property that changes executor behavior.
Request spelling and diagnostics are intentionally excluded. The key records whether no affinity was explicitly requested so that a successful no-affinity policy is not confused with an unsupported affinity fallback.
Public Functions
-
bool operator==(const CpuExecutorKey&) const = default#
Public Members
-
uint32_t effective_threads = 1#
Effective participants, including the caller.
-
std::optional<CpuLogicalProcessor> caller_processor#
Optional caller placement.
-
std::vector<CpuLogicalProcessor> worker_processors#
Exact worker placement, or an empty vector for unpinned workers.
-
ResolvedSpinPolicy spin#
Resolved spin-before-park behavior.
-
bool explicit_no_affinity = false#
Whether the request explicitly selected no affinity.
-
bool allow_nested_parallelism = false#
Whether nested parallelism was requested.
-
bool operator==(const CpuExecutorKey&) const = default#
-
class CpuExecutorRegistry#
- #include <cpu_executor.h>
Leases compatible shared executors from a process-owned bounded registry.
The registry retains multithreaded executors so compatible sessions reuse the same operating-system threads. Bounded spinning ends in a parked wait, so an idle retained executor eventually consumes no CPU regardless of its spin policy. Idle executors are evicted when the bounded capacity is needed for another policy. Serial executors have no workers and are not retained.
Public Functions
-
explicit CpuExecutorRegistry(size_t capacity)#
Creates a registry with a strict live-pool capacity.
-
CpuExecutorRegistry(const CpuExecutorRegistry&) = delete#
-
CpuExecutorRegistry &operator=(const CpuExecutorRegistry&) = delete#
-
std::shared_ptr<CpuExecutor> Acquire(const CpuExecutionPolicy &request)#
Resolves and acquires an executor for
request.
-
std::shared_ptr<CpuExecutor> Acquire(const ResolvedCpuExecutionPolicy &policy)#
Acquires an executor for an already resolved policy.
-
inline size_t capacity() const noexcept#
Returns the configured maximum number of simultaneously live pools.
-
size_t live_pool_count()#
Returns the number of live pools currently tracked.
Private Functions
-
void ResetAfterForkLocked(uint64_t process_id)#
-
void RemoveExpiredLocked()#
-
bool EvictIdleRetainedLocked()#
-
struct Entry#
Public Members
-
CpuExecutorKey key#
-
std::weak_ptr<CpuExecutor> executor#
-
std::shared_ptr<CpuExecutor> retained_executor#
-
CpuExecutorKey key#
-
explicit CpuExecutorRegistry(size_t capacity)#
-
class CpuExecutorScope#
- #include <cpu_executor.h>
Installs a non-owning executor view on the calling thread.
The previous view is restored when the scope ends, so nested scopes and subgraph executions compose. The scope does not extend the executor lifetime: the installer must keep its lease alive.
Public Functions
-
explicit CpuExecutorScope(CpuExecutor *executor) noexcept#
Installs
executor(possiblynullptr) on the calling thread.
-
CpuExecutorScope(const CpuExecutorScope&) = delete#
-
CpuExecutorScope &operator=(const CpuExecutorScope&) = delete#
-
~CpuExecutorScope()#
Private Members
-
CpuExecutor *previous_#
-
explicit CpuExecutorScope(CpuExecutor *executor) noexcept#
-
struct CpuLoopCost#
- #include <cpu_executor.h>
Describes the estimated work performed by one independent loop iteration.
Byte counts are exact logical traffic.
compute_cyclesis a relative estimate of arithmetic work, excluding loads and stores.Public Functions
-
bool operator==(const CpuLoopCost&) const = default#
-
bool operator==(const CpuLoopCost&) const = default#
-
struct CpuParallelConstraints#
- #include <cpu_executor.h>
Kernel constraints applied to a cost-model decision.
Public Functions
-
bool operator==(const CpuParallelConstraints&) const = default#
-
bool operator==(const CpuParallelConstraints&) const = default#
-
struct CpuParallelPlan#
- #include <cpu_executor.h>
Cost-model decision consumed by :cpp:class:
CpuExecutor.Public Functions
-
bool operator==(const CpuParallelPlan&) const = default#
-
bool operator==(const CpuParallelPlan&) const = default#
-
using ParallelRangeFn = void (*)(void*, int64_t, int64_t)#
-
namespace runtime
-
namespace core
Parallel-region diagnostics#
-
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
Enums
Functions
-
const char *HardwareCounterStatusName(HardwareCounterStatus status) noexcept#
Returns the stable lowercase name of a hardware-counter status.
-
std::optional<double> ComputeCpuUtilization(std::optional<uint64_t> process_cpu_time_ns, std::optional<uint64_t> wall_time_ns, int32_t observed_threads) noexcept#
Returns normalized process CPU utilization when all inputs are valid.
-
std::optional<uint64_t> ReadProcessCpuTimeNs() noexcept#
Returns aggregate process CPU time, or no value when the platform cannot provide it.
-
ParallelRegionCollector *CurrentParallelRegionCollector() noexcept#
Returns the non-owning collector installed on the calling thread.
-
uint64_t CurrentParallelRegionRunId() noexcept#
Returns the run identifier installed on the calling thread.
-
uint64_t CurrentParallelRegionId() noexcept#
Returns the active region identifier installed on the calling thread.
-
uint64_t NextParallelRegionId() noexcept#
Returns a new process-unique region identifier.
-
struct HardwareCounterMeasurement#
- #include <parallel_region_collector.h>
Opaque state returned when a grouped hardware-counter measurement begins.
Public Members
-
bool active = false#
-
bool active = false#
-
struct HardwareCounterSample#
- #include <parallel_region_collector.h>
Holds one grouped hardware-counter sample. Counts are present only when valid.
Public Members
-
class ParallelRegionCollector#
- #include <parallel_region_collector.h>
Collects parallel-region events in fixed storage without locking inference.
Storage is allocated once by the constructor. Concurrent writers reserve distinct slots atomically; events beyond
capacityincrement the dropped count. Readers must inspect events only when no inference is writing.Public Functions
-
explicit ParallelRegionCollector(size_t capacity, bool hardware_counters = false)#
Allocates storage and optionally enables Linux grouped hardware counters.
-
~ParallelRegionCollector()#
-
ParallelRegionCollector(const ParallelRegionCollector&) = delete#
-
ParallelRegionCollector &operator=(const ParallelRegionCollector&) = delete#
-
void Record(ParallelRegionEvent event) noexcept#
Records an event or increments the dropped count when storage is full.
-
HardwareCounterMeasurement BeginHardwareCounters() noexcept#
Starts one grouped measurement, or returns its explicit unavailable status.
-
HardwareCounterSample EndHardwareCounters(HardwareCounterMeasurement measurement, bool isolated = true) noexcept#
Stops and returns one grouped measurement, rejecting non-isolated regions.
-
inline size_t capacity() const noexcept#
Returns the configured event capacity.
-
std::span<const ParallelRegionEvent> events() const noexcept#
Returns the completed event slots. No inference may be writing concurrently.
-
inline uint64_t dropped_events() const noexcept#
Returns the number of events rejected after capacity was exhausted.
-
ParallelRegionReport Report() const#
Returns an owning snapshot that is independent of the collector storage.
-
explicit ParallelRegionCollector(size_t capacity, bool hardware_counters = false)#
-
class ParallelRegionCollectorScope#
- #include <parallel_region_collector.h>
Installs a non-owning collector and profiling identity for this scope.
Public Functions
-
explicit ParallelRegionCollectorScope(ParallelRegionCollector *collector, uint64_t run_id = 0, uint64_t region_id = 0) noexcept#
-
ParallelRegionCollectorScope(const ParallelRegionCollectorScope&) = delete#
-
ParallelRegionCollectorScope &operator=(const ParallelRegionCollectorScope&) = delete#
-
~ParallelRegionCollectorScope()#
Private Members
-
ParallelRegionCollector *previous_collector_#
-
uint64_t previous_run_id_#
-
uint64_t previous_region_id_#
-
explicit ParallelRegionCollectorScope(ParallelRegionCollector *collector, uint64_t run_id = 0, uint64_t region_id = 0) noexcept#
-
struct ParallelRegionEvent#
- #include <parallel_region_collector.h>
Describes one portable ParallelFor execution.
Public Members
-
uint64_t region_id = 0#
-
uint64_t parent_region_id = 0#
-
uint64_t run_id = 0#
-
int64_t total_iterations = 0#
-
int64_t grain_size = 0#
Minimum iterations assigned to a block.
-
int32_t requested_threads = 0#
-
int32_t admitted_threads = 0#
-
int32_t observed_threads = 0#
Number of distinct threads that executed blocks, not peak concurrency.
-
HardwareCounterSample counters#
-
uint64_t executor_instance_id = 0#
-
bool nested_inline = false#
-
uint64_t region_id = 0#
-
class ParallelRegionReport#
- #include <parallel_region_collector.h>
Immutable snapshot of bounded parallel-region profiling data.
Public Functions
-
ParallelRegionReport() = default#
-
inline const std::vector<ParallelRegionReportEvent> &events() const noexcept#
Returns the copied events in collector order.
-
inline uint64_t dropped_events() const noexcept#
Returns the dropped-event count captured with the snapshot.
Private Functions
-
inline ParallelRegionReport(std::vector<ParallelRegionReportEvent> events, uint64_t dropped_events)#
Friends
- friend class ParallelRegionCollector
-
ParallelRegionReport() = default#
-
struct ParallelRegionReportEvent#
- #include <parallel_region_collector.h>
Owns one event copied from a bounded parallel-region collector.
Public Members
-
uint64_t region_id = 0#
-
uint64_t parent_region_id = 0#
-
uint64_t run_id = 0#
-
uint_least32_t line = 0#
-
uint_least32_t column = 0#
-
int64_t total_iterations = 0#
-
int64_t grain_size = 0#
Minimum iterations assigned to a block.
-
int32_t requested_threads = 0#
-
int32_t admitted_threads = 0#
-
int32_t observed_threads = 0#
-
HardwareCounterStatus counter_status = HardwareCounterStatus::kDisabled#
-
uint64_t executor_instance_id = 0#
-
bool nested_inline = false#
-
uint64_t region_id = 0#
-
const char *HardwareCounterStatusName(HardwareCounterStatus status) noexcept#
-
namespace runtime
-
namespace core
Completion state#
-
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
Enums
-
class TaskCompletion#
- #include <task_completion.h>
Shares completion, cancellation, and failure state for runtime operations.
Public Functions
-
void MarkRunning() const#
Marks the task as running.
-
void Succeed() const#
Marks the task as successfully completed.
-
void Fail(std::exception_ptr error, std::string message = {}) const#
Marks the task as failed and preserves its exception for Wait().
-
void Suppress(TaskId caused_by, std::string message = {}) const#
Marks a pending task as suppressed by a failed dependency.
-
void Wait() const#
Waits for a terminal state and rethrows a task exception.
-
bool IsReady() const#
Returns whether the task has reached a terminal state.
-
TaskStatus status() const#
-
TaskDiagnostic diagnostic() const#
Private Static Functions
-
static bool IsTerminal(TaskStatus status)#
-
struct State#
-
void MarkRunning() const#
-
struct TaskDiagnostic#
- #include <task_completion.h>
-
class TaskCompletion#
-
namespace runtime
-
namespace core
Bounded fork/join#
-
namespace onnx_threads#
Functions
-
void ForkJoin(void *left_context, void (*left)(void*) noexcept, void *right_context, void (*right)(void*) noexcept, bool parallel) noexcept#
Executes two non-null, non-throwing operations and waits for both to finish.
When parallel is true, admits one asynchronous worker within the shared hardware-concurrency budget. A saturated budget or a failed worker launch executes both operations inline. Contexts remain borrowed until return.
-
void ForkJoin(void *left_context, void (*left)(void*) noexcept, void *right_context, void (*right)(void*) noexcept, bool parallel) noexcept#