Expand description
EdgeFirst HAL - Tensor Module
The edgefirst_tensor crate provides a unified interface for managing multi-dimensional arrays (tensors)
across four memory backends: the platform’s native zero-copy GPU buffer, POSIX shared memory, the system
heap, and an OpenGL Pixel Buffer Object. The crate defines traits and structures for creating, reshaping,
and mapping tensors into memory.
§Examples
use edgefirst_tensor::{Error, Tensor, TensorMemory, TensorTrait};
let tensor = Tensor::<f32>::new(&[2, 3, 4], Some(TensorMemory::Mem), Some("test_tensor"))?;
assert_eq!(tensor.memory(), TensorMemory::Mem);
assert_eq!(tensor.name(), "test_tensor");§Overview
The main structures and traits provided by the edgefirst_tensor crate are TensorTrait and
TensorMapTrait, which define the behavior of Tensors and their memory mappings, respectively.
The Tensor<T> struct wraps a backend-specific storage with optional image format metadata
(PixelFormat); mapping a tensor yields a HostView, which implements
TensorMapTrait and derefs to the underlying elements. The
TensorDyn type-erased enum wraps Tensor<T> for runtime element-type dispatch.
TensorMemory::DmaBuf is one variant with three implementations behind it — a Linux DMA-heap DMA-BUF,
a macOS/iOS IOSurfaceRef, or an Android AHardwareBuffer. Callers ask for Dma and get whichever
the platform provides, so portable code never branches on the mechanism.
§Image tensors
Images go through Tensor::image (or Tensor::image_desc for the full-featured request) rather
than Tensor::new. Two things set them apart:
- They take a required
CpuAccessdeclaration. Hardware access — GPU, NPU, ISP, codec — is always implied; what the CPU intends is the one thing the allocator cannot guess. Mapping beyond the declaration is best-effort and always counted byunplanned_cpu_access_count. - DMA-backed images carry a 64-byte-aligned row stride in every layout, because Mali and Vivante
reject an EGLImage import at an unaligned pitch. Read the real pitch from
Tensor::effective_row_stride; don’t assumewidth * bpp.
Re-exports§
pub use colorimetry::ColorEncoding;pub use colorimetry::ColorRange;pub use colorimetry::ColorSpace;pub use colorimetry::ColorTransfer;pub use colorimetry::Colorimetry;pub use colorimetry::MatrixWeights;pub use colorimetry::RangeScaling;pub use blob::BlobError;pub use blob::BlobHeader;pub use blob::BlobPlane;pub use blob::BlobStrings;pub use blob::BlobView;pub use blob::Regions;pub use blob::TransportMode;pub use blob::HEADER_LEN;pub use blob::PLANE_RECORD_LEN;pub use lens::Element;pub use pin::HostPin;pub use protocol::dtype_to_dtype;pub use protocol::format as tensor_format;pub use protocol::format_from_code;pub use protocol::kind as tensor_kind;pub use protocol::SendPtr;pub use protocol::TensorDesc;pub use protocol::ABI_VERSION;pub use view::HostView;
Modules§
- blob
- The tensor blob: a size-prefixed, append-only serialization of a tensor.
- colorimetry
- Colorimetry metadata for image/video tensors.
- covguard
- Coverage-capture resilience for crash-on-shutdown hardware (e.g. the i.MX Vivante EGL driver SIGABRTs during teardown after tests pass). Under coverage instrumentation only, install a SIGABRT handler that flushes the LLVM profile to LLVM_PROFILE_FILE before the abort completes, then restores the default disposition and re-raises so the process exit status is unchanged (the CI workflow already treats JUnit as the source of truth).
- d3d11_
layout (PixelFormat, DType, width, height) -> D3D11 texture layout.- lens
Tensor<T>as a typed lens over [TensorDyn].- pin
- Persistent host mapping, decoupled from cache coherency.
- protocol
- The cross-package tensor protocol.
- view
- One CPU-access window, for every backend.
Macros§
- ef_
vocabulary - Declare a vocabulary once, emit every surface from it.
Structs§
- Bounding
Box - A bounding box with f32 coordinates in XYXY format
- Buffer
Identity - Unique identity for a tensor’s underlying buffer.
- Chroma
Layout - Chroma addressing parameters for a semi-planar (NV12/NV16/NV24) format —
the single source of truth shared by the codec writer, CPU readers, and the
Linux + macOS GL shaders. See
PixelFormat::chroma_layout. - Cuda
Handle - CUDA registration for a GPU-backed tensor. Held as
Optionon the tensor. - CudaMap
- Scoped CUDA device-pointer mapping.
Dropunmaps aGlBuffer(so GL may reuse the PBO for the nextconvert()call) and copies a writableD3d11mapping back into the texture.ExternalMemmappings are persistent —Dropis a no-op. - Detect
Box - A detection box with f32 bbox and score
- EfClient
State - Client-owned state a library entry point calls back into — frozen by value, forever, and reused verbatim by every domain that needs one (PBO today; CUDA-GL next).
- Image
Desc - Declarative image-allocation request — the full-featured front door
for image tensors (
TensorDyn::image_descand the image crate’sImageProcessor::create_image_desc). - Packed
Rgb888 Layout - Geometry of the RGBA8888 surface backing a packed RGB u8/i8 image tensor.
- Packed
Rgba16f Layout - Geometry of the RGBA16F-packed surface backing a planar F16 image tensor.
- PboClient
Parts - The C-ABI parts
ef_tensor_wrap_pbotakes, from aPboTensorat the origin of its buffer. - PboMapping
- Raw mapped pointer from a PBO. CPU-accessible while the buffer is mapped. The pointer is only valid between map and unmap calls.
- PboOps
Vtable Parts - The three parts of a [
PboOpsVtable], read out of a descriptor’sptror supplied directly by a C caller. - PboTensor
- A tensor backed by an OpenGL Pixel Buffer Object.
- Plane
Descriptor - Per-plane DMA-BUF descriptor for external buffer import.
- Plane
Geometry - Where one plane’s bytes physically live inside a tensor’s allocation.
- Proto
Data - Raw prototype data for fused decode+render pipelines.
- Quantization
- Quantization parameters for an integer tensor.
- Region
- A rectangular sub-region of a tensor’s leading spatial frame, in pixels.
- Segmentation
- A segmentation result paired with the normalized bounding box that
describes the spatial extent of
segmentation. - Tensor
- Multi-backend tensor with optional image format metadata.
- View
Origin - The parent image a
view/batchsub-region was carved from, snapshotted at the time the view was created. - f16
- Re-export of
half::f16so downstream crates can writeTensor::<edgefirst_tensor::f16>::from_iosurface(…)without addinghalfto their own dependency list. The version stays in lockstep with thehalfworkspace dep. A 16-bit floating point type implementing the IEEE 754-2008 standardbinary16a.k.a “half” format.
Enums§
- Compression
- Requested tile-compression behavior for an image allocation (set via
ImageDesc::with_compression). - Compression
Scheme - Vendor tile-compression schemes the HAL recognizes and records.
- CpuAccess
- Declared CPU involvement for an image tensor, chosen at allocation.
- DType
- Element type discriminant for runtime type identification.
- Error
- Identity
Kind - What kind of system key an identity was derived from. Participates in the id so that, say, inode 7 and IOSurfaceID 7 cannot collide.
- Pixel
Format - Pixel format identifier.
- Pixel
Layout - Memory layout category.
- Proto
Layout - Memory layout of the prototype tensor within
ProtoData. - Quant
Mode - Semantic mode discriminant for hot-path kernel dispatch.
- Tensor
Dyn - Type-erased tensor. Wraps a
Tensor<T>with runtime element type. - Tensor
Memory - Which memory backend a tensor is (or should be) allocated from.
Traits§
- Cuda
GlOps - Routes
cudaGraphicsMapResources/Unmap/Unregister through the GL worker thread (the GL context must be current there). Implemented by the image crate. - Integer
Type - Integer element types that may carry quantization metadata.
- PboOps
- Trait for PBO GL operations, implemented by the image crate.
- Tensor
MapTrait - Tensor
Trait - The operations every memory backend implements.
Functions§
- client_
state_ ⚠pbo_ ops - Build a live
PboOpsfrom a client’sEfClientStateand its two op functions — the one place the three parts are assembled, whether they arrived through acrate::TensorDescundercrate::protocol::kind::PBOor throughef_tensor_wrap_pbo’s arguments. - compression_
fallback_ count - Number of
Compression::Anyrequests since process start that resolved to a linear layout instead of a vendor tile scheme. A steady-state pipeline holds this flat after warmup; growth means an allocation path keeps requesting compression it never gets. - compression_
support - Whether this platform can allocate
(format, dtype)images in a vendor tile-compressed layout.truerequires an Android build, an eligible format (RGBA8888u8/i8initially), and a positively identified GPU vendor; everywhere else the answer isfalseandCompression::Anyrequests fall back to linear. - cuda_
runtime_ path - The runtime
load()opened, if any – seeCudaTable::runtime_pathfor what this points to on each platform.Noneiff no runtime loaded. - gl_
map_ resource - Map a registered resource →
(device ptr as usize, size). GL-thread only. - gl_
register_ buffer - Register a GL buffer (PBO) with CUDA. Returns the resource as
usize(pointer) orNone. MUST be called on the thread where the GL context is current. - gl_
unmap_ resource - Unmap a previously mapped resource. GL-thread only.
- gl_
unregister_ resource - Unregister a previously registered resource. GL-thread only.
- image_
dims_ from_ shape - The logical
(width, height)an allocation shape describes forformat– the inverse ofPixelFormat::allocation_shape. - is_
ahardwarebuffer_ available - Always returns
falseon non-Android platforms. - is_
cuda_ available - True iff libcudart loaded and all interop symbols resolved. Cached, cheap.
- is_
dma_ available - Check if Linux DMA-BUF allocation is available on this system.
- is_
gpu_ buffer_ available - Portable probe for the platform’s native zero-copy GPU buffer allocator
(DMA-BUF on Linux, IOSurface on macOS/iOS, AHardwareBuffer on Android,
D3D11 textures on Windows). Returns
falseon platforms with no equivalent. Use this when writing cross-platform code that cares whether theDmatensor variant will work, not which underlying mechanism is used. - is_
iosurface_ available - is_
shm_ available - Check if POSIX shared memory allocation is available on this system.
- memcpy_
device_ ⚠to_ host - Copy
countbytes from a CUDA device pointer to host. Returnsfalseon failure or if libcudart is unavailable. - memcpy_
host_ ⚠to_ device - Copy
countbytes from host to a CUDA device pointer. Returnsfalseon failure or if libcudart is unavailable. - packed_
rgb888_ layout - Geometry of the RGBA8888-packed surface backing a packed RGB u8/i8 image tensor.
- packed_
rgba16f_ layout - Canonical geometry for the RGBA16F-packed surface backing a planar F16 image tensor.
- read_
pbo_ ⚠vtable_ parts - Read a
crate::TensorDesc::ptr’s vtable into its parts, so a caller can hand them to a constructor rather than reassembling adyn PboOpsfirst. - stream_
create - Create a CUDA stream. Returns
Noneif libcudart is unavailable or stream creation fails. The returned stream must be released withstream_destroy. Intended for clients (e.g. the codec’s nvJPEG backend) that submit async device work and synchronise on it. - stream_
destroy ⚠ - Destroy a CUDA stream. No-op if libcudart is unavailable.
- stream_
synchronize ⚠ - Block until all work submitted to
streamcompletes. Returnsfalseon failure or if libcudart is unavailable. - unletter_
norm - Invert a letterbox: map a
BoundingBoxnormalized over the model input back to normalized-over-the-crop, given the content bounds[lx0, ly0, lx1, ly1]. The box is canonicalised first, a degenerate (zero-span) letterbox axis maps with unit scale (no divide-by-zero), and the result is clamped to[0, 1]. - unplanned_
cpu_ access_ count - Number of tensor maps that exceeded the buffer’s declared
CpuAccesssince process start. A pipeline that declares its CPU access correctly holds this flat; seeCpuAccessfor the contract.
Type Aliases§
- Cuda
Stream - EfPbo
MapFn - Map a PBO for CPU access.
0on success;-1when the GL context is gone; any other non-zero value a generic failure. - EfPbo
Unmap Fn - Unmap a PBO previously mapped by an
EfPboMapFn. Same return codes. - Foreign
Owner - Opaque keep-alive handle for a foreign-memory tensor (see
Tensor::from_foreign/TensorDyn::from_foreign_ptr). - Raw
- The C-facing handle pointer type. Declared in both backends with the same
name, so a
-capicrate’s signatures do not change with the backend. - Result