loaderx 2.4.6__cp314-cp314t-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loaderx/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """loaderx: a data loader over typed, ordered zrecord sequences.
2
+
3
+ Public API is imported from its layer, not flattened here, so the abstraction
4
+ boundaries stay visible:
5
+
6
+ from loaderx.utils import train_dict
7
+ from loaderx.converter import convert, huggingface
8
+ from loaderx.zrecord import Dense, Ragged, ZrecordError
9
+ from loaderx.dataloader import DataLoader
10
+ from loaderx.zsampler import Sampler
11
+
12
+ ``utils`` holds the manual, standalone ``train_dict`` step. ``converter`` owns
13
+ offline remote ingestion into completed Zrecord streams. ``zrecord`` exposes
14
+ ``Dense`` and ``Ragged`` are rebuildable ordered containers: ``create`` extends
15
+ the sequence in append order, ``open`` is read-only, and ``close`` is the sole
16
+ public publication boundary.
17
+ ``dataloader`` dynamically composes opened streams and produces the endless,
18
+ step-based sampler + prefetch pipeline over them.
19
+ """
20
+
21
+ __version__ = "2.4.6"
loaderx/_storage.py ADDED
@@ -0,0 +1,196 @@
1
+ """Python lifecycle support over the Cython Store binding."""
2
+
3
+ import os
4
+ import sys
5
+ import threading
6
+
7
+ import numpy as np
8
+
9
+ from . import _store
10
+
11
+ CODECS = _store.CODECS
12
+ MAX_DATA_SHARDS = _store.MAX_DATA_SHARDS
13
+ MAX_RECORD_LEN = _store.MAX_RECORD_LEN
14
+ MAX_SCHEMA_LEN = _store.MAX_SCHEMA_LEN
15
+ ZrecordError = _store.ZrecordError
16
+
17
+
18
+ def _path_bytes(path):
19
+ return os.fsencode(os.fspath(path))
20
+
21
+
22
+ def _logical_cpu_count():
23
+ process_cpu_count = getattr(os, "process_cpu_count", None)
24
+ logical = process_cpu_count() if process_cpu_count is not None else None
25
+ if logical is None and hasattr(os, "sched_getaffinity"):
26
+ logical = len(os.sched_getaffinity(0))
27
+ return logical or os.cpu_count() or 1
28
+
29
+
30
+ def _physical_cpu_count(logical):
31
+ if sys.platform.startswith("linux"):
32
+ cpus = os.sched_getaffinity(0) if hasattr(os, "sched_getaffinity") else range(logical)
33
+ cores = set()
34
+ try:
35
+ for cpu in cpus:
36
+ topology = f"/sys/devices/system/cpu/cpu{cpu}/topology"
37
+ with open(f"{topology}/physical_package_id") as file:
38
+ package = int(file.read())
39
+ with open(f"{topology}/core_id") as file:
40
+ core = int(file.read())
41
+ cores.add((package, core))
42
+ except (OSError, ValueError):
43
+ return logical
44
+ return len(cores) or logical
45
+
46
+ if sys.platform == "darwin":
47
+ import subprocess
48
+ try:
49
+ return int(subprocess.check_output(
50
+ ["sysctl", "-n", "hw.physicalcpu"], text=True,
51
+ ).strip())
52
+ except (OSError, subprocess.SubprocessError, ValueError):
53
+ return logical
54
+
55
+ if sys.platform == "win32":
56
+ import ctypes
57
+ try:
58
+ query = ctypes.windll.kernel32.GetLogicalProcessorInformationEx
59
+ query.argtypes = [ctypes.c_int, ctypes.c_void_p,
60
+ ctypes.POINTER(ctypes.c_ulong)]
61
+ query.restype = ctypes.c_bool
62
+ size = ctypes.c_ulong()
63
+ query(0, None, ctypes.byref(size)) # RelationProcessorCore
64
+ if size.value == 0:
65
+ return logical
66
+ buffer = ctypes.create_string_buffer(size.value)
67
+ if not query(0, buffer, ctypes.byref(size)):
68
+ return logical
69
+ cores = 0
70
+ offset = 0
71
+ while offset < size.value:
72
+ relationship = int.from_bytes(buffer[offset:offset + 4], "little")
73
+ record_size = int.from_bytes(buffer[offset + 4:offset + 8], "little")
74
+ if relationship == 0:
75
+ cores += 1
76
+ if record_size < 8:
77
+ return logical
78
+ offset += record_size
79
+ return cores or logical
80
+ except (AttributeError, OSError, ValueError):
81
+ return logical
82
+
83
+ return logical
84
+
85
+
86
+ class _Executor:
87
+ def __init__(self):
88
+ logical = _logical_cpu_count()
89
+ physical = _physical_cpu_count(logical)
90
+ lanes = max(1, physical, logical * 3 // 4)
91
+ self._handle = _store.Executor(lanes)
92
+
93
+ def close(self):
94
+ handle = getattr(self, "_handle", None)
95
+ if handle is not None:
96
+ self._handle = None
97
+ handle.close()
98
+
99
+ def __del__(self):
100
+ self.close()
101
+
102
+
103
+ _executor = None
104
+ _executor_lock = threading.Lock()
105
+
106
+
107
+ def _get_executor():
108
+ global _executor
109
+ if _executor is None:
110
+ with _executor_lock:
111
+ if _executor is None:
112
+ _executor = _Executor()
113
+ return _executor
114
+
115
+
116
+ class _Store:
117
+ """Common binding behavior over the native RecordEngine handle."""
118
+
119
+ @classmethod
120
+ def open(cls, path):
121
+ self = cls.__new__(cls)
122
+ self._executor = _get_executor()
123
+ self.writable = False
124
+ raw_path = _path_bytes(path)
125
+ self._handle, schema = _store.Store.open(
126
+ self._executor._handle, raw_path,
127
+ )
128
+ self._length = self._handle.length()
129
+ self.data_shards = self._handle.data_shards()
130
+ return self, schema
131
+
132
+ @classmethod
133
+ def create(cls, path, codec, data_shards, dict_bytes, schema_bytes):
134
+ self = cls.__new__(cls)
135
+ self._executor = _get_executor()
136
+ self.writable = True
137
+ raw_path = _path_bytes(path)
138
+ raw_dict = np.frombuffer(dict_bytes or b"", dtype=np.uint8)
139
+ raw_schema = np.frombuffer(schema_bytes, dtype=np.uint8)
140
+ self._handle = _store.Store.create(
141
+ self._executor._handle, raw_path, CODECS[codec], data_shards,
142
+ raw_dict, raw_schema,
143
+ )
144
+ self.data_shards = data_shards
145
+ self._length = None
146
+ return self
147
+
148
+ def codec(self):
149
+ return self._handle.codec()
150
+
151
+ @property
152
+ def closed(self):
153
+ handle = getattr(self, "_handle", None)
154
+ return handle is None or handle.closed
155
+
156
+ def __len__(self):
157
+ if self._length is not None:
158
+ return self._length
159
+ return self._handle.length()
160
+
161
+ def close(self):
162
+ handle = getattr(self, "_handle", None)
163
+ if handle is not None:
164
+ self._handle = None
165
+ executor = self._executor
166
+ try:
167
+ handle.close(self.writable)
168
+ finally:
169
+ self._executor = None
170
+
171
+ def __del__(self):
172
+ try:
173
+ self.close()
174
+ except Exception:
175
+ pass
176
+
177
+ def dense_gather(self, idxs, dst, record_bytes):
178
+ self._handle.dense_gather(idxs, dst, record_bytes)
179
+
180
+ def dense_append(self, src, record_bytes):
181
+ return self._handle.dense_append(src, record_bytes)
182
+
183
+ def ragged_gather(self, idxs):
184
+ return self._handle.ragged_gather(idxs)
185
+
186
+ def ragged_append(self, owners, headers, payload_lengths, offsets):
187
+ return self._handle.ragged_append(
188
+ owners, headers, payload_lengths, offsets,
189
+ )
190
+
191
+
192
+ def _build_dict(samples, sizes, target):
193
+ """Train a standalone zstd dictionary from concatenated sample bytes."""
194
+ samples = np.frombuffer(samples, dtype=np.uint8) \
195
+ if isinstance(samples, (bytes, bytearray)) else samples
196
+ return _store.build_dict(samples, sizes, target)
loaderx/converter.py ADDED
@@ -0,0 +1,261 @@
1
+ """Convert Hugging Face datasets into ordinary Zrecord stores."""
2
+
3
+ from contextlib import ExitStack
4
+ from pathlib import Path
5
+ import os
6
+ import shutil
7
+ import tempfile
8
+
9
+ import numpy as np
10
+
11
+ from .zrecord import Dense, Ragged
12
+
13
+
14
+ __all__ = ["convert", "huggingface"]
15
+
16
+ _DECODE_BATCH_RECORDS = 64
17
+ _TARGET_BATCH_BYTES = 64 << 20
18
+ _MAX_BATCH_RECORDS = 32768
19
+
20
+
21
+ def _path_component(name, kind):
22
+ if (not isinstance(name, str) or not name or name in (".", "..")
23
+ or Path(name).name != name or "/" in name or "\\" in name):
24
+ raise ValueError(f"{kind} name {name!r} must be one path component")
25
+ return name
26
+
27
+
28
+ def _numeric_dtype(value):
29
+ try:
30
+ dtype = np.dtype(value)
31
+ except (TypeError, ValueError):
32
+ return None
33
+ return dtype if dtype.kind in "biufc" and dtype.itemsize else None
34
+
35
+
36
+ def _declared_schema(value):
37
+ name = type(value).__name__
38
+ dtype = _numeric_dtype(getattr(value, "dtype", None))
39
+ if name in ("Value", "ClassLabel"):
40
+ return None if dtype is None else (Dense, dtype, ())
41
+ shape = getattr(value, "shape", None)
42
+ if shape is not None and dtype is not None:
43
+ if all(dimension is not None and int(dimension) >= 0 for dimension in shape):
44
+ return Dense, dtype, tuple(int(dimension) for dimension in shape)
45
+ return Ragged, dtype, len(shape)
46
+ child = getattr(value, "feature", None)
47
+ if child is not None:
48
+ child_schema = _declared_schema(child)
49
+ if child_schema is not None:
50
+ child_kind, child_dtype, child_geometry = child_schema
51
+ length = getattr(value, "length", None)
52
+ if isinstance(length, int) and length >= 0 and child_kind is Dense:
53
+ return Dense, child_dtype, (length, *child_geometry)
54
+ child_ndim = len(child_geometry) if child_kind is Dense else child_geometry
55
+ return Ragged, child_dtype, child_ndim + 1
56
+ return None
57
+
58
+
59
+ def _decode_records(features):
60
+ if not features:
61
+ return _DECODE_BATCH_RECORDS
62
+ row_bytes = 0
63
+ for feature in features.values():
64
+ schema = _declared_schema(feature)
65
+ if schema is None or schema[0] is Ragged:
66
+ return _DECODE_BATCH_RECORDS
67
+ _, dtype, shape = schema
68
+ row_bytes += dtype.itemsize * max(1, int(np.prod(shape, dtype=np.intp)))
69
+ return min(_MAX_BATCH_RECORDS, max(1, _TARGET_BATCH_BYTES // row_bytes))
70
+
71
+
72
+ def _schema(feature, batch, column):
73
+ """Return ``(Dense/Ragged, dtype, shape/ndim)`` for one column."""
74
+ feature_schema = _declared_schema(feature) if feature is not None else None
75
+ if feature_schema is not None:
76
+ return feature_schema
77
+ if isinstance(batch, dict) or len(batch) == 0:
78
+ raise ValueError(f"column {column!r} is nested or empty and has no numeric schema")
79
+ first = batch[0]
80
+ if first is None:
81
+ raise ValueError(f"column {column!r} contains null values")
82
+ if isinstance(first, (str, np.str_)):
83
+ raise ValueError(f"column {column!r} contains strings, not numeric arrays")
84
+ if isinstance(first, (bytes, np.bytes_)):
85
+ raise ValueError(f"column {column!r} contains binary values, not numeric arrays")
86
+ array = np.asarray(first)
87
+ dtype = _numeric_dtype(array.dtype)
88
+ if dtype is None:
89
+ raise ValueError(f"column {column!r} has no numeric dtype")
90
+ if array.ndim == 0:
91
+ return Dense, dtype, ()
92
+ if isinstance(batch, np.ndarray) and batch.dtype != object:
93
+ return Dense, _numeric_dtype(batch.dtype), tuple(batch.shape[1:])
94
+ return Ragged, dtype, array.ndim
95
+
96
+
97
+ def _write_dataset(dataset, target, codec, dataset_type, iterable_type):
98
+ features = getattr(dataset, "features", None)
99
+ if isinstance(dataset, dataset_type):
100
+ decode_records = _decode_records(features)
101
+ dataset = dataset.with_format("numpy", dtype=None)
102
+ elif isinstance(dataset, iterable_type):
103
+ decode_records = _DECODE_BATCH_RECORDS
104
+ dataset = dataset.with_format(None)
105
+ else:
106
+ raise TypeError("convert requires a Hugging Face Dataset or IterableDataset")
107
+
108
+ batches = iter(dataset.iter(batch_size=decode_records))
109
+ try:
110
+ try:
111
+ first = next(batches)
112
+ except StopIteration:
113
+ raise ValueError("dataset is empty") from None
114
+ if not isinstance(first, dict) or not first:
115
+ raise TypeError("dataset batches must be non-empty dictionaries")
116
+ columns = [_path_component(column, "column") for column in first]
117
+ schemas = {
118
+ column: _schema(
119
+ features.get(column) if features is not None else None,
120
+ first[column],
121
+ column,
122
+ )
123
+ for column in columns
124
+ }
125
+
126
+ target.mkdir(exist_ok=True)
127
+ with ExitStack() as stack:
128
+ writers = {}
129
+ for column, (kind, dtype, geometry) in schemas.items():
130
+ if kind is Dense:
131
+ writer = Dense.create(target / column, dtype, geometry, codec=codec)
132
+ else:
133
+ writer = Ragged.create(target / column, dtype, geometry, codec=codec)
134
+ writers[column] = stack.enter_context(writer)
135
+
136
+ pending = {column: [] for column in columns}
137
+ pending_records = 0
138
+ pending_bytes = 0
139
+ records = 0
140
+ batch = first
141
+ while batch is not None:
142
+ if not isinstance(batch, dict) or set(batch) != set(columns):
143
+ raise ValueError("dataset columns changed during conversion")
144
+ lengths = {column: len(batch[column]) for column in columns}
145
+ count = next(iter(lengths.values()))
146
+ if any(length != count for length in lengths.values()):
147
+ raise ValueError(f"dataset columns have different batch lengths: {lengths}")
148
+ if count:
149
+ prepared = {}
150
+ batch_bytes = 0
151
+ for column, (kind, dtype, geometry) in schemas.items():
152
+ if kind is Dense:
153
+ values = np.asarray(batch[column], dtype=dtype)
154
+ prepared[column] = [values]
155
+ batch_bytes += values.nbytes
156
+ else:
157
+ values = [
158
+ np.asarray(record, dtype=dtype) for record in batch[column]
159
+ ]
160
+ prepared[column] = values
161
+ batch_bytes += sum(
162
+ value.nbytes + geometry * 8 for value in values
163
+ )
164
+ if pending_records and (
165
+ pending_bytes + batch_bytes > _TARGET_BATCH_BYTES or
166
+ pending_records + count > _MAX_BATCH_RECORDS):
167
+ _flush(writers, schemas, pending)
168
+ pending = {column: [] for column in columns}
169
+ pending_records = 0
170
+ pending_bytes = 0
171
+ for column in columns:
172
+ pending[column].extend(prepared[column])
173
+ pending_records += count
174
+ pending_bytes += batch_bytes
175
+ records += count
176
+ if (pending_bytes >= _TARGET_BATCH_BYTES or
177
+ pending_records >= _MAX_BATCH_RECORDS):
178
+ _flush(writers, schemas, pending)
179
+ pending = {column: [] for column in columns}
180
+ pending_records = 0
181
+ pending_bytes = 0
182
+ batch = next(batches, None)
183
+ if pending_records:
184
+ _flush(writers, schemas, pending)
185
+ if records == 0:
186
+ raise ValueError("dataset is empty")
187
+ finally:
188
+ close = getattr(batches, "close", None)
189
+ if callable(close):
190
+ close()
191
+
192
+
193
+ def _flush(writers, schemas, pending):
194
+ for column, (kind, _, _) in schemas.items():
195
+ values = pending[column]
196
+ if kind is Dense:
197
+ batch = values[0] if len(values) == 1 else np.concatenate(values, axis=0)
198
+ writers[column].append(batch)
199
+ else:
200
+ writers[column].append(values)
201
+
202
+
203
+ def convert(dataset, output, *, codec):
204
+ """Persist one Dataset or every split with internal byte-bounded appends."""
205
+ if codec not in ("raw", "zstd"):
206
+ raise ValueError("converter codec must be 'raw' or 'zstd'")
207
+ try:
208
+ from datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDict
209
+ except ImportError:
210
+ raise RuntimeError("convert needs the optional dependency loaderx[converter]") from None
211
+ if not isinstance(dataset, (Dataset, IterableDataset, DatasetDict, IterableDatasetDict)):
212
+ raise TypeError("convert requires a Hugging Face Dataset or DatasetDict")
213
+
214
+ output = Path(output)
215
+ if output.exists():
216
+ raise FileExistsError(f"output already exists: {output}")
217
+ output.parent.mkdir(parents=True, exist_ok=True)
218
+ temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent))
219
+ published = False
220
+ try:
221
+ if isinstance(dataset, (DatasetDict, IterableDatasetDict)):
222
+ if not dataset:
223
+ raise ValueError("DatasetDict is empty")
224
+ for split, source in dataset.items():
225
+ _write_dataset(
226
+ source,
227
+ temporary / _path_component(split, "split"),
228
+ codec,
229
+ Dataset,
230
+ IterableDataset,
231
+ )
232
+ else:
233
+ _write_dataset(dataset, temporary, codec, Dataset, IterableDataset)
234
+ if output.exists():
235
+ raise FileExistsError(f"output was created during conversion: {output}")
236
+ os.rename(temporary, output)
237
+ published = True
238
+ return output
239
+ finally:
240
+ if not published:
241
+ shutil.rmtree(temporary, ignore_errors=True)
242
+
243
+
244
+ def huggingface(repo_id, *, config=None, revision="main", token=None):
245
+ """Download a pinned Hugging Face repository and return its DatasetDict."""
246
+ try:
247
+ import datasets
248
+ from huggingface_hub import HfApi
249
+ except ImportError:
250
+ raise RuntimeError("huggingface needs loaderx[converter]") from None
251
+ commit = HfApi().dataset_info(
252
+ repo_id=repo_id, revision=revision, token=token,
253
+ ).sha
254
+ if not commit:
255
+ raise RuntimeError(f"Hugging Face did not resolve {repo_id!r} at {revision!r}")
256
+ dataset = datasets.load_dataset(
257
+ repo_id, name=config, revision=commit, token=token,
258
+ )
259
+ if not isinstance(dataset, datasets.DatasetDict) or not dataset:
260
+ raise TypeError("load_dataset did not return a non-empty DatasetDict")
261
+ return dataset