Appearance
Process functions API
ProcessFn binds native row callbacks, and OutputLayout describes their fixed output record. Read the guide for a complete CPU preset workflow and the runnable program for packed CUDA transfer.
python
from pycellpack.loader.process_fn import ProcessFn, OutputLayout, compile_library, presetsFind the contract you need
- Choose an exported library, source build or Numba callback.Bind native codeCode ownership and configuration identity are separate requirements.
- Define field offsets or retain processed results.Read named outputA layout describes a fixed record; NumPy field views keep its slot leased.
- Use scGPT, Geneformer, UCE or STATE SE.Configure a presetTables follow schema output order, with float32 mapped input.
Construction and identity
| Interface | Required input | Result / default |
|---|---|---|
ProcessFn.from_library | Library path or ctypes handle; CSR and/or dense functions | Bound function retaining library and native owners |
ProcessFn.from_source | Source files and/or inline code; exported symbols | Compiled/cached library bound as above |
ProcessFn.from_cfunc | CSR and/or dense Numba callbacks, or compilable functions | Native callback pointers; Numba loads on use |
ProcessFn(capsule, identity=...) | Provider-owned pycellpack.process.v1 capsule | Advanced binding with no reconstruction recipe |
process.schema(out_ids, ...) | Declared OutputLayout and output-panel IDs | OutputSchema; custom input dtype defaults to float32 |
compile_library | Source files and/or inline C/C++ code | Path to the compiled shared library |
Shared factory keywords:
| Parameter | Contract |
|---|---|
csr, dense | Exported names, supported function objects or addresses; at least the selected format is required |
row_format=None | Factories infer "auto" from both callbacks or the single supplied format; explicit "auto" requires both |
partial_rows=False | Opt into partial CSR rows and resolver support; dense delivery has no partial-row protocol |
user_data | Context passed to every call; ctypes/NumPy objects are retained, raw addresses remain the caller's responsibility |
key | Configuration values hashed into the derived identity, including everything read through user_data |
identity | Explicit integer in [0, 2**64); use instead of key, not together |
owner | Additional object retaining code or pointer-backed storage; retention alone does not contribute identity |
output | OutputLayout or equivalent structured dtype; optional for opaque output |
Derived library identities include file contents, function names, delivery mode, partial-row declaration and key. Numba identities also include function source or bytecode and the Numba version; cover any globals or closures in your key. Addresses need an explicit identity. Supplied context without a key or explicit identity is rejected.
process.schema accepts dtype, id, name, default and scratch_bytes in addition to out_ids. OutputSchema(process=...) infers row_bytes from a declared layout and rejects a conflicting explicit size. Without a layout, use its explicit row_bytes interface; schema() and unpack() then raise ValueError.
Compilation and reconstruction
compile_library accepts language, name, compiler, std, optimize, flags, include_dirs, defines, depends, cache_dir and force. Compiler selection uses the explicit choice, then CXX/CC, then supported platform drivers. The build cache includes sources, compiler identity, flags, ABI/preset headers and declared dependencies. List your additional included files in depends; they are not discovered as an arbitrary transitive dependency graph.
A compiler is resolved even for cached source builds. from_library can use an already built library without compiling. Recipe-based bindings pickle when their arguments do: source recipes rebuild from cache, library recipes reopen a path and named symbols, and supported Numba recipes reconstruct callables. Raw addresses, hand-made capsules or unsupported owner/context configurations do not provide a portable recipe. Preset recipes retain table values and rebuild native pointers in the receiver.
For generic factories, an explicit owner or integer user_data disables the automatic recipe, even if the owner would itself be picklable. Library/source recipes also require a path and named exports. Use a reconstruction factory for such pointer-owning configurations instead of sending the live object.
OutputLayout and field views
OutputLayout(fields, align=True) accepts NumPy structured dtype declarations, including explicit offsets and itemsize. Fields must be named, nonempty, native-endian numeric values within the record. Default C alignment includes tail padding. align=False describes a packed layout. The declaration must match the native callback; it does not guard that callback's output writes.
| Interface | Result |
|---|---|
layout.dtype | Structured dtype with field offsets, shapes and padding |
layout.names | Tuple of field names in declaration order |
layout.offsets | Name → byte offset within the record |
layout.row_bytes / process.row_bytes | Complete padded record byte size |
layout.unpack(raw, copy=False) / process.unpack(...) | Dictionary of named NumPy fields |
raw must be a NumPy uint8 array shaped [..., row_bytes]; its byte axis is contiguous, while leading axes may be strided. Scalar fields have the leading shape; array fields append their declared field shape. The usual source is batch.region(name).
With copy=False, fields may be strided or unaligned and retain raw storage and its slot lease, including after Batch release or Run closure. copy=True gives independent aligned C-contiguous arrays. Retaining every batch's field views can fill the output ring and block production. This helper accepts host NumPy arrays, not CUDA tensors. See ring ownership.
For explicit nonblocking H2D, retain the packed host view and host Tensor until the copy completes, then release them. Submitting the copy alone does not finish reading the slot. Device field views retain device storage; coordinate their CUDA streams independently. The CPU/CUDA program shows the complete lifetime sequence.
Callback input and ABI
ProcessFn.include_dir() and the module-level include_dir() locate process_fn_cabi.h, whose capsule name is pycellpack.process.v1. The context contains logical sequence position, global cell ID, schema index, input dtype and user_data. Callback values have already been converted to the schema dtype; column numbers address the mapped output panel. Every schema at one position sees the same position value; schema is its vector index, not application id.
| Delivery | Requirement |
|---|---|
"csr" | CSR callback; columns can be unsorted and list stored elements only |
"dense" | Dense callback; present omitted values are zero, absent source dimensions receive the schema default; factories reject partial_rows=True |
"auto" | Equivalent CSR and dense callbacks; internal layout/route choices may change which one runs |
| Partial CSR | Null column/value pointers require the supplied resolver; positions address stored elements, not output dimensions |
CSR omissions alone do not identify whether a dimension was missing or zero. Use a distinguishing dense default or application-owned source metadata when that information matters. Partial-row resolve accepts repeated/out-of-order element positions; each must be below nnz. Null positions with count == nnz request all elements in order. Its row and output pointers are valid only for the call; propagate a nonzero resolver status.
Callbacks may run concurrently. Write within row_bytes and scratch_bytes, retain no borrowed pointers, and prevent exceptions or unwinding from crossing the C ABI. Native write bounds are the provider's responsibility. A nonzero callback status fails the run as a RuntimeError; it is a provider-defined code.
Model presets
All four factories return ProcessFn with a declared layout, input_dtype=float32 and out_dim=len(tokens). Schemas reject incompatible mapped dtype or width. Each token and auxiliary-table entry addresses one schema output dimension in out_ids order, rather than a standard ID or original file column. Tables are copied into immutable contiguous storage. Negative tokens exclude dimensions.
Let L=length, Q=positive+negative for UCE and Q=positive+negative+shared for STATE SE.
| Factory | Required tables / special IDs | Fields per row |
|---|---|---|
scgpt | tokens; pad_token, cls_token | genes int64[L], values float32[L], targets float32[L] |
geneformer | tokens, medians; pad_token, cls_token, eos_token | ids int64[L], length uint32 |
uce | tokens, chroms, starts; pad_token, cls_token, chrom_offset, chrom_close_token | ids int64[L], loss_ids int64[Q], labels float32[Q], length uint32 |
state_se | tokens; global_size | ids int64[L], tasks int64[Q], targets float32[Q], counts float32[L], total float32 |
Medians, chromosomes and starts have the token-table width. Tokens must be a nonempty integer vector with at least one nonnegative entry. Factories validate option domains and table dimensions; per-cell content can still fail in native execution. Geneformer excludes nonpositive medians. UCE requires at least two eligible expressed genes in a cell and sufficient sentence capacity; the header also defines masking-related status codes. STATE SE requires nonnegative tokens below global_size; batch groups consecutive access positions for shared query draws and cls_index indexes the eligible panel.
Defaults and exact sampling arguments are listed in the declarations. They implement the shipped templates rather than loading a checkpoint's preprocessing configuration. Factories compile C++17 templates and pass build keywords to compile_library; native/Python struct sizes and offsets are compile-time checked. Headers are under include/template/{scgpt,geneformer,uce,state_se}.hpp.
Instantiate a C++ template directly
cpp
#include "template/scgpt.hpp"
struct Config : pycellpack::preset::ScGptDefaults {
static constexpr uint32_t length = 1200;
};
PYCELLPACK_EXPORT_PROCESS_FN(scgpt, pycellpack::preset::ScGpt<Config>)Bind scgpt_csr and scgpt_dense with ProcessFn.from_source. Supply the header's exact runtime-table struct through user_data, a key covering its contents, and a matching OutputLayout. template/common.hpp adapts these models to the C ABI.
Errors
Invalid layouts, identities, delivery modes, table dimensions and options raise TypeError or ValueError. Missing compilers raise CompilerNotFoundError; compilation failures raise ProcessBuildError; library loading or missing exports raise ProcessLibraryError. Execution and callback failures surface during iteration or joining. After failure, use the run recovery rules rather than consuming partially written output.
Declarations
Complete declarations and members
ProcessFn
A provider-owned pycellpack.process.v1 capsule (see process_fn_cabi.h): a CSR and/or a dense function turning one cell's row, mapped to the schema's output dims and converted to its dtype, into the cell's fixed-size output.
Four ways to build one: ProcessFn.from_source compiles C/C++ code and binds it; ProcessFn.from_cfunc binds numba @cfunc functions (or compiles Python functions as such); ProcessFn.from_library binds the functions of a library built elsewhere (an MSVC DLL, say); the constructor takes a vtable capsule made by hand.
Row semantics: an output dim the cell's matrix has a column for is present (its stored value, or 0 where the record stores none: CSR drops zeros, so they are expression values); an output dim with no matching column is missing; a column no output dim takes is dropped. CSR rows list stored elements only. Dense rows hold 0 at present zeros and the schema's default at missing dims, so a default no value takes (NaN, the dtype's maximum) lets a dense function tell missing dims apart; a CSR function can instead keep each dataset's genes in its user data and find the cell's dataset from the context's global cell id.
row_format picks the rows delivered: "auto" (both functions) gives CSR records as CSR rows; dense records use internal throughput thresholds based on dimensions, dtype conversion, value coding and cache state. Cached dense records may compact to CSR once at admission. "csr" or "dense" always delivers that format and needs only that function (the other vtable entry may be NULL).
The functions are native and thread-safe, write only their cell's output and their scratch (nothing is checked), and must compute the same output from the same row. identity versions the functions and all retained configuration; owner can retain a shared library, vtable or parameters. partial_rows declares that the CSR function resolves rows given without columns and values.
A function built by from_source, by from_library from a library path and exported names, or by from_cfunc from picklable functions pickles as that recipe (the other process rebuilds it, from the build cache for sources); one bound from a hand-made capsule or raw addresses names this process's memory and does not.
ProcessFn.output
output: OutputLayout | None — property.
Declared output layout, or None for a function with opaque output.
ProcessFn.row_bytes
row_bytes: int | None — property.
Declared output record size; None when no layout was supplied.
ProcessFn.input_dtype
input_dtype — property.
Required input dtype for a model template, otherwise None.
ProcessFn.out_dim
out_dim: int | None — property.
Required mapped input width for a model template, otherwise None.
ProcessFn.schema
python
ProcessFn.schema(out_ids, dtype=None, *, id=None, name=None, default=0, scratch_bytes=0)Build an OutputSchema using this function's declared record size.
Model templates also bind the input dtype and width of their tables. Custom functions default to float32 input. Supply output= when constructing a custom function to use this convenience.
ProcessFn.unpack
python
ProcessFn.unpack(raw, *, copy=False)Named output arrays; views retain the batch lease unless copy=True.
raw is a uint8 array, normally batch.region(name). See OutputLayout.unpack for shapes, strides and ownership. For GPU training, transfer the packed array once and construct fields on the device; copy=True is for retaining CPU arrays.
ProcessFn.identity
identity — property.
The declared identity: a 64-bit version of the functions and every piece of configuration they read.
ProcessFn.partial_rows
partial_rows — property.
Whether the CSR function resolves rows given without columns and values (always false for dense rows).
ProcessFn.row_format
row_format — property.
The row format the loader delivers: "auto", "csr" or "dense".
ProcessFn.from_library
python
ProcessFn.from_library(library, *, csr=None, dense=None, user_data=None, key=None, identity=None, row_format=None, partial_rows=False, owner=None, output=None)Binds a shared library's process functions, without a hand-made vtable or capsule.
library is a path or a loaded ctypes.CDLL; csr and dense name the exported functions (or give ctypes functions or addresses). The row format defaults to what they cover: both "auto", one alone that format. user_data is passed to every call: a ctypes object (a Structure, an array) or a numpy array, both kept alive, or a raw address the caller keeps valid; owner retains anything else it points to.
The identity defaults to a hash of the library file, the function names, the row format, partial_rows and key, which must describe what user_data holds (numbers, strings, bytes, numpy arrays, ctypes objects, or lists/tuples/dicts of them); give identity instead to set it directly. Raises ProcessLibraryError when the library cannot be loaded or lacks a function.
output is an OutputLayout or structured dtype specification for the function's fixed output record. It enables schema() and unpack() and must agree with the function's actual writes.
ProcessFn.from_source
python
ProcessFn.from_source(sources=(), *, code=None, csr=None, dense=None, user_data=None, key=None, identity=None, row_format=None, partial_rows=False, owner=None, output=None, **build)Compiles C/C++ sources (sources files and/or inline code) with compile_library (the remaining keywords: language, name, compiler, std, optimize, flags, include_dirs, defines, depends, cache_dir, force) and binds them as from_library does.
ProcessFn.from_cfunc
python
ProcessFn.from_cfunc(*, csr=None, dense=None, user_data=None, key=None, identity=None, row_format=None, partial_rows=False, owner=None, output=None)Binds process functions written in Python with numba.
csr and dense are numba @cfunc functions with the signatures returned by pycellpack.loader.process_fn.numba_bindings() (CSR_SIGNATURE, DENSE_SIGNATURE; int32(voidptr) is accepted too), or plain Python functions, which are compiled with those signatures here. user_data, key, identity, row_format, partial_rows and owner are as for from_library; the default identity hashes the functions' source (or bytecode), the numba version, the row format, partial_rows and key, which must also cover globals or closures the functions read. Raises ProcessBuildError when numba cannot compile a function, TypeError for a cfunc of another signature.
ProcessFn.include_dir
python
ProcessFn.include_dir()The directory holding process_fn_cabi.h and the model templates, which compiled sources include; compile_library puts it first on the include path.
OutputLayout
python
OutputLayout(fields, *, align=True)A NumPy structured dtype describing one native output record.
fields takes NumPy's structured dtype specifications, for example [("ids", "i8", (1024,)), ("length", "u4")]. C struct alignment (including tail padding) is used by default. Explicit offsets and an itemsize can instead be supplied through a NumPy dtype. The declaration must agree with the native function; it does not change the function.
OutputLayout.dtype
dtype: np.dtype — property.
The structured record dtype, including offsets and padding.
OutputLayout.names
names: tuple[str, ...] — property.
Field names in declaration order.
OutputLayout.offsets
offsets: dict[str, int] — property.
Byte offsets of the named fields within one record.
OutputLayout.row_bytes
row_bytes: int — property.
Bytes of one complete record, including tail padding.
OutputLayout.unpack
python
OutputLayout.unpack(raw: np.ndarray, *, copy=False) -> dict[str, np.ndarray]View uint8[..., row_bytes] as named arrays without copying.
The last axis must be contiguous; preceding axes may be strided. Views retain their source, including a batch's slot lease. Fields may be strided or unaligned. copy=True returns independent, aligned C-contiguous arrays, releasing that dependency. GPU training can instead transfer the complete packed buffer and construct device field views after the H2D copy has completed.
compile_library
python
compile_library(sources=(), *, code=None, language=None, name=None, compiler=None, std=None, optimize='-O3', flags=(), include_dirs=(), defines=None, depends=(), cache_dir=None, force=False) -> PathCompiles process function sources into a shared library; returns its path.
sources are C or C++ files (by suffix); code adds inline source text in language, C++ unless language="c" (one driver invocation compiles every input as one language, so inline code joins C source files only when it is declared C). The process headers (process_fn_cabi.h and the model templates under template/) and every source file's directory are on the include path, before include_dirs. flags are passed to the compiler as is (say ["-march=native"]); defines maps macro names to values (None: defined without a value).
The library is cached under cache_dir (default $CELLPACK_HOME/process-libraries) by everything that shapes it: the compiler and its version, the command options, the sources, the process headers and the files in depends (headers or included sources not listed in sources). A cached library is reused unless force; concurrent builds of the same library are safe. Raises CompilerNotFoundError when no GCC/Clang driver is usable and ProcessBuildError (with the command and the compiler's messages) when compilation fails.
find_compiler
python
find_compiler(language: str='c++', compiler: str | os.PathLike | None=None) -> CompilerThe compiler driver for language ("c" or "c++"): compiler if given, else $CXX / $CC, else the platform's usual GCC/Clang names.
Compiler
A GCC or Clang compiler driver: path, kind ("gcc", "clang" or "unknown", which is driven like GCC) and the first line of its version output.
Fields and defaults
python
path: str
kind: str
version: strProcessBuildError
A process library could not be compiled.
CompilerNotFoundError
No usable GCC or Clang driver was found.
ProcessLibraryError
A process library could not be loaded or lacks a function.
scgpt
python
scgpt(tokens, *, pad_token, cls_token, length=1024, n_bins=51, mask_ratio=0.4, pad_value=-2.0, mask_value=-1.0, cls_value=-2.0, seed=0, row_format='auto', **build) -> ProcessFnQuantile binning, sampling and masking using template/scgpt.hpp.
Output fields: genes int64[length], values and targets float32[length]. Random draws depend on seed and global cell id. Negative tokens exclude genes. Special token ids and value sentinels are supplied explicitly.
geneformer
python
geneformer(tokens, medians, *, pad_token, cls_token, eos_token, length=4096, special_tokens=True, row_format='auto', **build) -> ProcessFnMedian-normalized ranking using template/geneformer.hpp.
Nonpositive medians and negative tokens exclude genes. Output fields: ids int64[length] and length uint32 (the used token count). Set special_tokens=False for sentences without CLS/EOS (V1).
uce
python
uce(tokens, chroms, starts, *, pad_token, cls_token, chrom_offset, chrom_close_token, length=1536, sample=1024, positive=512, negative=512, mask_ratio=0.2, seed=0, row_format='auto', **build) -> ProcessFnChromosome-grouped sampling using template/uce.hpp.
chroms and starts address every output dim. Output fields: ids int64[length], loss_ids int64[positive+negative], labels float32[positive+negative] and length uint32. The template reports an error for cells with fewer than two eligible expressed genes, all genes masked, or a sentence exceeding length.
state_se
python
state_se(tokens, *, global_size, length=2048, positive=512, negative=512, shared=512, batch=128, raw_counts=0, cls_index=3, seed=0, stream=0, row_format='auto', **build) -> ProcessFnCell sentences and expression queries using template/state_se.hpp.
global_size is the protein token vocabulary size. raw_counts is 0 for detection, 1 for raw counts, 2 for log values. batch sets the number of consecutive access positions sharing query tokens; match it to the training microbatch. Output: ids int64[length], tasks int64[Q], targets float32[Q], counts float32[length], total float32, Q=positive+negative+shared.