Skip to content

API Reference

Qubitium edited this page Dec 3, 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. 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. 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

The explicit download helper may access the network. Uploads require an existing repository and a write token. Feature guide

Signature Usage and result
ds.download(repo, filename, *, revision='main', local_only=False, token=None, type='dataset') ds.download("org/model", "config.json", type="model", local_only=True) returns a cached Path or raises FileNotFoundError.
ds.upload(source, repo, *, type, file=None, revision='main', 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.
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 or download to validate and publish the file.

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.read(*paths, readers=None) ds.read("a.jsonl", "b.jsonl") streams shards in argument order. Override a suffix with 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.read_parquet(path, *, columns=None) ds.read_parquet(path, columns=["id"]).take(1) reads projected rows as a Dataset.
ds.read_parquet_buffers(path, column) [v.tolist() for v in ds.read_parquet_buffers(path, "id")] consumes read-only typed page buffers for a supported flat numeric column without nulls.
ds.write_parquet(path, rows, *, schema, row_group_size=1024, compression='none') ds.write_parquet(path, [{"id": 4}], schema={"id": "int32"}) writes a local shard. The guide lists supported schema forms and encodings.
ds.read_arrow_ipc(path, *, columns=None) ds.read_arrow_ipc(path, columns=["input_ids"]).collect() reads a supported Arrow IPC stream into rows.
Signature Usage and result
datashoal.arrow.sample_arrow_ipc(paths, count, *, rng, columns=None) sample_arrow_ipc(paths, 8, rng=random.Random(42), columns=["id"]) returns selected rows 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. 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 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 both st operations below and from datashoal import torch_ranges as tr. 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.
st.read_tensors(refs, *, device='cpu', dtype=None, granularity='module', zero_copy=True, window_bytes=268435456, limits=DEFAULT) for ref, value in st.read_tensors(idx.refs.values(), device="cpu"): ... yields targeted tensors. Device and dtype accept per-reference callbacks. Choose tensor, module or a grouping callback for granularity.
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.read(*, rows=None, device='cpu', limits=DEFAULT) idx["x"].read(rows=(0, 1)) reads a leading-dimension range on the requested device. 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"].read() in PyTorch elements. Packed shapes and slicing
tr.read_one(ref, device='cpu', *, rows=None, limits=DEFAULT) tr.read_one(idx["x"], rows=(0, 1)) reads a single reference.
tr.read_tensors(refs, *, device='cpu', dtype=None, granularity='module', zero_copy=True, window_bytes=268435456, limits=DEFAULT) Same callable as st.read_tensors. Use zero_copy=False to request owning tensor copies.
tr.safe_open(path, framework='pt', device='cpu') with tr.safe_open(path) as h: ... opens a targeted PyTorch compatibility handle.
tr.SafetensorsHandle(path, framework='pt', device='cpu') tr.SafetensorsHandle(path) constructs the context manager returned by safe_open.
tr.SafetensorsHandle.keys() h.keys() lists tensor names.
tr.SafetensorsHandle.metadata() h.metadata() returns a detached metadata dictionary or None.
tr.SafetensorsHandle.get_tensor(name) h.get_tensor("x") reads one tensor.
tr.SafetensorsHandle.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 read_tensors 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 write_parquet.
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.write_parquet(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.read_parquet_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