tensor_statistics.h#

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace core
namespace runtime

Typedefs

using TensorStatisticsProgressCallback = std::function<bool(TensorStatisticsPhase phase, int64_t completed, int64_t total)>#

Receives (phase, completed, total) synchronously on the calling thread.

Defaults to an empty callback, disabling notifications and callback-driven cancellation. Returning false cancels with std::runtime_error; callback exceptions propagate unchanged. Reductions and decoding report phase boundaries (0/1 and 1/1). Quantiles report distribution refinement passes for large FLOAT tensors, otherwise selected unique ranks, or 0/1 and 1/1 for constant FLOAT data. These are per-phase work units, not an overall percentage or a wall-clock estimate. Completion reports 1/1. Unneeded phases are omitted. Cancellation is cooperative between phases and selections: an individual reduction, refinement pass, decode or nth_element is not interrupted. The input is never mutated, and cancellation returns no partial statistics. Callbacks must not mutate the input.

Enums

enum class TensorStatisticsPhase#

Identifies the current standalone tensor statistics operation.

Values:

enumerator kDecode#
enumerator kSummary#
enumerator kMean#
enumerator kDistinct#
enumerator kHistogram#
enumerator kRectangle#
enumerator kQuantiles#
enumerator kComplete#

Functions

void ValidateTensorStatisticsOptions(int64_t bins, const std::vector<double> &quantiles, bool median, const std::vector<int64_t> &rectangle_shape, size_t max_output_bytes = kTensorStatisticsMaxOutputBytes)#

Validates options before allocating outputs or decoding input.

Charges bins*sizeof(int64_t) + (bins+1)*sizeof(double) for the histogram (50 bins when bins=0), rectangle_height*rectangle_width*sizeof(double), one double per requested quantile, and one double for the median when requested. Charges all requested outputs even when empty, small or nonfinite inputs would omit them. Rejects a combined payload exceeding max_output_bytes; callers may explicitly raise or lower the default 64 MiB budget. This is not a total-memory limit: input storage, decoding, input-dependent workspaces, vector capacity/metadata and binding copies are excluded.

TensorStatistics ComputeTensorStatistics(const Tensor &tensor, int64_t bins = 0, const std::vector<double> &quantiles = {}, bool median = false, const std::vector<int64_t> &rectangle_shape = {}, size_t max_output_bytes = kTensorStatisticsMaxOutputBytes, const TensorStatisticsProgressCallback &progress = {})#

Computes standalone numeric statistics; rejects strings, complex types and malformed storage.

Computes distinct_count for integer and boolean tensors only, using exact integer keys. A NaN propagates to min/max/mean and every requested quantile; otherwise infinities follow numeric ordering and IEEE arithmetic. Quantiles interpolate at q*(count-1), with exact endpoints preserved (including infinities).

Produces a histogram only for count >= 10, using finite values exclusively. Zero bins selects 50 bins for count > 500 and 10 otherwise. Constant finite data uses [value-0.5,value+0.5] where representable; extreme constants can have repeated edges. Bins are left-closed and right-open except the final bin, which includes the maximum. Uses arithmetic bin estimates when they agree with the exported edges, otherwise searches those edges to preserve exact boundary handling.

Resizes an optional rectangle using fractional-overlap area averages. Rank >= 2 becomes [first_dimension, product_of_remaining_dimensions]; scalars and vectors become [1,count]. Output is row-major with the requested positive [height,width], with no axis transposition. Nonfinite values propagate through the overlapping cells using IEEE arithmetic.

Validates all options even for empty tensors. Empty tensors return NaN min/max/mean, distinct_count=0 for integer/boolean tensors, no histogram or rectangle, one NaN per requested quantile, and NaN median only when requested. Rectangle metadata is empty when no map is produced. Applies ValidateTensorStatisticsOptions and its output budget before reading input. Large FLOAT tensors (count >= 32768, at most 128 unique requested ranks) reuse the histogram and refine selected bins exactly, with at most 8 MiB of private histogram counters and no tensor-sized selection copy. Other calls use a private FLOAT/DOUBLE/native 64-bit integer workspace (DOUBLE for other numeric types), selecting only requested ranks instead of sorting. Rectangle-only calls read the tensor directly without a full-size numeric copy.

TensorStatistics ComputeTensorStatistics(const RuntimeValue &value, int64_t bins = 0, const std::vector<double> &quantiles = {}, bool median = false, const std::vector<int64_t> &rectangle_shape = {}, size_t max_output_bytes = kTensorStatisticsMaxOutputBytes, const TensorStatisticsProgressCallback &progress = {})#

Computes tensor or encoded RuntimeValue statistics, rejecting structures and sequences.

Encoded values use DequantizeTensor (including shared parameter catalogues); numeric statistics describe reconstructed values, including distinct_count (signed zeros compare equal and NaNs count as one distinct value). Their dtype/shape describe the original logical tensor type, since encoded heterogeneous struct storage has no single tensor dtype/shape. size_bytes is the original encoded raw payload size, excluding schemas and separately shared parameters. Applies the same output budget before dequantizing input.

TensorStatistics ComputeTensorStatistics(const EncodedValueProto &value, int64_t bins = 0, const std::vector<double> &quantiles = {}, bool median = false, const std::vector<int64_t> &rectangle_shape = {}, const StructTypeCatalogue &catalogue = {}, size_t max_output_bytes = kTensorStatisticsMaxOutputBytes, const TensorStatisticsProgressCallback &progress = {})#

Computes encoded statistics, resolving named storage types through catalogue. Shared parameter references must first be materialized or use the RuntimeValue overload. Applies the same output budget before dequantizing input.

Variables

constexpr size_t kTensorStatisticsMaxOutputBytes = 64 * 1024 * 1024#

Default per-call budget for option-driven numeric output payloads (64 MiB).

struct TensorStatistics#
#include <tensor_statistics.h>

Holds numeric tensor statistics and original storage metadata.

Public Members

int32_t dtype = TensorProto::UNDEFINED#
std::vector<int64_t> shape#
size_t size_bytes = 0#
int64_t count = 0#
double min = std::numeric_limits<double>::quiet_NaN()#
double max = std::numeric_limits<double>::quiet_NaN()#
double mean = std::numeric_limits<double>::quiet_NaN()#
std::optional<int64_t> distinct_count#
std::vector<int64_t> distribution#
std::vector<double> bin_edges#
std::vector<double> quantiles#
std::optional<double> median#
std::vector<double> rectangle_map#
std::vector<int64_t> rectangle_shape#

Exact statistics on large tensors#

Quantiles retain linear interpolation at q * (count - 1) and the documented NaN/infinity behavior. The implementation deduplicates required ranks, including the median when Q2 is already requested.

For FLOAT tensors with at least 32768 elements and at most 128 unique requested ranks, it locates those ranks in the histogram already computed for the result. Only bins containing required ranks are refined, using three distributions over the order-preserving FLOAT bit keys (12, 10 and 10 bits). The final keys identify the exact stored values, not bin-center approximations. Infinities are accounted for separately, and signed zeros remain in the same initial histogram bin. Private histogram counters are bounded by 8 MiB independently of tensor size. No tensor-sized selection copy is allocated, even for concentrated distributions. Constant FLOAT data needs no refinement.

Other inputs recursively partition only relevant ranges with std::nth_element. For K requested ranks this takes average O(N log(K + 1)) work rather than sorting all N values. This fallback uses four bytes per FLOAT element, eight per DOUBLE or 64-bit integer element, and DOUBLE for other real types. No selection workspace is allocated without a quantile/median request or when the input contains NaNs.

Rectangle reduction reads the original tensor directly. The histogram reuses the summary’s finite bounds instead of scanning the input again. Input storage remains unchanged.

Progress and cancellation#

Each overload accepts an optional trailing TensorStatisticsProgressCallback after the output budget (and after the catalogue for encoded values). It defaults to {}, so existing calls need no callback and receive no notifications. The callback-free binary symbols are retained for existing SDK consumers.

const auto stats = onnx_light::core::runtime::ComputeTensorStatistics(
    tensor, 0, {0.25, 0.5, 0.75}, true, {32, 32});

To receive progress and enable cooperative cancellation:

namespace rt = onnx_light::core::runtime;
const auto stats = rt::ComputeTensorStatistics(
    tensor, 0, {0.25, 0.5, 0.75}, true, {32, 32},
    rt::kTensorStatisticsMaxOutputBytes,
    [&](rt::TensorStatisticsPhase phase, int64_t completed, int64_t total) {
        display_phase_progress(phase, completed, total);
        return !cancel_requested();
    });

Callbacks execute synchronously on the calling thread, never concurrently on worker threads. Decoding, summary, mean, distinct counting, histogram and rectangle report their start and end as 0/1 and 1/1. Unneeded phases are omitted. Large-FLOAT quantiles report 0/3 and one update after each refinement pass, or 0/1 and 1/1 when no refinement is needed. The selection fallback reports 0/K before copying the input, then one update per selected unique rank. Completion reports 1/1; an empty tensor reports only completion. These counts describe each phase, not global progress or elapsed-time estimates.

Returning false throws std::runtime_error with Tensor statistics cancelled.; exceptions from callbacks propagate unchanged. Cancellation is checked between phases and selections, not inside an individual decode, reduction, refinement pass or nth_element. No partial result is returned. The callback must not mutate the input tensor. Option and output-budget validation precede callbacks and decoding. The Python API continues to use the callback-free path.