Skip to content
API REFERENCEUsage guides →

Training DataLoader API ​

python
from pycellpack import Accesses, ScDataset, ScDataLoader

These interfaces produce owned Tensor batches from corpus-local sample orders. For a complete program and checked output, read training batches. For NumPy ring views and global cell IDs, use the separate native Loader.

Dataset and sample declarations ​

ScDataset ​

ScDataset(store, *, ids) pairs a 2-D file-backed Store view with one standard ID per visible column. It keeps the Store and copies the ID map to read-only uint32 storage. Keep the backing file immutable while using the loader.

InputRequirement
storeIts decode dtype equals its file dtype; memory streams are rejected
idsOne-dimensional NumPy integer array of length store.shape[1]
Kept IDsDistinct integers in [0, uint32.max) within this dataset
Dropped columns-1 or uint32.max
Store viewsRow selection and ordinary column subsets/reordering remain lazy; one stored column cannot contribute multiple kept dimensions

Rows in sample orders address this view. For store[[5, 2]], local row 0 means stored row 5. Choose output conversion on ScDataLoader rather than with Store.astype. ScDataset.from_anndata(adata, ids=..., layer=None) selects an existing Store from X or a named layer; it does not encode arrays or match names.

Corpus Accesses ​

Accesses(dataset_ids, rows) borrows two parallel 1-D NumPy integer arrays. The value object does not validate their contents. Starting an iterator copies them to uint32 dataset IDs and uint64 local rows, checks equal lengths and nonnegative ranges, and validates each pair against the corpus. Repeats and order are retained. The corpus's total contributed rows must fit uint32 CellIds.

len(accesses) counts samples. This is the package-root Accesses, distinct from native loader.Accesses, whose values are global cell IDs. ScDataLoader also accepts the tuple (dataset_ids, rows).

Construct a loader ​

Sampling and output ​

ParameterDefaultContract
corpusRequiredNonempty sequence of ScDataset objects; captured as a tuple
accessesNoneCorpus Accesses or its two-array tuple
access_fnNoneNative AccessFn; corpus counts are bound automatically; supply exactly one of accesses/access_fn
out_idsNoneNonempty distinct standard IDs below uint32.max, in output order; omission requires identical dataset maps and selects their kept IDs
processNoneProcessFn with declared OutputLayout; omission produces dense X
dtypeNonefloat32, or the ProcessFn's required input dtype; must be a supported native loader conversion
default0Typed fill for dimensions absent from a source; does not replace present sparse zeros
drop_lastFalseTrim incomplete final batch before execution

Preset token/configuration tables follow out_ids order. They do not use standard IDs as table offsets. Output fields with a process are declared by its OutputLayout.

Execution and memory ​

ParameterDefaultUnit / contract
batch_size256Positive samples per output slot; bool is rejected
prefetch4Positive host output slots; bool is rejected
workersNoneNative threads; automatic value is min(16, usable CPUs); explicit values bypass this automatic cap
cache_bytes0Nonnegative online input-cache budget; zero disables planning
scratch_bytes0Process scratch bytes per worker
backendNoneProbe io_uring, else pread; explicit "uring" or "pread"
direct_ioNoneProbe O_DIRECT; False forces buffered input I/O
**settingsEmptyIndividual LoaderConfig fields such as inflight, claim_batch, window, profile and cpus; config and slot_rows are rejected

Output prefetch, input cache and returned Tensor allocations are separate budgets. ScDataLoader derives native slot_rows from batch_size.

Tensor delivery ​

ParameterDefaultContract
device"cpu"CPU or CUDA PyTorch device, for example "cuda:0"
contiguousFalseTrue for all output fields, a field name or a sequence for selected fields; unknown names are rejected

Iteration returns dict[str, torch.Tensor]. Built-in X has shape (actual_batch_rows, len(out_ids)); process field shapes have batch rows prefixed. CPU outputs own a packed clone and may be retained without holding native ring slots. CUDA outputs own device storage after one packed H2D transfer. The copy stream completes before host views are released. Field views may be strided; selected fields or misaligned field layouts can require copies. Device field-copy streams establish dependencies with the current CUDA stream before return.

Iteration, epochs and completion ​

OperationBehavior
len(loading)Batch count for the current order; does not start workers, import Torch or validate sample bounds
iter(loading)Copies/validates an array order or binds its AccessFn, imports Torch, creates a fresh ring/run and resets stats to None
loading.out_idsRead-only output-panel view
loading.statsNone before the first run or during a new run; final RunStats on exhaustion, progress snapshot after early close
loading.close()Closes the active iterator; another run can be started afterward
with loading:Closes the active iterator on exit, including break and exception paths

Only one iterator may be active. The caller owns epoch policy: replace loading.accesses or loading.access_fn between runs. Every iterator starts from the beginning of that supplied order; there is no implicit reshuffle or resume offset. Use a sliced order to resume. Do not mutate corpus or output configuration after construction.

Failures and validation timing ​

FailureWhere to look
TypeError / ValueError during constructionCorpus, Store, ID maps, panel, process output declaration or execution settings
TypeError / ValueError on iterator startSample array shapes/types, dataset indices or dataset-local rows
RuntimeError for a second iteratorExhaust or close the active iterator first
ModuleNotFoundError naming torchInstall PyTorch separately before iteration
I/O or native worker error during iterationSource file state, backend, process callback and native error cause

Completed Tensor batches retain independent storage after early close. A progress snapshot is not a success receipt for the full order; only normal exhaustion collects the final statistics.

Declarations ​

Complete declarations and members

ScDataset ​

python
ScDataset(store: Store, *, ids: np.ndarray)

A two-dimensional Store and one explicit standard id per visible dim.

ids must be a NumPy integer vector. -1/uint32.max drops a dim; other ids must be distinct. Rows address this Store's current view. Ordinary column subsets/reorderings stay lazy. Multiple mapped dims referring to the same stored column and dtype-converting Store views are rejected explicitly.

ScDataset.from_anndata ​

python
ScDataset.from_anndata(adata, *, ids: np.ndarray, layer=None)

Select X (layer=None) or a layer already holding a Store.

This convenience imports no AnnData and never compresses a matrix implicitly. H5CP's read_h5(..., lazy=True) preserves these Stores.

ScDataset.store ​

store: Store — property.

The immutable Store view supplied for this dataset.

ScDataset.ids ​

ids: np.ndarray — property.

Read-only uint32 standard IDs, one per visible column; uint32.max marks a dropped dimension.

ScDataset.shape ​

shape — property.

Visible (rows, columns) of the dataset view.

ScDataset.dtype ​

dtype — property.

Stored numeric dtype. Loader output conversion is configured separately.

Accesses ​

Parallel arrays of corpus dataset indices and dataset-local rows.

The caller owns ordering, sampling and epoch policy. Arrays are borrowed by this value object and snapshotted when a loader iterator starts.

Fields and defaults ​

python
dataset_ids: np.ndarray
rows: np.ndarray

ScDataLoader ​

python
ScDataLoader(corpus: Sequence[ScDataset], accesses=None, *, access_fn: AccessFn | None=None, out_ids: np.ndarray | None=None, process: ProcessFn | None=None, batch_size=256, device='cpu', prefetch=4, cache_bytes=0, workers=None, dtype=None, default=0, scratch_bytes=0, drop_last=False, contiguous=False, backend=None, direct_io=None, **settings)

Iterate named Tensors while native workers supply a bounded packed ring.

corpus is an ordered list of ScDatasets; dataset ids are its indices. accesses accepts Accesses or (dataset_ids, rows). Alternatively access_fn takes a native AccessFn. Supply exactly one; the caller owns sampling, ordering and epoch policy.

out_ids defines the common mapped panel, in ProcessFn table order. It can be omitted for datasets with identical standard ids. process outputs require a declared OutputLayout; without process the output is dense X. Torch is imported only by iteration, never by construction or len().

prefetch is the number of host output slots; workers are native threads. CUDA uses one packed H2D and returns field views; contiguous=True or a sequence of field names requests field copies on independent CUDA streams. CPU batches own their storage and may be retained without blocking a slot.

ScDataLoader.out_ids ​

out_ids — property.

Read-only standard IDs in model output order.

ScDataLoader.close ​

python
ScDataLoader.close()

Close this loader's active iterator; the loader can be reused.