Files

486 lines
17 KiB
Python

"""Чтение метаданных GGUF без загрузки весов.
Модуль разбирает только заголовок и блок key-value в начале файла.
Тензоры и большие массивы (словари токенизатора) пропускаются через
seek, поэтому память остаётся маленькой даже для моделей на десятки
гигабайт. Сторонние библиотеки и сеть не используются.
"""
import os
import re
import struct
# --- ограничения, чтобы битый файл не съел память/время -------------------
MAX_METADATA_BYTES = 32 * 1024 * 1024
MAX_STRING_BYTES = 4 * 1024 * 1024
MAX_TRAVERSED_BYTES = 512 * 1024 * 1024
MAX_ARRAY_DEPTH = 8
MAX_KV_COUNT = 1_000_000
MAX_TENSOR_COUNT = 100_000_000
MAX_KEY_BYTES = 64 * 1024
GGUF_MAGIC = b"GGUF"
# Типы значений метаданных GGUF (спецификация v2/v3).
GGUF_VALUE_UINT8 = 0
GGUF_VALUE_INT8 = 1
GGUF_VALUE_UINT16 = 2
GGUF_VALUE_INT16 = 3
GGUF_VALUE_UINT32 = 4
GGUF_VALUE_INT32 = 5
GGUF_VALUE_FLOAT32 = 6
GGUF_VALUE_BOOL = 7
GGUF_VALUE_STRING = 8
GGUF_VALUE_ARRAY = 9
GGUF_VALUE_UINT64 = 10
GGUF_VALUE_INT64 = 11
GGUF_VALUE_FLOAT64 = 12
# Соответствие general.file_type -> названию квантизации (ggml/llama.cpp).
GGUF_FILE_TYPES = {
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: "IQ2_S",
22: "IQ3_XXS",
23: "IQ3_XS",
24: "IQ1_S",
25: "IQ4_NL",
26: "IQ3_S",
27: "IQ4_XS",
28: "IQ1_M",
29: "BF16",
30: "Q4_0_4_4",
31: "Q4_0_4_8",
32: "Q4_0_8_8",
33: "TQ1_0",
34: "TQ2_0",
# Более новые типы ggml; неизвестные значения не считаются ошибкой.
35: "IQ4_NL_4_4",
36: "IQ4_NL_4_8",
37: "IQ4_NL_8_8",
38: "MXFP4_MOE",
}
# Фиксированный размер значения в байтах (кроме STRING/ARRAY).
_FIXED_SIZES = {
GGUF_VALUE_UINT8: 1,
GGUF_VALUE_INT8: 1,
GGUF_VALUE_UINT16: 2,
GGUF_VALUE_INT16: 2,
GGUF_VALUE_UINT32: 4,
GGUF_VALUE_INT32: 4,
GGUF_VALUE_FLOAT32: 4,
GGUF_VALUE_BOOL: 1,
GGUF_VALUE_UINT64: 8,
GGUF_VALUE_INT64: 8,
GGUF_VALUE_FLOAT64: 8,
}
_FIXED_FORMATS = {
GGUF_VALUE_UINT8: "<B",
GGUF_VALUE_INT8: "<b",
GGUF_VALUE_UINT16: "<H",
GGUF_VALUE_INT16: "<h",
GGUF_VALUE_UINT32: "<I",
GGUF_VALUE_INT32: "<i",
GGUF_VALUE_FLOAT32: "<f",
GGUF_VALUE_BOOL: "<?",
GGUF_VALUE_UINT64: "<Q",
GGUF_VALUE_INT64: "<q",
GGUF_VALUE_FLOAT64: "<d",
}
# Квантизация в имени файла: Q8_0, Q4_K_M, IQ3_XS, F16, BF16, TQ2_0 ...
_QUANT_RE = re.compile(
r"(?i)(?<![A-Z0-9])("
r"BF16|F16|F32|"
r"IQ\d+_[A-Z0-9]+(?:_[A-Z0-9]+)*|"
r"TQ\d+_\d+|"
r"Q\d+_K(?:_[SML])?|"
r"Q\d+_\d+_\d+_\d+|"
r"Q\d+_NL|"
r"Q\d+_[01]|"
r"MXFP4(?:_MOE)?"
r")(?![A-Z0-9])"
)
_PARAMS_LABEL_RE = re.compile(r"(?i)(\d+(?:[.,]\d+)?)\s*([KMGTB])B?\b")
_PARAMS_FILE_RE = re.compile(r"(?i)(\d+(?:\.\d+)?)\s*B(?![A-Z0-9])")
_SIZE_UNITS = {
"K": 1_000,
"M": 1_000_000,
"G": 1_000_000_000,
"T": 1_000_000_000_000,
"B": 1_000_000_000,
}
class _GGUFError(Exception):
"""Внутренняя ошибка разбора; наружу превращается в поле error."""
class _ReadLimit(_GGUFError):
"""Превышен лимит чтения метаданных."""
class _Cursor:
"""Потоковый курсор по файлу с раздельными лимитами чтения и seek."""
def __init__(self, fh, size: int):
self.fh = fh
self.size = size
self.pos = 0
self.read_bytes = 0
self.traversed = 0
def read(self, count: int) -> bytes:
if count < 0:
raise _GGUFError("Отрицательный размер чтения")
if self.pos + count > self.size:
raise _GGUFError("Файл обрывается внутри заголовка GGUF")
if self.read_bytes + count > MAX_METADATA_BYTES:
raise _ReadLimit("Метаданные GGUF превышают 32 МБ")
data = self.fh.read(count)
if len(data) != count:
raise _GGUFError("Не удалось дочитать заголовок GGUF")
self.pos += count
self.read_bytes += count
self.traversed += count
return data
def skip(self, count: int):
if count < 0:
raise _GGUFError("Отрицательный размер пропуска")
if self.pos + count > self.size:
raise _GGUFError("Файл обрывается внутри заголовка GGUF")
self.pos += count
self.traversed += count
if self.traversed > MAX_TRAVERSED_BYTES:
raise _ReadLimit("Блок метаданных GGUF слишком велик")
self.fh.seek(self.pos)
def _uint(cur: _Cursor, size: int) -> int:
fmt = "<I" if size == 4 else "<Q"
return struct.unpack(fmt, cur.read(size))[0]
def _read_string(cur: _Cursor, len_size: int, max_bytes: int = MAX_STRING_BYTES) -> str:
length = _uint(cur, len_size)
if length < 0:
raise _GGUFError("Отрицательная длина строки")
if length > max_bytes:
head = cur.read(max_bytes)
cur.skip(length - max_bytes)
return head.decode("utf-8", "replace") + "…"
raw = cur.read(length) if length else b""
return raw.decode("utf-8", "replace")
def _skip_string(cur: _Cursor, len_size: int):
length = _uint(cur, len_size)
if length < 0:
raise _GGUFError("Отрицательная длина строки")
cur.skip(length)
def _read_value(cur: _Cursor, vtype: int, len_size: int):
fmt = _FIXED_FORMATS.get(vtype)
if fmt is not None:
return struct.unpack(fmt, cur.read(_FIXED_SIZES[vtype]))[0]
if vtype == GGUF_VALUE_STRING:
return _read_string(cur, len_size)
if vtype == GGUF_VALUE_ARRAY:
raise _GGUFError("Массив не ожидался в скалярном поле")
raise _GGUFError(f"Неизвестный тип метаданных GGUF: {vtype}")
def _skip_value(cur: _Cursor, vtype: int, len_size: int, depth: int = 0):
fixed = _FIXED_SIZES.get(vtype)
if fixed is not None:
cur.skip(fixed)
return
if vtype == GGUF_VALUE_STRING:
_skip_string(cur, len_size)
return
if vtype == GGUF_VALUE_ARRAY:
if depth >= MAX_ARRAY_DEPTH:
raise _GGUFError("Слишком большая вложенность массивов GGUF")
elem_type = _uint(cur, 4)
count = _uint(cur, len_size)
if count > MAX_TENSOR_COUNT:
raise _GGUFError("Некорректная длина массива GGUF")
if count == 0:
return
elem_fixed = _FIXED_SIZES.get(elem_type)
if elem_fixed is not None:
# Одно seek вместо чтения миллионов элементов.
cur.skip(elem_fixed * count)
return
if elem_type == GGUF_VALUE_STRING:
for _ in range(count):
_skip_string(cur, len_size)
return
if elem_type == GGUF_VALUE_ARRAY:
for _ in range(count):
_skip_value(cur, elem_type, len_size, depth + 1)
return
raise _GGUFError(f"Неизвестный тип элемента массива GGUF: {elem_type}")
raise _GGUFError(f"Неизвестный тип метаданных GGUF: {vtype}")
def _as_int(value, default: int = 0) -> int:
"""Аккуратно привести число/строку к int."""
if isinstance(value, bool):
return int(value)
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
parsed = _parse_size_text(value)
if parsed is not None:
return parsed
try:
return int(float(value.strip()))
except Exception:
return default
return default
def _parse_size_text(text: str):
"""Разобрать "3.2B", "900M", "1,7 B" в число параметров."""
if not isinstance(text, str):
return None
match = _PARAMS_LABEL_RE.search(text)
if not match:
return None
try:
number = float(match.group(1).replace(",", "."))
except Exception:
return None
unit = match.group(2).upper()
# Без явного суффикса K/M/G/T считаем значение уже целым числом.
if unit not in _SIZE_UNITS:
return int(number)
return int(number * _SIZE_UNITS[unit])
def quant_from_filename(name: str) -> str:
"""Выделить название квантизации из имени файла.
Примеры: ``Llama-3.2-3B-Q8_0.gguf`` -> ``Q8_0``,
``Qwen3-1.7B-Q4_K_M.gguf`` -> ``Q4_K_M``, ``model-BF16.gguf`` -> ``BF16``.
Если распознать не удалось, возвращается пустая строка.
"""
if not name:
return ""
match = _QUANT_RE.search(os.path.basename(str(name)))
return match.group(1).upper() if match else ""
def format_params(value) -> str:
"""Человекочитаемое число параметров: 1.7B, 26.4B, 900M.
Для неизвестного/нулевого значения возвращается пустая строка.
"""
if value is None or value == "":
return ""
try:
number = float(value)
except (TypeError, ValueError):
# Если пришла готовая строка ("3.2B"), отдаём её как есть.
return str(value).strip()
if number <= 0:
return ""
for suffix, divisor in (("T", 1e12), ("B", 1e9), ("M", 1e6), ("K", 1e3)):
if number >= divisor:
scaled = number / divisor
text = f"{scaled:.1f}".rstrip("0").rstrip(".")
return f"{text}{suffix}"
return str(int(number))
def _params_from_filename(name: str) -> int:
match = _PARAMS_FILE_RE.search(os.path.basename(str(name or "")))
if not match:
return 0
try:
return int(float(match.group(1)) * 1_000_000_000)
except Exception:
return 0
def _first_int(values: dict, keys, default: int = 0) -> int:
for key in keys:
if key in values:
parsed = _as_int(values[key], default=0)
if parsed:
return parsed
return default
def _empty_result(path: str, size: int = 0, mtime: float = 0.0) -> dict:
return {
"path": path,
"file": os.path.basename(path) if path else "",
"size": int(size or 0),
"mtime": float(mtime or 0.0),
"architecture": "",
"name": "",
"quantization": "",
"parameters": 0,
"params_label": "",
"context_length": 0,
"embedding_length": 0,
"block_count": 0,
"tensor_count": 0,
"version": 0,
"error": "",
}
def read_gguf_metadata(path: str) -> dict:
"""Прочитать заголовок/метаданные GGUF, не загружая веса.
Возвращает словарь с полями ``path``, ``file``, ``size``, ``mtime``,
``architecture``, ``name``, ``quantization``, ``parameters``,
``params_label``, ``context_length``, ``embedding_length``,
``block_count``, ``tensor_count``, ``version`` и ``error``.
Любая проблема (нет файла, битый заголовок, лимит метаданных) попадает
в ``error``; исключения наружу не выбрасываются.
"""
try:
full_path = os.path.abspath(os.path.expanduser(str(path)))
except Exception:
full_path = str(path)
result = _empty_result(full_path)
try:
stat = os.stat(full_path)
size = int(getattr(stat, "st_size", 0) or 0)
mtime = float(getattr(stat, "st_mtime", 0.0) or 0.0)
except Exception as exc:
result["error"] = f"Файл недоступен: {exc}"
return result
result["size"] = size
result["mtime"] = mtime
filename = os.path.basename(full_path)
result["file"] = filename
values = {}
try:
if size < 8:
raise _GGUFError("Файл слишком мал для GGUF")
with open(full_path, "rb") as fh:
cursor = _Cursor(fh, size)
if cursor.read(4) != GGUF_MAGIC:
raise _GGUFError("Неверная сигнатура GGUF")
version = _uint(cursor, 4)
if version == 1:
count_size = 4
elif version in (2, 3):
count_size = 8
else:
raise _GGUFError(f"Неподдерживаемая версия GGUF: {version}")
tensor_count = _uint(cursor, count_size)
kv_count = _uint(cursor, count_size)
if tensor_count > MAX_TENSOR_COUNT:
raise _GGUFError("Некорректное число тензоров GGUF")
if kv_count > MAX_KV_COUNT:
raise _GGUFError("Некорректное число метаданных GGUF")
result["version"] = version
result["tensor_count"] = int(tensor_count)
for _ in range(kv_count):
key = _read_string(cursor, count_size, max_bytes=MAX_KEY_BYTES)
vtype = _uint(cursor, 4)
wanted = key in (
"general.name",
"general.architecture",
"general.parameter_count",
"general.size_label",
"general.file_type",
) or key.endswith(
(".context_length", ".block_count", ".embedding_length")
)
# Читаем только скалярные нужные поля; массивы (словари
# токенизатора) и прочее пропускаем, не загружая в память.
if wanted and (vtype in _FIXED_FORMATS or vtype == GGUF_VALUE_STRING):
values[key] = _read_value(cursor, vtype, count_size)
else:
_skip_value(cursor, vtype, count_size)
except Exception as exc:
result["error"] = str(exc) or exc.__class__.__name__
architecture = values.get("general.architecture")
architecture = str(architecture).strip() if architecture is not None else ""
result["architecture"] = architecture
suffix_keys = {
".context_length": [],
".block_count": [],
".embedding_length": [],
}
for key in values:
for suffix, bucket in suffix_keys.items():
if key.endswith(suffix):
bucket.append(key)
def pick(suffix: str) -> int:
keys = suffix_keys[suffix]
preferred = f"{architecture}{suffix}" if architecture else ""
if preferred and preferred in values:
return _as_int(values[preferred])
return _first_int(values, keys)
result["context_length"] = pick(".context_length")
result["block_count"] = pick(".block_count")
result["embedding_length"] = pick(".embedding_length")
name = values.get("general.name")
name = str(name).strip() if name is not None else ""
result["name"] = name or os.path.splitext(filename)[0]
parameters = _as_int(values.get("general.parameter_count"))
if parameters <= 0:
# size_label бывает как "3.2B", так и обычным числом.
parameters = _as_int(values.get("general.size_label"))
if parameters <= 0:
parameters = _params_from_filename(filename)
result["parameters"] = parameters
result["params_label"] = (
format_params(parameters)
if parameters > 0
else (
str(values.get("general.size_label")).strip()
if values.get("general.size_label")
else ""
)
)
file_type = _as_int(values.get("general.file_type"), default=-1)
quantization = GGUF_FILE_TYPES.get(file_type, "")
if not quantization:
quantization = quant_from_filename(filename)
result["quantization"] = quantization
return result