jabara.formats.gguf のソースコード

"""GGUF files, the format of llama.cpp and the tools around it. See DESIGN.md.

A GGUF file is a header (magic, version, tensor and key-value counts), the key-value metadata, one entry per tensor
(name, dimensions, type, offset), then the tensor data, each tensor at an offset aligned to `general.alignment` (32
by default) from the start of the data section. The header is parsed with `struct` alone. A tensor of a float or
integer type keeps its dtype and the role `weight` (float) or `other`; a quantized tensor is kept as `uint8` with the
role `other`, its bytes as they are, padding up to the next tensor included.
"""

from __future__ import annotations

import mmap
import struct
from collections.abc import Iterable
from pathlib import Path

from pydantic import JsonValue

from jabara.errors import ArchiveFormatError
from jabara.formats import splice
from jabara.formats.base import CheckpointFormat, Split
from jabara.formats.registry import register_format
from jabara.formats.splice import Span
from jabara.types import DTYPE_ITEMSIZE, FLOAT_DTYPES, TensorMeta

_MAGIC = b"GGUF"
_VERSIONS = {2, 3}
# GGML tensor types that are plain arrays, by the dtype their bytes hold; every other type is quantized.
_PLAIN = {0: "float32", 1: "float16", 24: "int8", 25: "int16", 26: "int32", 27: "int64", 28: "float64", 30: "bfloat16"}
# Key-value types: the size of the fixed-size ones; 8 is a string and 9 an array.
_FIXED = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
_STRING, _ARRAY = 8, 9
_ALIGNMENT_KEY = "general.alignment"


class _Reader:
    """Reads the header of `raw` from the front; `ArchiveFormatError` for anything that runs past the end."""

    def __init__(self, path: Path, raw: mmap.mmap) -> None:
        self.path, self.raw, self.at = path, raw, 0

    def bad(self, msg: str) -> ArchiveFormatError:
        return ArchiveFormatError(f"{self.path}: not a GGUF file: {msg}")

    def take(self, fmt: str) -> tuple[int, ...]:
        size = struct.calcsize(fmt)
        if self.at + size > len(self.raw):
            raise self.bad("its header runs past the end of the file")
        values = struct.unpack_from(fmt, self.raw, self.at)
        self.at += size
        return values

    def string(self) -> str:
        (n,) = self.take("<Q")
        if self.at + n > len(self.raw):
            raise self.bad("a string runs past the end of the file")
        text = bytes(self.raw[self.at : self.at + n])
        self.at += n
        try:
            return text.decode("utf-8")
        except UnicodeDecodeError as e:
            raise self.bad("a string is not UTF-8") from e

    def value(self, kind: int) -> int | None:
        """Skip one value of type `kind`; return it when it is an unsigned integer (an alignment is one)."""
        if kind == _STRING:
            self.string()
        elif kind == _ARRAY:
            inner, n = self.take("<IQ")
            if inner in _FIXED:
                if self.at + n * _FIXED[inner] > len(self.raw):
                    raise self.bad("an array runs past the end of the file")
                self.at += n * _FIXED[inner]
            else:
                for _ in range(n):
                    self.value(inner)
        elif kind in _FIXED:
            fmt = {1: "<B", 2: "<H", 4: "<I", 8: "<Q"}[_FIXED[kind]]
            (v,) = self.take(fmt)
            return v
        else:
            raise self.bad(f"unknown metadata type {kind}")
        return None


def _spans(path: Path, raw: mmap.mmap) -> list[Span]:
    r = _Reader(path, raw)
    if raw[:4] != _MAGIC:
        raise r.bad("no GGUF magic")
    r.at = 4
    (version,) = r.take("<I")
    if version not in _VERSIONS:
        swapped = int.from_bytes(version.to_bytes(4, "little"), "big")
        why = "a big-endian GGUF file" if swapped in _VERSIONS else f"version {version}"
        raise r.bad(f"{why}; Jabara reads little-endian GGUF of versions 2 and 3")
    n_tensors, n_kv = r.take("<QQ")
    alignment = 32
    for _ in range(n_kv):
        key = r.string()
        (kind,) = r.take("<I")
        value = r.value(kind)
        if key == _ALIGNMENT_KEY:
            if not value:
                raise r.bad(f"{_ALIGNMENT_KEY} is not a positive integer")
            alignment = value
    entries = []
    for _ in range(n_tensors):
        name = r.string()
        (n_dims,) = r.take("<I")
        dims = r.take(f"<{n_dims}Q")
        kind, offset = r.take("<IQ")
        entries.append((name, kind, dims, offset))
    data = -(-r.at // alignment) * alignment
    if not entries:  # a file of metadata alone (a vocabulary, say): all of it is the remainder
        return []
    ordered = sorted(entries, key=lambda e: e[3])
    ends = [data + e[3] for e in ordered[1:]] + [len(raw)]
    spans = []
    for (name, kind, dims, offset), next_start in zip(ordered, ends, strict=True):
        start = data + offset
        if offset % alignment or start > next_start:
            raise r.bad(f"tensor {name!r} is not at an aligned offset inside the file")
        shape = tuple(reversed(dims))  # GGUF lists the fastest-varying dimension first
        dtype = _PLAIN.get(kind)
        if dtype is not None:
            size = DTYPE_ITEMSIZE[dtype] * _count(shape)
            if start + size > next_start:
                raise r.bad(f"tensor {name!r} runs into the next tensor or past the end of the file")
            role = "weight" if dtype in FLOAT_DTYPES else "other"
            spans.append(Span(start, start + size, TensorMeta(name=name, dtype=dtype, shape=shape, role=role)))
        else:  # quantized: its bytes run up to the next tensor
            meta = TensorMeta(name=name, dtype="uint8", shape=(next_start - start,), role="other")
            spans.append(Span(start, next_start, meta))
    return spans


def _count(shape: tuple[int, ...]) -> int:
    n = 1
    for d in shape:
        n *= d
    return n


[ドキュメント] @register_format class Gguf(CheckpointFormat): """A GGUF file (llama.cpp): the header and the metadata kept as they are, every tensor compressed.""" kind = "gguf" names = ("*.gguf",) in_directory = () frameworks = (("llama.cpp, and the tools that convert models for it", "*.gguf"),)
[ドキュメント] def split(self, path: Path) -> Split: raw = splice.open_map(path, "a GGUF file") try: spans = _spans(path, raw) except RecursionError as e: # arrays nested deeper than Python's stack raise ArchiveFormatError(f"{path}: not a GGUF file: its metadata nests too deep") from e return Split(*splice.cut(path, raw, spans))
[ドキュメント] 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)