Appearance
DataLoader and sample ordering โ
This complete program generates two small matrices in a temporary directory, aligns their different column panels, and delivers scGPT preset fields for two caller-defined epochs. It checks integration of sample order, native processing and Tensor delivery; it does not construct a model or optimizer.
For a first dense X batch with checked numeric values and no process compiler, start with the training guide.
Choose a run โ
Every mode needs PyTorch and a C++17 compiler: the program always compiles its scGPT process preset. The access-function mode additionally compiles a corpus callback. Install PyTorch separately for the target CPU or CUDA environment.
In your Python project, install PyCellPack from PyPI and save the downloadable program as dataloader-example.py. With PyTorch and the compiler available, run:
sh
uv add pycellpack
uv run dataloader-example.py
uv run dataloader-example.py --access-fn
uv run dataloader-example.py --device cuda| Command option | What changes | Required device |
|---|---|---|
| No option | Materialized dataset/local-row arrays, copied CPU Tensor batches | CPU |
--access-fn | Native callback returns the same kind of corpus pairs | CPU |
--device cuda | Packed pinned-host transfer and contiguous genes/values fields | Compatible PyTorch CUDA installation and GPU |
Each epoch replaces loading.accesses or loading.access_fn before iteration. The corpus has 12 samples and batch size 4, so each epoch prints three steps and ends with accesses=12. Each batch contains genes, values and targets, all with shape (4, 8). CPU output lines therefore include:
text
epoch=0 step=0 genes=(4, 8)@cpu, values=(4, 8)@cpu, targets=(4, 8)@cpuThe token table is in output-panel order. A returned field is a Tensor, while the caller's Accesses rows still refer to dataset-local input rows. These are separate identities.
Complete source โ
- 01Define the corpus
ScDatasetWrap file-backed Stores and assign standard gene IDs.
- 02Choose sample order
Accesses / AccessFnSupply dataset IDs and dataset-local rows, or a native AccessFn.
- 03Declare delivery
ScDataLoaderChoose output IDs, dtype, batch size and device.
- 04Iterate and close
with loadingConsume named Tensor fields; use a context manager for cleanup.
The application chooses vocabulary, sampling policy and epoch order explicitly.
Complete program: fixture, sampler, preset and two epochs
py
"""External sample ordering with fixed accesses or a native AccessFn.
uv run example/dataloader-example.py
uv run example/dataloader-example.py --access-fn
uv run example/dataloader-example.py --device cuda
Torch is installed separately. A C++17 compiler builds the model template
and the optional access function; sampling policy is ordinary caller code.
"""
import argparse
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
from pycellpack import write
from pycellpack.dataloader import (
Accesses,
AccessFn,
ScDataLoader,
ScDataset,
process_presets,
)
ACCESS_CODE = r'''
#include "access_fn_cabi.h"
struct Visits { const uint32_t *datasets; const uint64_t *rows; };
extern "C" int32_t generate_accesses(void *context, uint64_t start, uint64_t count,
uint32_t *datasets, uint64_t *rows) {
const auto &visits = *static_cast<const Visits *>(context);
for (uint64_t i = 0; i < count; ++i) {
datasets[i] = visits.datasets[start + i];
rows[i] = visits.rows[start + i];
}
return 0;
}
'''
def sample_order(corpus, rng):
counts = [len(dataset) for dataset in corpus]
datasets = np.repeat(np.arange(len(corpus), dtype=np.uint32), counts)
rows = np.concatenate([np.arange(n, dtype=np.uint64) for n in counts])
order = rng.permutation(len(rows))
return Accesses(datasets[order], rows[order])
def bind_access_fn(accesses):
import ctypes
class Visits(ctypes.Structure):
_fields_ = [("datasets", ctypes.c_void_p), ("rows", ctypes.c_void_p)]
tables = Visits(accesses.dataset_ids.ctypes.data, accesses.rows.ctypes.data)
return AccessFn.from_source(code=ACCESS_CODE, kind="corpus", length=len(accesses),
user_data=tables, key=(accesses.dataset_ids, accesses.rows), owner=accesses)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
parser.add_argument("--access-fn", action="store_true")
args = parser.parse_args()
with TemporaryDirectory(prefix="pycellpack-dataloader-") as directory:
root = Path(directory)
rng = np.random.default_rng(0)
a = rng.poisson(2, (7, 6)).astype(np.float32)
b = rng.poisson(2, (5, 3)).astype(np.float32)
a[:, 0] += 1
b[:, 0] += 1
corpus = [
ScDataset(write(root / "a.cpk", a, workers=1), ids=np.arange(6)),
ScDataset(write(root / "b.cpk", b, workers=1), ids=np.array([0, 2, 4])),
]
process = process_presets.scgpt(np.arange(10, 16), pad_token=0, cls_token=1, length=8, seed=3)
accesses = sample_order(corpus, rng)
inputs = {"access_fn": bind_access_fn(accesses)} if args.access_fn else {"accesses": accesses}
with ScDataLoader(corpus=corpus, out_ids=np.arange(6), process=process, batch_size=4,
workers=2, prefetch=2, device=args.device,
contiguous=("genes", "values"), **inputs) as loading:
print(loading)
for epoch in range(2):
accesses = sample_order(corpus, rng)
if args.access_fn:
loading.access_fn = bind_access_fn(accesses)
else:
loading.accesses = accesses
for step, batch in enumerate(loading):
print(f"epoch={epoch} step={step} " + ", ".join(
f"{name}={tuple(tensor.shape)}@{tensor.device}" for name, tensor in batch.items()
))
print(f"accesses={loading.stats.accesses}")
if __name__ == "__main__":
main()Download the source. See the DataLoader API for lifecycle and transfer contracts, or AccessFn for callback ownership and deterministic range generation.