Skip to content
API REFERENCEUsage guides →

Training data delivery: loader ​

cellpack::loader binds immutable matrix sources to output schemas, evaluates the application's access sequence, and produces ordered batches into a bounded ring. It owns read/decode/map/process scheduling. It does not own sampling policy, distributed process creation, model execution, or GPU transfer completion.

Find the contract for your task ​

Follow one boundary at a time

For an end-to-end program, use loading and ownership. This page collects argument, identity and lifecycle rules; the interface index at the end provides exact declarations and member links.

Public object model ​

ObjectResponsibilityInput → output
DataSourceBuilderRegister streams and compose column identitiesFiles + source-to-standard maps → source
DataSourceImmutable catalog and metadata shared by planner/workersGlobal cell → input location and shape metadata
OutputSchemaDeclare one delivery's panel, dtype, default and record sizeMapped input → dense vector or process record
AccessesDefine deterministic cell selectionAccess index → global CellId
LoaderBind source, schemas and execution configurationAccesses + ring + planning → prepared run
RunOwn the producer lifecycleConcurrent production/consumption → final statistics
RingLayout / RingDescribe/own shared bounded outputSlot layout → reusable leased storage
Batch / BatchLeasePrevent slot overwrite while readingCompleted slot → valid per-schema byte regions
ProcessFnTransform one mapped rowCSR/dense ABI row → fixed-size native record

Source registration ​

DataSourceBuilder::new(vocab, page_size) requires a positive standard vocabulary below u32::MAX and a supported power-of-two page size. direct_io(enabled) configures record-file opening. add_cpk(path, to_std) and add_cpk_region(path, offset, length, map) return a matrix index. Every map entry is a distinct in-range standard id or UNMAPPED. The map length equals the stored column count, and all streams use the same page size. build consumes the builder and returns a source.

DataSource queryReturn and units
n_cells / n_pages / n_matrices / vocabCounts in their respective global spaces
matrix_cells(matrix)Optional first global CellId and u64 row count
matrix_dtypesStored dtype per registered matrix
page_size / max_cell_pagesBytes per page / maximum pages covering a record
resident_metadata_bytesKnown resident metadata allocation estimate
fingerprint / mapping_fingerprintCompatibility identities, not cryptographic integrity proofs
cell_pagesBorrowed file descriptor, aligned byte offset and page count
cell_bytesBorrowed file descriptor, exact record byte offset and length

Descriptors remain owned by the source; do not close them. Keep the source and input files alive and immutable while using returned locations.

Schemas and conversion ​

OutputSchema::dense(id, out_ids, dtype) fixes dense output width to out_ids.len() × dtype.width(). OutputSchema::process(id, out_ids, dtype, cell_bytes, process, identity, scratch_bytes) fixes a custom record size independent of input-panel width.

DeclarationContract
idUnique schema id within a loader
out_idsNonempty distinct standard ids, in output order
dtypeInput is converted to this type before built-in delivery or callback
cell_bytesPositive fixed bytes per cell; dense built-in size is derived
identityVersions custom callback behavior and retained configuration
scratch_bytesPrivate scratch available to a process call
with_default / with_default_bytesSets missing dimensions only; present omitted values remain zero
namedHuman-readable reporting label, outside plan identity

Schema accessors expose these settings and is_builtin / row_format / process_fn. The loader checks source-to-output conversion with allowed; its policy differs from unrestricted low-level casts. See dtype compatibility.

Access sequences and native access ABI ​

InterfaceInputResult and constraints
Vec / slice / array / Box / Arc implementationsStored global idsBorrowed or owned fixed sequence
Shuffle::new / subsetCell range or subset, epochs, seedRandom-access epoch permutations
Shuffle::blocksBlock size, group sizeAdds locality to generated ordering
Replicate::newPer-position sequence, schema countSame cell for every schema
Offset::newBase sequence, per-schema offsetsPaired global cells; checked addition
SliceAccesses::newArc<dyn Accesses>, start, lengthBounded interval without copying values
Unsafe ExternAccesses::newAccessFn, context, lengthNative generator of global ids
Unsafe ExternCorpusAccesses::newCorpusAccessFn, context, length, dataset countsNative dataset/local-row pairs translated into global ids

Accesses::fill(start, out) must fill exactly the requested range. Calls can be concurrent, out of order, and repeated; values depend only on the index and immutable configuration. Length must be divisible by the schema count.

For S schemas and N positions, the sequence contains N × S IDs. Access k supplies schema index k % S at position k / S. OutputSchema::id does not change this order. For two schemas, [3, 8, 0, 5] delivers cells [3, 0] to region 0 and [8, 5] to region 1. With slot_cells=2, that is one batch with two rows and two output regions.

AccessFn(context, start, count, out_cells) writes count global u32 ids. CorpusAccessFn(context, start, count, out_datasets, out_rows) writes u32 dataset indices and u64 local rows. Dataset counts must match registration order. Callbacks return zero on success; nonzero becomes Error::Accesses. Code and raw context outlive the sequence, tolerate concurrency, and retain no output pointers. Rust wrappers do not automatically own a foreign context.

Loader and run lifecycle ​

MethodInputsReturn and behavior
Loader::newArc<DataSource>, schemas, LoaderConfigImmutable bound loader; validates graph and conversions
ring_layoutSlot count, world sizeLayout derived from schema byte sizes and slot positions
prepareBorrowed Accesses, Arc<Ring>, PlanningBorrowing Run; checks files, layout, count and plan binding
Run::runPrepared runProducer execution on calling thread; returns RunStats
Run::waitRank and batch indexResult<Option<BatchLease>>; none past sequence end
Run::for_each_batchBorrowed-batch callbackScoped producer plus ordered local consumption of all ranks
Run::snapshotActive runPublished, potentially lagging statistics
Run::cancelActive/prepared runWakes parties and aborts further production
batches / generation / ringRunBatch count, run identity and ring handle

A run borrows the loader and sequence. One run holds a loader at a time; drop it before preparing another, even after run() succeeds. prepare does not launch workers. Run::run may execute once; subsequent attempts return Busy.

Production and consumption must overlap once a sequence can fill the ring. for_each_batch provides this overlap and joins its producer on success or failure. For a custom consumer, call wait(rank, b) only for batches owned by that rank, in increasing order, while another thread executes run().

cancel() permanently aborts this run's ring; it cannot be reused afterward. Dropping an unstarted run cancels it too. A failed run's output is incomplete and cannot be treated as success. Reuse after success additionally requires all ready batches consumed and all leases released.

Planning-related methods plan_options, compile, replay, replay_with_cost, compile_online, plan_online, online are described in opt. memory_estimate_for describes a particular planning mode; a cache budget alone does not bound total process memory.

Ring layout and ownership ​

Constructor/familyMemory modelCaller obligation
Ring::allocateRust-owned control and dataRetain ring through consumers
Unsafe init / attachExternal contiguous storageStable owner, alignment, capacity and protocol
Unsafe init_regions / attach_regionsSeparate control and dataCorrect independent regions, no overlap
Unsafe with_bufferExternal data with private controlStable data owner and compatible layout

RingLayout stores slots, positions per slot, world, and per-schema cell bytes. bytes, control_bytes, data_bytes, data_min_bytes, slot_stride, regions report checked sizes/offsets. Control alignment is 64 bytes; region starts are 64-byte aligned; slot stride and contiguous storage use 4096-byte alignment.

Batch b occupies slot b % slots and belongs to rank b % world. All schemas and positions of a slot must finish before it is ready. Ring::wait yields a borrowed Batch; acquire / acquire_generation yield an owned BatchLease; acquire_timeout returns Batch, Pending, or Done.

region(s) exposes exactly rows() × cell_bytes(s) bytes. data() can include padding and unused tail space. Drop/release the lease only after all readers finish. A ring can serve another run after its previous slots and leases are released; an aborted ring cannot. Participant methods and headers are advanced shared-process protocol interfaces, not process-launching utilities.

Process function ABI ​

ProcessFn::new binds both CSR and dense callbacks in Auto. with_format requires only callbacks needed by forced Csr or Dense. Both auto callbacks must compute equivalent outputs. Each sees already mapped columns and values converted to the schema dtype.

ProcessContext identifies ABI version, row struct size, logical position, global cell, schema index, dtype code and user data. CsrRow has element count, columns, values, output and scratch; columns are not necessarily sorted after mapping. DenseRow supplies a full panel including missing-dimension defaults.

Callbacks initialize the fixed output record, write only owned output/scratch, are concurrent-safe, retain no input pointer, and never unwind across the C ABI. Nonzero status becomes Error::Process. Unsafe with_partial_rows additionally requires handling null value/column pointers through a call-local resolver and valid element positions. See ProcessFn details for the complete callback contract.

Configuration, statistics, and failures ​

Performance lists every LoaderConfig default and its units. IoBackend::Uring requires io_uring support; choose Pread explicitly otherwise. Counters are always on; RunStats combines event, I/O, per-schema and optional profile/online reports. The generated pages below enumerate every field.

Configuration errors, invalid cells, I/O, incompatible plans, callback statuses, worker panics, busy state, and cancellation have distinct error variants. A secondary Aborted can be the consequence of another participant's original error.

Complete interface index ​

Declarations and member links by interface

Re-exports ​

InterfaceResponsibility
DtypeNumeric type of a matrix’s values; its width is the chunks’ value width.

Structs ​

InterfaceResponsibility
BatchBorrowed slot lease. Output references cannot outlive this guard.
BatchLeaseOwned slot lease, suitable for foreign-runtime array base objects.
CountersEvent counts every run keeps.
CsrRowA CSR row: nnz stored elements with output columns in the chunk’s coded order (not sorted) and values of the schema’s dtype. Every other output dim is a zero or missing (see the module notes). A dense record delivered as a CSR row lists its non-zeros.
DataSourceEvery input matrix, numbered by global cell id, with each matrix’s map from its columns to the standard ids (the data side of the panel). Shared by planner and workers.
DataSourceBuilderRegisters matrices one at a time, then composes them into a DataSource .
DenseRowA dense row: out_dim values of the schema’s dtype: the stored value or 0 at present dims, the schema’s default at missing dims (see the module notes).
ExternAccessesA sequence computed by a native function.
ExternCorpusAccessesA native corpus generator bound to the registered datasets’ row counts.
IoStatsRead statistics of one worker, summed over workers in RunStats .
LoaderOne data source and the schemas that output its cells, ready to serve runs.
LoaderConfigHow a loader’s runs execute: threads, I/O backend, windowing and profiling.
MemoryEstimateBytes a run reserves, by purpose. Each term is a known reservation, not a measured footprint: allocator overhead, the compiler’s own state and the OS page cache are outside it, and reserved bytes need not be resident.
OffsetSchema s of a position loads the position’s cell plus offsets[s] .
OutputSchemaOne output: its dims as standard ids, the element type and size of a cell, and either the built-in dense row or a process function.
OutputStatsCounts of one schema’s outputs.
ProcessContextWhat every process call learns about itself: which cell, which schema, and the caller’s user_data .
ProcessFnA schema’s callbacks: both for RowFormat::Auto , one for a forced format.
ReplicateEvery schema of a position loads the position’s cell: inner names one cell per position, the sequence has schemas accesses per position.
RingA bounded ring over owned or caller-provided memory: the slot protocol and the participant bookkeeping that keep one producer and world consumer ranks apart.
RingHeaderThe ring’s header, at the start of control memory: geometry, the current run, and per-schema region offsets and cell sizes.
RingLayoutSlots of positions, each holding every schema’s region. A slot’s remaining output counter is a u32 , so slot_cells × schemas must fit in one.
RunA prepared run: the loader bound to an access sequence, a ring and its planning mode.
RunStatsA run’s statistics: event counts, I/O counts, per-schema counts, the bytes it reserved and, if it profiled, the recorded sites.
ShuffleEpochs of shuffled cells: each epoch visits every position (or every entry of a subset) once, in its own pseudorandom order. With blocks, an epoch shuffles blocks of consecutive cells, and shuffles cells within each group of consecutive (shuffled) blocks: local reads, as from chunked shuffle buffers.
SliceAccessesA bounded interval of another computed or stored access sequence.
SlotHeaderOne slot’s header, on its own cache line: which batch it holds, its state and how many of its outputs are still unwritten.

Enums ​

InterfaceResponsibility
AcquisitionOutcome of a bounded owned-lease acquisition.
ConversionCost classes of conversions, as the cost model prices them.
ErrorA loader failure.
IoBackendHow a worker reads: the platform’s asynchronous ring, or blocking preadv.
PlanningHow a run caches.
RowFormatThe row format a process function receives.

Constants ​

InterfaceResponsibility
CONVERSIONSClasses in Conversion ’s numbering; the cost model’s table size.
MAX_SCHEMASMost schemas one loader outputs.
PROCESS_ABI_VERSIONThe process ABI the loader implements: the layout of ProcessContext , CsrRow and DenseRow . A callback built against another version must not be passed to ProcessFn .
PROCESS_BOUNDSElement-count boundaries of the process site’s size bands; a call’s element count (output dims for a dense record, stored elements otherwise) belongs to the band below the first boundary above it.
REGION_ALIGNAlignment of each schema’s region within a slot.
SLOT_ALIGNAlignment of slots.

Traits ​

InterfaceResponsibility
AccessesA sequence of cells: a pure function from access index to CellId .

Functions ​

InterfaceResponsibility
allowedWhether values stored as s may be output as t : the same type, lossless widening, same-width signed to unsigned (negatives are not checked), signed to wider unsigned, and any integer to a float.

Type Aliases ​

InterfaceResponsibility
AccessFnfn(context, start, count, out) -> status : writes the cells of accesses start..start + count to out ; zero on success.
CellIdGlobal cell identity: matrices occupy consecutive ranges in registration order.
CorpusAccessFnFills dataset indices and dataset-local rows for an access interval. The output arrays have count entries and do not outlive the call.
CsrFnA CSR callback: returns 0 on success, any other value stops the run.
DenseFnA dense callback: returns 0 on success, any other value stops the run.
ResolveFnThe partial-row resolver a CsrRow carries: (row, positions, count, columns, values) -> status , writing count column/value pairs.
ResultThe loader’s result type.
SchemaIdA caller-chosen schema id; ids must be distinct within a loader and enter the plan fingerprint.
Definition