"""HDF5 files (Keras `.weights.h5`, legacy Keras `.h5`) and Keras 3 `.keras` files, through the optional `h5py`. See
DESIGN.md.
h5py reports where each dataset of contiguous layout sits in the file; Jabara compresses those bytes and keeps every
other byte of the file (the HDF5 metadata, small datasets that HDF5 stores inside their header) as they are. A chunked,
filtered (compressed), external, or virtual dataset is refused: its bytes are not in one place. A `.keras` file is a
zip whose members are stored as they are; its `model.weights.h5` member is read the same way.
"""
from __future__ import annotations
import importlib
import io
import mmap
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Any
import numpy as np
from pydantic import JsonValue
from jabara.errors import ArchiveFormatError, MissingDependencyError
from jabara.formats import splice
from jabara.formats._zip import stored_members
from jabara.formats.base import CheckpointFormat, Split
from jabara.formats.npy import dtype_name
from jabara.formats.registry import register_format
from jabara.formats.splice import Checksum, Span
from jabara.types import FLOAT_DTYPES, TensorMeta
_KERAS_WEIGHTS = "model.weights.h5"
# Where Keras 3 (`optimizer/`) and legacy Keras (`optimizer_weights/`) keep the optimizer state.
_OPTIMIZER = ("optimizer/", "optimizer_weights/")
def _h5py() -> Any: # noqa: ANN401 - h5py ships no types; it is an optional dependency loaded here
try:
return importlib.import_module("h5py")
except ImportError as e:
raise MissingDependencyError("reading an HDF5 file needs h5py: pip install 'jabara[hdf5]'") from e
class _Window(io.RawIOBase):
"""A read-only file object over `raw[start:end]`, so that h5py reads a zip member without a copy of it."""
def __init__(self, raw: mmap.mmap, start: int, end: int) -> None:
self.raw, self.start, self.end, self.at = raw, start, end, start
def readable(self) -> bool:
return True
def seekable(self) -> bool:
return True
def tell(self) -> int:
return self.at - self.start
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
base = {io.SEEK_SET: self.start, io.SEEK_CUR: self.at, io.SEEK_END: self.end}[whence]
self.at = max(self.start, base + offset)
return self.tell()
def readinto(self, buffer: Any) -> int: # noqa: ANN401 - a writable buffer of any kind
view = memoryview(buffer).cast("B")
n = max(0, min(len(view), self.end - self.at))
view[:n] = self.raw[self.at : self.at + n]
self.at += n
return n
def _dataset_spans(file: object, base: int, bad: Callable[[str], ArchiveFormatError]) -> list[Span]:
"""The datasets of the HDF5 file `file` (a path or a file object) whose bytes sit in one place, at `base` plus
their offset in it."""
h5py = _h5py()
spans: list[Span] = []
refused: list[str] = []
def visit(name: str, obj: object) -> None:
if not isinstance(obj, h5py.Dataset):
return
plist = obj.id.get_create_plist()
layout = plist.get_layout()
if layout == h5py.h5d.COMPACT: # stored inside its header: it stays in the remainder
return
if layout != h5py.h5d.CONTIGUOUS or plist.get_nfilters() or plist.get_external_count():
refused.append(name)
return
offset = obj.id.get_offset()
if offset is None: # never written: no bytes to take
return
size = obj.id.get_storage_size()
dtype = dtype_name(obj.dtype)
if dtype is None or int(np.prod(obj.shape)) * obj.dtype.itemsize != size:
meta = TensorMeta(name=name, dtype="uint8", shape=(size,), role="other")
else:
role = "weight" if dtype in FLOAT_DTYPES and not name.startswith(_OPTIMIZER) else "other"
meta = TensorMeta(name=name, dtype=dtype, shape=tuple(obj.shape), role=role)
spans.append(Span(base + offset, base + offset + size, meta))
try:
with h5py.File(file, "r") as f:
f.visititems(visit)
except Exception as e: # h5py raises OSError, RuntimeError, KeyError, OverflowError, ... for a damaged file
raise bad(f"h5py does not read it ({type(e).__name__}: {' '.join(str(e).split())})") from e
if refused:
raise bad(
f"dataset {refused[0]!r} is chunked, compressed, or stored elsewhere, so its bytes are not in one place"
)
return spans
[docs]
@register_format
class Hdf5(CheckpointFormat):
"""An HDF5 file, such as the `.weights.h5` that Keras 3 writes or a legacy Keras `.h5` model."""
kind = "hdf5"
names = ("*.h5", "*.hdf5")
in_directory = ()
frameworks = (("Keras 3 (save_weights), legacy Keras, h5py", "*.weights.h5, *.h5, *.hdf5"),)
[docs]
def split(self, path: Path) -> Split:
raw = splice.open_map(path, "an HDF5 file")
def bad(msg: str) -> ArchiveFormatError:
return ArchiveFormatError(f"{path}: {msg}")
return Split(*splice.cut(path, raw, _dataset_spans(path, 0, bad)))
[docs]
def join(
self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool
) -> None:
splice.join(source, remainder, tensors, out, exact=exact)
[docs]
@register_format
class Keras(CheckpointFormat):
"""A Keras 3 `.keras` file: a zip of `config.json`, `metadata.json`, and `model.weights.h5`, stored as they are."""
kind = "keras"
names = ("*.keras",)
in_directory = ()
frameworks = (("Keras 3 (model.save)", "*.keras"),)
[docs]
def split(self, path: Path) -> Split:
raw = splice.open_map(path, "a .keras file")
def bad(msg: str) -> ArchiveFormatError:
return ArchiveFormatError(f"{path}: not a .keras file that Jabara reads: {msg}")
members = stored_members(path, raw, bad, "Keras stores every member as it is")
weights = members.get(_KERAS_WEIGHTS)
if weights is None:
raise bad(f"no {_KERAS_WEIGHTS}")
spans = _dataset_spans(_Window(raw, weights.start, weights.end), weights.start, bad)
return Split(*splice.cut(path, raw, spans, [Checksum(weights.start, weights.end, weights.crc_at)]))
[docs]
def join(
self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool
) -> None:
splice.join(source, remainder, tensors, out, exact=exact)