Skip to content

API Reference

Qubitium edited this page Dec 5, 2026 · 10 revisions

Python API reference

DataShoal 0.1.0. Examples use local files unless they name a provider. In signatures, * introduces keyword-only parameters and limits=DEFAULT means the immutable default SafeTensors.TensorLimits().

import datashoal as ds exposes the native entry points: load, upload, Dataset, DownloadConfig and the Parquet, ArrowIPC and SafeTensors namespaces. Use from datashoal import hf_compat as hf for the compatibility API, and from datashoal import SafeTensors as st for checkpoints. Native extension ABI

Loading and cache policy

Use a path for local data or a repository ID and revision for cached artifacts. Feature guide

Signature Usage and result
ds.DownloadConfig(*, force=False) Pass ds.DownloadConfig(force=True) to refresh a remote artifact. An empty config permits a cache fill.
ds.load(source, *, type, file=None, split=None, config='default', revision=None, download=False, token=None, provider='hf', limits=None) ds.load(path, type="dataset") returns a row stream for a file. ds.load(["a.jsonl", "b.jsonl"], type="dataset") streams an ordered list or tuple of local shards. Model files and complete snapshots return paths. A named HF dataset split returns a stream. Use type="safetensors" for an archive context manager. Default access is offline.

Hub files and Xet uploads

Uploads require an existing repository and a write token. Feature guide

Signature Usage and result
ds.upload(source, repo, *, type, file=None, revision=None, message='Upload with DataShoal', token=None) ds.upload("weights", "org/model", type="model", file="v1") uploads a local file or directory in one commit and returns its ID. revision=None targets main.
Signature Usage and result
datashoal.xet.reconstruct(repo, kind, commit, filename, size, file_id, token) Low-level iterator over reconstructed bytes for one HF file. Supply repo type, pinned commit, repository filename, verified size and 64-hex Xet file ID from Hub metadata. Applications normally use load to validate and publish the file.

Native templates

from datashoal.templates import Template exposes a subset of Jinja2 for data-only source and plain-text generation. Its C11 and Python implementations support the same subset.

API Behaviour
Template(source: str) Compile up to 1 MiB of UTF-8 template text using the local JIT extension when available or the Python fallback. Bad or unsupported syntax raises ValueError.
template.render(**data) -> str Render with plain string-key dictionaries, lists, tuples, strings, signed 64-bit integers, floats, booleans, and None. Missing names raise KeyError. Unsupported values raise TypeError or a limit error. A compiled instance supports concurrent renders. Coordinate changes to caller-owned mutable containers.
datashoal.templates.renderer_fingerprint() -> str Hex SHA-256 of the C11 renderer, Python fallback, and public wrapper sources for invalidating generated artifacts.

The grammar supports {{ path }}, dotted dictionary lookup, if with optional not, for name in path over lists and tuples, else, comments, and ASCII whitespace trimming with -. Loop attributes are index, index0, first, last, and length. The engine supports ASCII identifiers up to 128 bytes and Unicode literal text and values. It emits scalar text verbatim. Extension tags, arithmetic, filters, macros, calls, object attributes, and file loading are outside this subset. Keep templates under caller control and validate inserted values for the intended destination.

The fixed limits include 32,768 tags, 64 levels of nesting or lookup segments, 262,144 context entries, 16 MiB each for cumulative context text and dictionary storage, 1,048,576 render steps, and 16 MiB of output. Bounds errors stop the operation before it returns output.

from datashoal.templates import Template

template = Template("{% for item in items %}{{ item.name }}{% if not loop.last %}, {% endif %}{% endfor %}")
assert template.render(items=[{"name": "pack"}, {"name": "unpack"}]) == "pack, unpack"

Dataset streams

A row is a dictionary. Each pass gets a fresh cursor. A shared cursor divides its entries between callers. Close an abandoned cursor with cursor.close(). Feature guide

Signature Usage and result
ds.Dataset(rows) ds.Dataset(lambda: iter([{"x": 1}])) constructs a repeatable stream from a factory.
ds.load(paths, *, type='dataset') ds.load(["a.jsonl", "b.jsonl"], type="dataset") streams local shards in list order. For a custom suffix use hf.load_dataset(..., readers={".ext": factory}); the factory receives a shard path.
ds.Dataset.collect() stream.collect() materializes every row in order.
ds.Dataset.map(transform) stream.map(lambda r: {"n": len(r["text"])}) lazily replaces each row with the callback result.
ds.Dataset.filter(predicate) stream.filter(lambda r: r["n"] > 0) keeps matching rows lazily.
ds.Dataset.take(count) stream.take(8) returns a list of up to eight rows, stopping early.
ds.Dataset.sample(count, *, seed) stream.sample(32, seed=17) returns a reproducible, shuffled list sampled without replacement.
ds.Dataset.batches(size) for batch in stream.batches(32): ... yields lists and includes a final partial batch.

Parquet and Arrow

Use projected reads to avoid decoding unused columns. Feature guide

Signature Usage and result
ds.Parquet.load(source, *, file=None, columns=None, revision=None, download=False, token=None, provider='hf') ds.Parquet.load(path, columns=["id"]).take(1) reads projected rows as a Dataset. Like load, it accepts a local path or a repository ID with file=.
ds.Parquet.load_buffers(source, column, *, file=None, revision=None, download=False, token=None, provider='hf') [v.tolist() for v in ds.Parquet.load_buffers(path, "id")] consumes read-only typed page buffers for a supported flat numeric column without nulls.
ds.Parquet.save(path, rows, *, schema, row_group_size=1024, compression='none') ds.Parquet.save(path, [{"id": 4}], schema={"id": "int32"}) writes a local shard. The guide lists supported schema forms and encodings.
ds.ArrowIPC.load(source, *, file=None, columns=None, revision=None, download=False, token=None, provider='hf') ds.ArrowIPC.load(path, columns=["input_ids"]).collect() reads a supported Arrow IPC stream into rows.
ds.ArrowIPC.sample(paths, count, *, rng, columns=None) ds.ArrowIPC.sample(paths, 8, rng=random.Random(42), columns=["id"]) returns selected rows from ordered local shards in RNG order, reading the selected record batches.

HF dataset compatibility

Materialized datasets own their rows. Integer indexing returns a row, string indexing returns a column list, slicing returns a dictionary of column lists. Iteration, reversed iteration and len work on materialized datasets. Feature guide

Signature Usage and result
hf.load_dataset(path, name=None, *, split=None, streaming=False, data_files=None, revision='main', local_only=True, token=None, readers=None) hf.load_dataset("json", data_files={"train": path}, split="train") selects one split. Set streaming=True for a repeatable stream. Multiple splits without a selection return a split mapping.
hf.Dataset(rows) hf.Dataset([{"x": 1}]) creates a materialized dataset. Read its column_names property for the field list.
hf.Dataset.from_list(rows) hf.Dataset.from_list([{"x": 1}]) copies input rows.
hf.Dataset.from_dict(columns) hf.Dataset.from_dict({"x": [1, 2]}) builds rows from equal-length columns.
hf.Dataset.select(indices, *, keep_in_memory=True) data.select([2, 0]) gathers rows in the requested order.
hf.Dataset.shuffle(seed=None) data.shuffle(seed=4) returns a reordered dataset.
hf.Dataset.filter(function) data.filter(lambda r: r["x"] > 0) returns a filtered dataset.
hf.Dataset.map(function, *, batched=False, batch_size=1000, remove_columns=None, fn_kwargs=None, keep_in_memory=True, load_from_cache_file=False, num_proc=1) data.map(lambda r: {"y": r["x"] + 1}) merges output fields into each row. In batch mode callbacks consume and return column lists. Use one process and in-memory transforms.
hf.IterableDataset(rows) hf.IterableDataset(lambda: iter([{"x": 1}])) creates a repeatable stream. It inherits collect, sample and batches from ds.Dataset.
hf.IterableDataset.take(count) list(stream.take(2)) reads a prefix. The take operation itself returns a lazy iterable dataset.
hf.IterableDataset.map(function, *, batched=False, batch_size=1000, remove_columns=None, fn_kwargs=None) stream.map(lambda r: {"y": r["x"]}) lazily merges fields into rows.
hf.IterableDataset.filter(function) stream.filter(lambda r: r["x"] > 0) selects lazily.
hf.DatasetDict.map(function, **kwargs) hf.DatasetDict(train=data).map(fn) maps each materialized split and returns a DatasetDict.
hf.DatasetDict.filter(function) splits.filter(predicate) filters all splits and preserves split names.
hf.IterableDatasetDict.map(function, **kwargs) hf.IterableDatasetDict(train=stream).map(fn) returns mapped lazy splits.
hf.IterableDatasetDict.filter(function) streams.filter(predicate)["train"] selects one filtered stream.

HF Hub compatibility

Cache resolution defaults to local files. Shim installation changes process-wide import resolution and must precede imports of the upstream package. The PyTorch handle hf.safe_open is listed under Indexed PyTorch checkpoints. Feature guide

Signature Usage and result
hf.hf_hub_download(repo_id, filename, *, repo_type='model', revision='main', local_files_only=True, token=None) hf.hf_hub_download("org/model", "config.json") returns a cached file path as a string.
hf.snapshot_download(repo_id, *, repo_type='model', revision='main', local_files_only=True, token=None) hf.snapshot_download("org/data", repo_type="dataset") returns a snapshot directory string.
hf.upload_file(*, path_or_fileobj, path_in_repo, repo_id, repo_type='model', revision='main', token=None, commit_message='Upload with DataShoal') hf.upload_file(path_or_fileobj="local.bin", path_in_repo="weights.bin", repo_id="org/model") uploads a local path and returns the commit ID.
hf.install(*packages) hf.install("datasets", "huggingface_hub") installs the selected import shims. An existing conflicting module raises RuntimeError.

ModelScope compatibility

Import from datashoal import modelscope_compat as ms. All four calls return string paths. A cache miss raises FileNotFoundError with local_files_only=True. Set it to False to permit transfers. Feature guide

Signature Usage and result
ms.model_file_download(model_id, file_path, revision=None, *, cache_dir=None, token=None, local_files_only=True, endpoint=None) ms.model_file_download("org/model", "config.json") resolves a single model file.
ms.dataset_file_download(dataset_id, file_path, *, revision=None, cache_dir=None, token=None, local_files_only=True, endpoint=None) ms.dataset_file_download("org/data", "train.parquet") resolves a dataset shard.
ms.snapshot_download(model_id=None, revision=None, *, repo_id=None, repo_type='model', cache_dir=None, token=None, local_files_only=True, endpoint=None) ms.snapshot_download("org/model") returns the full snapshot directory.
ms.dataset_snapshot_download(dataset_id, revision=None, *, cache_dir=None, token=None, local_files_only=True, endpoint=None) ms.dataset_snapshot_download("org/data") returns a complete dataset directory.

SafeTensors archives

Use st for raw bytes, memory archives, and local shard layouts. PyTorch is optional. Feature guide

Signature Usage and result
st.wire.TensorData(dtype, shape, data) st.wire.TensorData("U8", (2,), b"ab") describes a contiguous little-endian payload by dtype, shape and data.
st.TensorLimits(max_header_bytes=16777216, max_tensors=65536, max_rank=32, max_metadata_entries=4096, max_materialized_bytes=1073741824, max_chunk_bytes=67108864, max_file_bytes=1099511627776) st.TensorLimits(max_materialized_bytes=4096) bounds archive operations. All seven budgets take integer values; byte budgets use bytes.
st.load(source, *, file=None, revision=None, download=False, token=None, provider='hf', limits=None) with st.load(path) as a: ... opens one validated shard. Use file= for a repository shard.
st.save(path, tensors, *, metadata=None, limits=DEFAULT, durable=False) st.save(path, {"x": tensor}, metadata={"format": "pt"}) publishes atomically. durable=True syncs the file before replacement.
st.dumps(tensors, *, metadata=None, limits=DEFAULT) blob = st.dumps({"x": tensor}) produces owned archive bytes.
st.loads(data, *, limits=DEFAULT) with st.loads(blob) as a: ... opens immutable archive bytes.
st.wire.layout(path, *, limits=DEFAULT) layout = st.wire.layout(path) returns a cached, validated on-disk layout.
st.wire.encode_header(specs, *, metadata=None, limits=DEFAULT) header, n = st.wire.encode_header([("x", "U8", (2,), 2)]) returns padded JSON header bytes and total payload size. Prefix the header with its length as an eight-byte little-endian integer when streaming a file.
Signature Usage and result
archive.read(name) archive.read("x") returns owned bytes subject to max_materialized_bytes.
archive.readinto(name, buffer) archive.readinto("x", bytearray(archive.wire.tensors["x"].nbytes)) fills a writable contiguous buffer exactly and returns the byte count.
archive.chunks(name, size=None) list(archive.chunks("x", size=1024)) yields independent bytes for one tensor.
archive.close() archive.close() releases the archive; context exit handles this automatically.

The archive exposes wire.metadata (a read-only string mapping, or None when absent), wire.has_metadata, wire.data_start (absolute byte offset) and wire.tensors (name to WireTensor with dtype, shape, begin, end and nbytes). With PyTorch installed, archive.torch(name, *, device="cpu") returns an independently writable tensor.

Signature Usage and result
layout.select(name, *, rows=None) st.save(dest, {"part": layout.select("x", rows=(0, 1))}) copies selected leading rows without decoding them.
layout.wire.header() layout.wire.header() returns a detached wire header with relative offsets.

TensorLayout exposes path, wire.data_start, wire.tensors, wire.metadata and identity. Each wire.tensors entry holds a WireTensor with dtype, shape, absolute begin and exclusive end. A selected StoredTensor carries path, name, wire and source identity. Keep indexed shards immutable while in use. Invalid or changed indexed shards can raise datashoal.tensor_layout.UnsafeCheckpointError, a ValueError subclass.

Indexed PyTorch checkpoints

Install PyTorch to enable st.index, from datashoal import torch_ranges as tr and hf.safe_open. DEFAULT_WINDOW_BYTES is 256 MiB. Feature guide

Signature Usage and result
st.index(files, *, limits=DEFAULT) idx = st.index([path]) builds a CheckpointIndex from shard headers. Use idx[name], name in idx, len(idx), iter(idx), or idx.keys(). Duplicate names are rejected.
idx.load(names=None, *, device='cpu', dtype=None, granularity='module', zero_copy=True, window_bytes=268435456, limits=None) for ref, value in idx.load(["a", "b"], device="cpu"): ... yields (ref, tensor) pairs through targeted mappings. Names default to every tensor in the index, and limits=None uses the budgets the index was built with. Device and dtype accept per-reference callbacks. Choose tensor, module or a grouping callback for granularity. Use zero_copy=False to request owning tensor copies.
Signature Usage and result
tr.supports_dtype(dtype) tr.supports_dtype(torch.float32) tests writer support for a torch.dtype.
tr.mapped_bytes(path) tr.mapped_bytes(path) reports bytes mapped into this Linux process or -1 if unavailable.
tr.CheckpointIndex(files, *, limits=DEFAULT) tr.CheckpointIndex([path]) is the constructor exposed through st.index. files lists shard paths and refs maps names to TensorRef objects.
tr.TensorRef.wire.begin Absolute file offset of the first payload byte.
tr.TensorRef.wire.end Exclusive absolute end offset. Header-relative versus absolute offsets
tr.TensorRef.wire.nbytes Byte length of this tensor’s checkpoint payload, equal to ref.wire.end - ref.wire.begin.
tr.TensorRef.wire.dtype SafeTensors dtype code from the header, e.g. "F4".
tr.TensorRef.wire.shape Value counts along each axis in the file header. Use ref.wire.nbytes for the byte count. Worked F16 and F4 examples
tr.TensorRef.load(*, rows=None, device='cpu', limits=None) idx["x"].load(rows=(0, 1)) reads a leading-dimension range on the requested device. limits=None uses the limits the index was built with. Use indexed references so shard identity is verified.
tr.TensorRef.dtype idx["x"].dtype returns the corresponding runtime dtype or raises for unsupported types.
tr.TensorRef.shape idx["x"].shape equals the dimensions of a full idx["x"].load() in PyTorch elements. Packed shapes and slicing
hf.safe_open(filename, framework='pt', device='cpu') with hf.safe_open(path) as h: ... opens a targeted safetensors.safe_open-style handle. Importing hf_compat does not import PyTorch; this call does.
h.keys() h.keys() lists tensor names.
h.metadata() h.metadata() returns a detached metadata dictionary or None.
h.get_tensor(name) h.get_tensor("x") reads one tensor.
h.get_slice(name) s = h.get_slice("x"); s.get_shape() returns logical dimensions, s.get_dtype() returns the wire dtype, and s[0:2] reads leading rows. General indexing materializes the tensor before indexing.

TensorRef fields are name, path, wire, identity and limits. Its wire.nbytes and is_floating properties describe the source range. Read the mapping lifetime and copy budgets before keeping views across checkpoint replacement.

Module-level helpers and record types

These names are available from their defining modules. Use the factory shown to obtain records populated from a validated source.

Module symbol Usage and result
st.wire.WireHeader(data_start, tensors, metadata) Obtain from archive.wire or layout.wire. Its header() method returns a detached dictionary with standard file-format keys.
st.wire.WireTensor(dtype, shape, begin, end) Inspect archive.wire.tensors[name] for the wire type, logical dimensions and payload length.
datashoal.wire.layout(path, *, limits=DEFAULT) The implementation exposed as st.wire.layout(path).
datashoal.tensor_layout.TensorLayout(path, wire, identity) Obtain from st.wire.layout(path) and use its select and wire.header methods.
datashoal.tensor_layout.StoredTensor(path, name, wire, identity) Obtain from layout.select(name) and pass as a value to st.save or st.dumps.
datashoal.tensor_layout.file_identity(stat) file_identity(os.stat(path)) produces the device, inode, size, mtime_ns and ctime_ns tuple checked when reopening a shard.
tr.TensorRef(name, path, wire, identity, limits=DEFAULT) Obtain from st.index(path)[name]. The limits accompany the reference when materializing a copy.
tr.map_file_window(fd, length, *, offset, access) Maps an aligned local-file byte range with the requested mmap access mode. Use CheckpointIndex.load to manage tensor ownership and enforce limits.
datashoal.parquet.Node(name, repetition, physical, annotation, children=(), width=0) Internal decoded Parquet schema record. Applications provide the schema mapping to Parquet.save.
datashoal.dataset.Row Type alias for a dictionary from field names to Python values.

Offline example from rows to weights

Run this example in an empty temporary directory. It uses the public Python package and works without PyTorch.

from pathlib import Path
from tempfile import TemporaryDirectory

import datashoal as ds
from datashoal import SafeTensors as st, hf_compat as hf

with TemporaryDirectory() as directory:
    base = Path(directory)
    shard = base / "train.parquet"
    ds.Parquet.save(shard, [{"id": 1}, {"id": 2}], schema={"id": "int32"})
    rows = ds.load(shard, type="dataset")
    assert rows.filter(lambda r: r["id"] > 1).take(1) == [{"id": 2}]
    assert list(rows.batches(2)) == [[{"id": 1}, {"id": 2}]]
    assert hf.load_dataset("parquet", data_files=str(shard), split="train")["id"] == [1, 2]
    assert [v for page in ds.Parquet.load_buffers(shard, "id") for v in page] == [1, 2]

    path = base / "weights.safetensors"
    st.save(path, {"x": st.wire.TensorData("U8", (2,), b"ab")})
    selected = st.wire.layout(path).select("x", rows=(1, 2))
    with st.loads(st.dumps({"last": selected})) as archive:
        assert archive.read("last") == b"b"

Clone this wiki locally