Appearance
Training DataLoader API
python
from pycellpack import Accesses, ScDataset, ScDataLoaderThese 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.
| Input | Requirement |
|---|---|
store | Its decode dtype equals its file dtype; memory streams are rejected |
ids | One-dimensional NumPy integer array of length store.shape[1] |
| Kept IDs | Distinct integers in [0, uint32.max) within this dataset |
| Dropped columns | -1 or uint32.max |
| Store views | Row 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
| Parameter | Default | Contract |
|---|---|---|
corpus | Required | Nonempty sequence of ScDataset objects; captured as a tuple |
accesses | None | Corpus Accesses or its two-array tuple |
access_fn | None | Native AccessFn; corpus counts are bound automatically; supply exactly one of accesses/access_fn |
out_ids | None | Nonempty distinct standard IDs below uint32.max, in output order; omission requires identical dataset maps and selects their kept IDs |
process | None | ProcessFn with declared OutputLayout; omission produces dense X |
dtype | None | float32, or the ProcessFn's required input dtype; must be a supported native loader conversion |
default | 0 | Typed fill for dimensions absent from a source; does not replace present sparse zeros |
drop_last | False | Trim 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
| Parameter | Default | Unit / contract |
|---|---|---|
batch_size | 256 | Positive samples per output slot; bool is rejected |
prefetch | 4 | Positive host output slots; bool is rejected |
workers | None | Native threads; automatic value is min(16, usable CPUs); explicit values bypass this automatic cap |
cache_bytes | 0 | Nonnegative online input-cache budget; zero disables planning |
scratch_bytes | 0 | Process scratch bytes per worker |
backend | None | Probe io_uring, else pread; explicit "uring" or "pread" |
direct_io | None | Probe O_DIRECT; False forces buffered input I/O |
**settings | Empty | Individual 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
| Parameter | Default | Contract |
|---|---|---|
device | "cpu" | CPU or CUDA PyTorch device, for example "cuda:0" |
contiguous | False | True 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
| Operation | Behavior |
|---|---|
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_ids | Read-only output-panel view |
loading.stats | None 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
| Failure | Where to look |
|---|---|
TypeError / ValueError during construction | Corpus, Store, ID maps, panel, process output declaration or execution settings |
TypeError / ValueError on iterator start | Sample array shapes/types, dataset indices or dataset-local rows |
RuntimeError for a second iterator | Exhaust or close the active iterator first |
ModuleNotFoundError naming torch | Install PyTorch separately before iteration |
| I/O or native worker error during iteration | Source 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.ndarrayScDataLoader
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.