Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

10.8 KB
Raw Blame
"""Read-only GGUF metadata inspection.

The dashboard only needs lightweight model metadata for fit/performance
reporting. This parser intentionally stops after the GGUF metadata header and
never reads tensor data, so it is safe to run against very large model files.
"""

from __future__ import annotations

import logging
import struct
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)


_GGUF_VALUE_TYPES = {
    0: "uint8",
    1: "int8",
    2: "uint16",
    3: "int16",
    4: "uint32",
    5: "int32",
    6: "float32",
    7: "bool",
    8: "string",
    9: "array",
    10: "uint64",
    11: "int64",
    12: "float64",
}

_STRUCTS = {
    0: "<B",
    1: "<b",
    2: "<H",
    3: "<h",
    4: "<I",
    5: "<i",
    6: "<f",
    7: "<?",
    10: "<Q",
    11: "<q",
    12: "<d",
}

# GGUF arrays may nest (item type 9 is itself "array"), so a crafted file can
# chain arrays deep enough to exhaust the interpreter stack. Real exporters emit
# flat arrays, so bound the depth and degrade gracefully instead of letting a
# RecursionError escape this parser's failure contract.
_MAX_ARRAY_DEPTH = 64

# general.file_type uses llama_ftype / LlamaFileType, not GGML tensor type IDs.
# https://github.com/ggml-org/llama.cpp/blob/95887577ab5fead779581a7030a83c7752ff3234/include/llama.h#L106-L150
_FILE_TYPE_LABELS = {
    0: "F32",
    1: "F16",
    2: "Q4_0",
    3: "Q4_1",
    7: "Q8_0",
    8: "Q5_0",
    9: "Q5_1",
    10: "Q2_K",
    11: "Q3_K_S",
    12: "Q3_K_M",
    13: "Q3_K_L",
    14: "Q4_K_S",
    15: "Q4_K_M",
    16: "Q5_K_S",
    17: "Q5_K_M",
    18: "Q6_K",
    19: "IQ2_XXS",
    20: "IQ2_XS",
    21: "Q2_K_S",
    22: "IQ3_XS",
    23: "IQ3_XXS",
    24: "IQ1_S",
    25: "IQ4_NL",
    26: "IQ3_S",
    27: "IQ3_M",
    28: "IQ2_S",
    29: "IQ2_M",
    30: "IQ4_XS",
    31: "IQ1_M",
    32: "BF16",
    36: "TQ1_0",
    37: "TQ2_0",
}


class GGUFTruncated(ValueError):
    """The bytes end before the GGUF metadata block does."""


class NotGGUF(ValueError):
    """The bytes do not start with the GGUF magic."""


class _Reader:
    def __init__(self, data: bytes):
        self.data = data
        self.offset = 0

    def read(self, size: int) -> bytes:
        if self.offset + size > len(self.data):
            raise GGUFTruncated("GGUF metadata ended unexpectedly")
        chunk = self.data[self.offset:self.offset + size]
        self.offset += size
        return chunk

    def skip(self, size: int) -> None:
        if self.offset + size > len(self.data):
            raise GGUFTruncated("GGUF metadata ended unexpectedly")
        self.offset += size

    def unpack(self, fmt: str):
        size = struct.calcsize(fmt)
        return struct.unpack(fmt, self.read(size))[0]

    def string(self) -> str:
        length = self.unpack("<Q")
        return self.read(length).decode("utf-8", errors="replace")


def _read_value(reader: _Reader, value_type: int, depth: int = 0) -> Any:
    if value_type in _STRUCTS:
        return reader.unpack(_STRUCTS[value_type])
    if value_type == 8:
        return reader.string()
    if value_type == 9:
        return _read_array(reader, depth)
    raise ValueError(f"unsupported GGUF value type: {value_type}")


def _skip_value(reader: _Reader, value_type: int, depth: int = 0) -> None:
    if value_type in _STRUCTS:
        reader.skip(struct.calcsize(_STRUCTS[value_type]))
        return
    if value_type == 8:
        length = reader.unpack("<Q")
        reader.skip(length)
        return
    if value_type == 9:
        if depth >= _MAX_ARRAY_DEPTH:
            raise ValueError("GGUF array nesting too deep")
        item_type = reader.unpack("<I")
        length = reader.unpack("<Q")
        if item_type in _STRUCTS:
            reader.skip(struct.calcsize(_STRUCTS[item_type]) * length)
            return
        for _ in range(length):
            _skip_value(reader, item_type, depth + 1)
        return
    raise ValueError(f"unsupported GGUF value type: {value_type}")


def _read_array(reader: _Reader, depth: int = 0) -> Any:
    if depth >= _MAX_ARRAY_DEPTH:
        raise ValueError("GGUF array nesting too deep")
    item_type = reader.unpack("<I")
    length = reader.unpack("<Q")
    if item_type not in _STRUCTS and item_type not in (8, 9):
        raise ValueError(f"unsupported GGUF array type: {item_type}")

    sample_limit = 64
    sample = [_read_value(reader, item_type, depth + 1) for _ in range(min(length, sample_limit))]
    remaining = max(length - sample_limit, 0)
    if item_type in _STRUCTS:
        # Tokenizer score/type arrays can contain hundreds of thousands of
        # entries. Their unused fixed-width tail needs only one bounds check.
        reader.skip(struct.calcsize(_STRUCTS[item_type]) * remaining)
    else:
        for _ in range(remaining):
            _skip_value(reader, item_type, depth + 1)

    if length <= sample_limit:
        return sample
    return {
        "type": "array",
        "item_type": _GGUF_VALUE_TYPES.get(item_type, str(item_type)),
        "length": length,
        "sample": sample,
    }


def _first_int(metadata: dict[str, Any], suffixes: tuple[str, ...]) -> int | None:
    for key, value in metadata.items():
        if key.endswith(suffixes) and isinstance(value, int) and not isinstance(value, bool):
            return value
    return None


def _first_int_or_list(
    metadata: dict[str, Any], suffixes: tuple[str, ...]
) -> int | list[int] | None:
    for key, value in metadata.items():
        if not key.endswith(suffixes):
            continue
        if isinstance(value, int) and not isinstance(value, bool):
            return value
        if isinstance(value, list) and all(
            isinstance(item, int) and not isinstance(item, bool) for item in value
        ):
            return value
    return None


def _first_value(metadata: dict[str, Any], suffixes: tuple[str, ...]) -> Any:
    for key, value in metadata.items():
        if key.endswith(suffixes):
            return value
    return None


def inspect_gguf(path: Path | str, max_metadata_bytes: int = 32 * 1024 * 1024) -> dict[str, Any]:
    """Return normalized GGUF metadata, degrading to ``unknown`` on failure."""
    p = Path(path)
    result: dict[str, Any] = {
        "path": str(p),
        "exists": p.exists(),
        "format": "gguf",
        "readable": False,
        "architecture": "unknown",
        "quantization": "unknown",
        "metadata": {},
    }
    if not p.exists() or not p.is_file():
        return result

    try:
        result["size_bytes"] = p.stat().st_size
        with p.open("rb") as f:
            data = f.read(max_metadata_bytes)
        result.update(parse_gguf_metadata(data))
    except NotGGUF:
        result["error"] = "not a GGUF file"
    except (OSError, UnicodeDecodeError, ValueError, struct.error) as exc:
        logger.debug("Failed to inspect GGUF %s: %s", p, exc)
        result["error"] = str(exc)
    return result


_MAX_TENSOR_DIMS = 8  # GGML_MAX_DIMS is 4; anything past 8 is not a tensor table


def _tensor_types(reader: _Reader, tensor_count: int) -> list[int] | None:
    """Distinct ggml types in the tensor-info table that follows the metadata.

    Each entry is a name, a dimension count, the dimensions, a ggml type and
    an offset. Returns None when ``data`` ends inside the table: the metadata
    is still complete, and a ranged reader may fetch more to learn the types.
    """
    types: set[int] = set()
    try:
        for _ in range(tensor_count):
            reader.skip(reader.unpack("<Q"))
            dims = reader.unpack("<I")
            if dims > _MAX_TENSOR_DIMS:
                raise ValueError(f"tensor with {dims} dimensions")
            reader.skip(8 * dims)
            types.add(reader.unpack("<I"))
            reader.skip(8)
    except GGUFTruncated:
        return None
    return sorted(types)


def parse_gguf_metadata(data: bytes) -> dict[str, Any]:
    """Normalize the GGUF metadata block at the start of ``data``.

    Raises :class:`NotGGUF` for other formats and :class:`GGUFTruncated` when
    ``data`` ends inside the metadata block, so a ranged reader can fetch more.
    Other malformed input raises ``ValueError``, ``struct.error`` or
    ``UnicodeDecodeError``.
    """
    reader = _Reader(data)
    if reader.read(4) != b"GGUF":
        raise NotGGUF("not a GGUF file")
    version = reader.unpack("<I")
    tensor_count = reader.unpack("<Q")
    metadata_count = reader.unpack("<Q")
    metadata: dict[str, Any] = {}
    for _ in range(metadata_count):
        key = reader.string()
        value_type = reader.unpack("<I")
        metadata[key] = _read_value(reader, value_type)
    metadata_bytes = reader.offset
    tensor_types = _tensor_types(reader, tensor_count)

    file_type = metadata.get("general.file_type")
    architecture = metadata.get("general.architecture", "unknown")
    return {
        "readable": True,
        "version": version,
        "tensor_count": tensor_count,
        "metadata_count": metadata_count,
        "metadata_bytes": metadata_bytes,
        "tensor_types": tensor_types,
        "architecture": architecture if isinstance(architecture, str) else "unknown",
        "file_type": file_type,
        "quantization": _FILE_TYPE_LABELS.get(file_type, str(file_type) if file_type is not None else "unknown"),
        "context_length": _first_int(metadata, (".context_length",)),
        "block_count": _first_int(metadata, (".block_count",)),
        "embedding_length": _first_int(metadata, (".embedding_length",)),
        "attention_head_count": _first_int(metadata, (".attention.head_count",)),
        "attention_head_count_kv": _first_int_or_list(
            metadata, (".attention.head_count_kv",)
        ),
        "attention_key_length": _first_int(
            metadata, (".attention.key_length",)
        ),
        "attention_value_length": _first_int(
            metadata, (".attention.value_length",)
        ),
        "rope_dimension_count": _first_int(metadata, (".rope.dimension_count",)),
        # Hybrid attention/recurrent layouts (llama.cpp llama-arch.cpp
        # LLM_KV_FULL_ATTENTION_INTERVAL and LLM_KV_SSM_*): only every
        # Nth layer of a Qwen3.5/3.6-style model holds a KV cache.
        "full_attention_interval": _first_int(metadata, (".full_attention_interval",)),
        "ssm_conv_kernel": _first_int(metadata, (".ssm.conv_kernel",)),
        "ssm_inner_size": _first_int(metadata, (".ssm.inner_size",)),
        "ssm_state_size": _first_int(metadata, (".ssm.state_size",)),
        "ssm_group_count": _first_int(metadata, (".ssm.group_count",)),
        "ssm_time_step_rank": _first_int(metadata, (".ssm.time_step_rank",)),
        "expert_count": _first_int(metadata, (".expert_count", ".expert.count")),
        "expert_used_count": _first_int(metadata, (".expert_used_count", ".expert.used_count")),
        "model_name": _first_value(metadata, ("general.name",)),
        "metadata": metadata,
    }