Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions changelog.d/checkpoint-text-without-per-value-loop.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Frame checkpoints (`microcosm.build.frame_checkpoint`) now write and read a text column, string index or strata whose values are all strings, none missing, without a Python loop over each value. They produce and parse the same `object_scalars_v1` bytes as before: a tag byte before each value's UTF-8 bytes, and the end offset of every value after a leading 0.

- **pyarrow-backed `str` and `string` columns:** written from the column's Arrow buffers with NumPy, after widening every chunk to 64-bit offsets.
- **Object and python-backed columns:** a value takes the new path only if its type is exactly `str` or `np.str_`.
- Values are encoded with `str.encode` through `map`, 8,192 at a time. Each batch is joined with `bytes.join`, and the batches are joined once.
- Arrow is not used for these values, because it attaches a cached UTF-8 copy to every non-ASCII Python string it reads.
- **Reading:** checks the offsets as before, then moves the text in place in the array HDF5 fills, about 1 MiB at a time, dropping the tag bytes. It checks UTF-8 with Arrow and restores the declared dtype, string storage and NA marker.

These still use the per-value code, which raises the same errors as before:
- columns with a missing value, a value that is not a string, or a `str` subclass;
- a string that cannot be encoded as UTF-8, or a stored value that is not valid UTF-8;
- offsets outside the payload;
- a pyarrow-backed column that pandas refuses to build from one Arrow array.

Checkpoint files, format versions 2 and 3, and recorded file digests are unchanged. Loaded frames hold the same values, dtypes, string storage and NA markers.

Peak memory, measured with `tracemalloc`:
- **Writing Python strings:** at most the per-value code's (0.96–1.00 times).
- **Reading object and python-backed columns:** within 1% of before.
- **pyarrow-backed columns:** both directions now hold the text in NumPy arrays instead of Python strings plus an Arrow copy.

Timings on a synthetic copy of the 15 text series of one post-clone US base checkpoint (9.85 million values), on a 10-core Mac at load 14–17:
- **Converting the text:** writing went from 8.78 s to 0.59 s, and reading from 4.89 s to 0.39 s.
- **A whole 253 MB checkpoint of those series:** writing went from 7.76 s to 1.02 s, and loading from 6.67 s to 1.86 s.
292 changes: 277 additions & 15 deletions packages/microcosm-build/src/microcosm/build/frame_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@

Object columns use a small deterministic scalar codec. Checkpoints are local
build artifacts and must not be loaded from untrusted sources.

A column of strings with no missing value is converted without a Python loop
over each value: pyarrow-backed columns through their Arrow buffers, Python
strings with ``str.encode`` and ``bytes.join``, and reading with NumPy and
Arrow. It produces and parses the same bytes as the per-value codec, which
still handles every other column.
"""

from __future__ import annotations
Expand All @@ -16,13 +22,14 @@
import math
import os
import struct
from collections.abc import Mapping
from collections.abc import Iterator, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd
import pyarrow as pa

from microcosm.frame import (
EntitySchema,
Expand Down Expand Up @@ -67,6 +74,18 @@
_TAG_STRING = 7
_TAG_BYTES = 8

_STRING_TAG_BYTE = bytes([_TAG_STRING])
# The identities of the value types whose bytes the per-value codec takes
# from ``str.encode``. Types are compared by identity: a metaclass can make
# another type hash like ``str`` and compare equal to it, or not hash at all.
_PLAIN_STRING_TYPE_IDS = np.asarray([id(str), id(np.str_)], dtype=np.uintp)
# How many Python strings are encoded at a time, which bounds the temporary
# ``bytes`` objects and ``bytes.join``'s buffer table.
_STRING_ENCODE_BATCH = 8_192
# About how many payload bytes each step of placing or removing the tag bytes
# covers, which bounds that step's temporary mask and copy.
_TAG_BYTE_STEP_BYTES = 1 << 20

_SUPPORTED_OBJECT_INFERRED_DTYPES = frozenset(
{
"boolean",
Expand Down Expand Up @@ -562,9 +581,10 @@ def _write_series(group: Any, series: pd.Series, spec: Mapping[str, object]) ->
_write_numpy_dataset(group, "values", values)
return
if encoding == _ENCODING_OBJECT:
offsets, payload = _encode_object_values(
series.to_numpy(dtype=object, copy=False)
)
encoded = _encode_string_values(series)
if encoded is None:
encoded = _encode_object_values(series.to_numpy(dtype=object, copy=False))
offsets, payload = encoded
_write_numpy_dataset(group, "offsets", offsets)
_write_bytes_dataset(group, "payload", payload)
return
Expand Down Expand Up @@ -603,10 +623,7 @@ def _read_series(
)
series = pd.Series(values.view(np.dtype(dtype)), copy=False)
elif encoding == _ENCODING_OBJECT:
offsets = _read_numpy_dataset(group, "offsets", path)
payload = _read_bytes_dataset(group, "payload", path)
values = _decode_object_values(offsets, payload, path=path, label=label)
series = pd.Series(values, dtype=restore_dtype, copy=False)
series = _read_object_series(group, restore_dtype, path=path, label=label)
elif encoding == _ENCODING_NULLABLE_BOOLEAN:
if dtype != "boolean":
raise ValueError(
Expand Down Expand Up @@ -759,21 +776,262 @@ def _encode_object_scalar(value: object) -> bytes:
)


def _decode_object_values(
offsets: np.ndarray,
payload: bytes,
def _encode_string_values(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | None:
"""The per-value codec's offsets and payload, without a loop over values.

The per-value codec stores each value as the string tag byte followed by
its UTF-8 bytes, and ``offsets[i + 1]`` is where value ``i`` ends.
Returns ``None`` when a value is missing or is not a string, or when a
value cannot be converted; the per-value codec writes those columns and
raises its own errors.
"""

dtype = series.dtype
if isinstance(dtype, pd.StringDtype) and dtype.storage == "pyarrow":
return _encode_arrow_strings(series)
return _encode_python_strings(series.to_numpy(dtype=object, copy=False))


def _encode_arrow_strings(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | None:
"""Offsets and payload from a pyarrow-backed column's Arrow buffers.

The Arrow array holds the values' UTF-8 bytes back to back with its own
end offsets, so in the payload value ``i`` ends ``i + 1`` tag bytes later.
"""

try:
stored = pa.array(series.array)
if stored.null_count:
return None
# Widen each chunk to 64-bit offsets before joining the chunks, so
# text past 2**31 bytes never passes through 32-bit offsets.
strings = stored.cast(pa.large_string())
if isinstance(strings, pa.ChunkedArray):
strings = strings.combine_chunks()
strings.validate(full=True) # UTF-8, as the per-value encode requires
except (pa.ArrowInvalid, pa.ArrowTypeError):
return None
value_count = len(strings)
if value_count == 0:
return np.zeros(1, dtype=np.int64), np.empty(0, dtype=np.uint8)
_validity, offsets_buffer, data_buffer = strings.buffers()
# Arrow allows spare bytes after the offsets, so read exactly the
# array's own offsets rather than the whole buffer.
string_offsets = np.frombuffer(
offsets_buffer,
dtype=np.int64,
count=value_count + 1,
offset=strings.offset * np.dtype(np.int64).itemsize,
)
first, last = int(string_offsets[0]), int(string_offsets[-1])
offsets = string_offsets - first + np.arange(value_count + 1, dtype=np.int64)
payload = np.empty(int(offsets[-1]), dtype=np.uint8)
payload[offsets[:-1]] = _TAG_STRING
if last > first:
text = np.frombuffer(
data_buffer, dtype=np.uint8, count=last - first, offset=first
)
for first_value, stop_value in _value_steps(offsets):
start_byte, stop_byte = int(offsets[first_value]), int(offsets[stop_value])
is_value_byte = np.ones(stop_byte - start_byte, dtype=np.bool_)
is_value_byte[offsets[first_value:stop_value] - start_byte] = False
payload[start_byte:stop_byte][is_value_byte] = text[
start_byte - first_value : stop_byte - stop_value
]
return offsets, payload


def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None:
"""Offsets and payload for an object array of ``str`` values.

Only exact ``str`` and ``np.str_`` values qualify. The per-value codec
calls each value's own ``encode``, which a subclass can override; these
two types use ``str.encode`` and take no instance attributes.

The values are encoded with ``str.encode`` through ``map``, a batch at a
time; each batch is joined with ``bytes.join``, and the batches are
joined once at the end. Arrow is not used: it reads a ``str`` with
CPython's ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside
every non-ASCII string for the rest of that string's life.
"""

# infer_dtype refuses most other columns cheaply; the identity check
# then refuses str subclasses, which infer_dtype counts as strings.
if pd.api.types.infer_dtype(values, skipna=False) not in ("string", "empty"):
return None
value_count = len(values)
type_ids = np.fromiter(
map(id, map(type, values)), dtype=np.uintp, count=value_count
)
if not np.isin(type_ids, _PLAIN_STRING_TYPE_IDS).all():
return None
del type_ids
# Each value's UTF-8 length goes to offsets[i + 1]; adding the tag byte
# to each and summing in place then gives the end of every value.
offsets = np.zeros(value_count + 1, dtype=np.int64)
batches: list[bytes] = []
try:
for start in range(0, value_count, _STRING_ENCODE_BATCH):
encoded = list(
map(str.encode, values[start : start + _STRING_ENCODE_BATCH])
)
offsets[start + 1 : start + 1 + len(encoded)] = np.fromiter(
map(len, encoded), dtype=np.int64, count=len(encoded)
)
# Joining after a leading empty value puts a tag before each value.
encoded.insert(0, b"")
joined = _STRING_TAG_BYTE.join(encoded)
del encoded
batches.append(joined)
del joined
except UnicodeEncodeError:
return None
offsets[1:] += 1
np.cumsum(offsets, out=offsets)
payload = batches[0] if len(batches) == 1 else b"".join(batches)
del batches
return offsets, np.frombuffer(payload, dtype=np.uint8)


def _value_steps(offsets: np.ndarray) -> Iterator[tuple[int, int]]:
"""Consecutive ranges of whole values, each about one step of bytes.

Each range ``(first, stop)`` covers values ``first`` to ``stop - 1``,
payload bytes ``offsets[first]`` to ``offsets[stop]``. A value longer
than a step makes its range longer.
"""

value_count = len(offsets) - 1
targets = np.arange(
_TAG_BYTE_STEP_BYTES, int(offsets[-1]), _TAG_BYTE_STEP_BYTES, dtype=np.int64
)
inner = np.searchsorted(offsets, targets).clip(1, max(value_count - 1, 1))
boundaries = np.unique(np.concatenate([[0], inner, [value_count]]))
return zip(boundaries[:-1].tolist(), boundaries[1:].tolist(), strict=True)


def _read_object_series(
group: Any,
restore_dtype: str | pd.BooleanDtype | pd.StringDtype,
*,
path: Path,
label: str,
) -> np.ndarray:
) -> pd.Series:
"""Read an ``object_scalars_v1`` series, without the per-value loop if able.

The per-value loop gets the payload as ``bytes``, with the array HDF5
filled dropped first, as before.
"""

offsets = _read_numpy_dataset(group, "offsets", path)
payload = _read_uint8_dataset(group, "payload", path)
_check_object_offsets(offsets, len(payload), path=path, label=label)
if _holds_only_strings(offsets, payload, restore_dtype):
series = _decode_string_values(offsets, payload, restore_dtype)
del payload
if series is not None:
return series
# The conversion rewrote both arrays in place; read the stored ones
# again for the per-value loop, which reports the invalid value.
offsets = _read_numpy_dataset(group, "offsets", path)
payload = _read_uint8_dataset(group, "payload", path)
payload_bytes = payload.tobytes()
del payload
values = _decode_object_values(offsets, payload_bytes, path=path, label=label)
return pd.Series(values, dtype=restore_dtype, copy=False)


def _holds_only_strings(
offsets: np.ndarray,
payload: np.ndarray,
restore_dtype: str | pd.BooleanDtype | pd.StringDtype,
) -> bool:
"""Whether checked offsets and payload hold only strings of a text dtype.

False when the declared dtype is not text, when an offset lies outside
the payload, or when a value's tag is not the string tag. The boundary
check compares differences, which wrap around when offsets far outside
the payload overflow int64; the per-value codec reads such offsets and
raises its own error.
"""

is_object = isinstance(restore_dtype, str) and restore_dtype == "object"
if not (is_object or isinstance(restore_dtype, pd.StringDtype)):
return False
if offsets.min() < 0 or offsets.max() > len(payload):
return False
return bool((payload[offsets[:-1]] == _TAG_STRING).all())


def _decode_string_values(
offsets: np.ndarray,
payload: np.ndarray,
restore_dtype: str | pd.StringDtype,
) -> pd.Series | None:
"""Parse offsets and payload for which ``_holds_only_strings`` holds.

Rewrites both arrays in place, so neither holds the stored values
afterwards: the text moves to the front of ``payload``, without the tag
bytes, and ``offsets`` become the text's own end offsets. A restored
pyarrow-backed column keeps both arrays. Returns ``None`` when a value is not
valid UTF-8, or when pandas refuses to build a pyarrow-backed column
from the Arrow array; the per-value codec then reads the column.
"""

value_count = len(offsets) - 1
for first_value, stop_value in _value_steps(offsets):
start_byte, stop_byte = int(offsets[first_value]), int(offsets[stop_value])
is_value_byte = np.ones(stop_byte - start_byte, dtype=np.bool_)
is_value_byte[offsets[first_value:stop_value] - start_byte] = False
# Every earlier step wrote below this step's bytes, and this step
# writes from its own start downwards, so no unread byte is lost.
payload[start_byte - first_value : stop_byte - stop_value] = payload[
start_byte:stop_byte
][is_value_byte]
offsets -= np.arange(value_count + 1, dtype=np.int64)
strings = pa.LargeStringArray.from_buffers(
value_count,
pa.py_buffer(offsets),
pa.py_buffer(payload[: len(payload) - value_count]),
)
try:
strings.validate(full=True) # UTF-8, as the per-value decode checks
except pa.ArrowInvalid:
return None
if isinstance(restore_dtype, pd.StringDtype) and restore_dtype.storage == "pyarrow":
try:
restored = pd.array(strings, dtype=restore_dtype)
except pa.ArrowInvalid:
# pandas 2.2 casts one Arrow array to 32-bit offsets, which
# refuses 2**31 or more bytes of text.
return None
return pd.Series(restored, copy=False)
return pd.Series(
strings.to_numpy(zero_copy_only=False), dtype=restore_dtype, copy=False
)


def _check_object_offsets(
offsets: np.ndarray, payload_size: int, *, path: Path, label: str
) -> None:
if offsets.ndim != 1 or offsets.dtype != np.dtype(np.int64) or len(offsets) < 1:
raise ValueError(
f"Frame checkpoint {path} {label!r} has malformed object offsets."
)
if offsets[0] != 0 or offsets[-1] != len(payload) or (np.diff(offsets) < 1).any():
if offsets[0] != 0 or offsets[-1] != payload_size or (np.diff(offsets) < 1).any():
raise ValueError(
f"Frame checkpoint {path} {label!r} has invalid object boundaries."
)


def _decode_object_values(
offsets: np.ndarray,
payload: bytes,
*,
path: Path,
label: str,
) -> np.ndarray:
_check_object_offsets(offsets, len(payload), path=path, label=label)
values = np.empty(len(offsets) - 1, dtype=object)
for index, (start, stop) in enumerate(zip(offsets[:-1], offsets[1:], strict=True)):
chunk = payload[int(start) : int(stop)]
Expand Down Expand Up @@ -812,7 +1070,7 @@ def _write_numpy_dataset(group: Any, name: str, values: np.ndarray) -> None:
group.create_dataset(name, data=np.asarray(values), track_times=False)


def _write_bytes_dataset(group: Any, name: str, value: bytes) -> None:
def _write_bytes_dataset(group: Any, name: str, value: bytes | np.ndarray) -> None:
group.create_dataset(
name,
data=np.frombuffer(value, dtype=np.uint8),
Expand All @@ -826,12 +1084,16 @@ def _read_numpy_dataset(group: Any, name: str, path: Path) -> np.ndarray:


def _read_bytes_dataset(group: Any, name: str, path: Path) -> bytes:
return _read_uint8_dataset(group, name, path).tobytes()


def _read_uint8_dataset(group: Any, name: str, path: Path) -> np.ndarray:
values = _read_numpy_dataset(group, name, path)
if values.ndim != 1 or values.dtype != np.dtype(np.uint8):
raise ValueError(
f"Frame checkpoint {path} HDF dataset {name!r} must be uint8 bytes."
)
return values.tobytes()
return values


def _read_metadata(root: Any, path: Path) -> dict[str, Any]:
Expand Down
Loading
Loading