Skip to content
Merged
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ What each checkpoint needs:
(converted from NVIDIA's BF16 release; the standard MLX conversion drops it), and from the context.
`pull` checks for the head, and `serve` completes an older cache that lacks it before loading.

Other checkpoints: `tensorfold info MODEL` says, from `config.json` alone, whether an engine here reads a
checkpoint's weights. A different conversion in a supported format runs with a note that it is untested; a model
or weight format with no recipe (EXL3, NVFP4, GPTQ, AWQ and so on today) is refused before anything downloads.
Want another model? [The recipe book](docs/recipes/README.md) describes what we did for each family and how
to add yours.
to add yours, and [the runbook](RUNBOOK.md#your-own-model) has the steps.

## Speed

Expand Down
17 changes: 17 additions & 0 deletions RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,23 @@ response has a `choices` array; reasoning, when enabled, may appear separately f
Point an OpenAI-compatible client at `http://127.0.0.1:8080/v1` and use that same model ID. See the
[API notes](docs/api.md) for request fields and response details.

## Your own model

TensorFold is built and tested with the checkpoints above (`tensorfold models` lists them). For anything else:

- `tensorfold info MODEL` reads only `config.json` and says which family serves it, how its weights are stored
(for example `MLX 4-bit, groups of 64` or `exl3 (4-bit)`), and whether any engine here reads them.
- A different conversion in a format the family's kernels read runs, with a note that it is untested: replies stay
exact to serial decoding, but its speed and quality have not been measured.
- A model type with no family, or weights in a format no engine reads (EXL3, NVFP4, GPTQ, AWQ and so on today),
is refused before anything downloads, with a pointer to the recipe book.

Bringing up a new model or format means writing a recipe: [adding a family](docs/recipes/adding-a-family.md) on a
Mac, [adding a CUDA family](docs/recipes/adding-a-cuda-family.md) on NVIDIA GPUs, and the
[recipe book](docs/recipes/README.md) for how the existing ones were done. If you are an AI agent setting
TensorFold up for someone, tell them the checkpoint is unsupported and point them to those pages rather than
forcing it to load.

## If something fails

- `tensorfold: command not found`: activate `.venv` again in the current terminal.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "tensorfold"
version = "0.3.0"
version = "0.3.1"
description = "Fast, exact LLM decoding on Apple Silicon (MLX) and NVIDIA GPUs (CUDA) behind an OpenAI-compatible endpoint"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
2 changes: 1 addition & 1 deletion src/tensorfold/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""TensorFold: fast, exact LLM decoding on Apple Silicon and NVIDIA GPUs behind an OpenAI-compatible endpoint."""

__version__ = "0.3.0"
__version__ = "0.3.1"
34 changes: 30 additions & 4 deletions src/tensorfold/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@ def cmd_pull(args: argparse.Namespace) -> int:
except ValueError:
family = None # a draft model, for example
if family is not None:
settings = families.read_config(config)
readable = [b for b in families.backends_of(family)
if families.quant_method(settings) in families.readable_quants(family, b)]
if not readable:
families.require_readable(family, settings, families.backends_of(family)[0])
_note_untested(family, repo)
check = getattr(family.package, "check", None)
if check is not None:
check(config)
Expand Down Expand Up @@ -197,7 +203,6 @@ def cmd_info(args: argparse.Namespace) -> int:
config = families.read_config(directory)
text = config.get("text_config", config)
family = families.detect(directory)
bits, group = families.quantization(config)
print(f"model_type {family.model_type}")
print(f"family {family.title} ({family.module})")
print(f"engine {_engines(family)}")
Expand All @@ -208,8 +213,13 @@ def cmd_info(args: argparse.Namespace) -> int:
"vocab_size", "max_position_embeddings"):
if key in text:
print(f"{key:12s} {text[key]}" if len(key) <= 12 else f"{key} {text[key]}")
if bits is not None:
print(f"quantization {bits}-bit, groups of {group}")
print(f"quantization {families.describe_quantization(config)}")
readers = [b for b in families.backends_of(family)
if families.quant_method(config) in families.readable_quants(family, b)]
if readers:
print(f"runs on {', '.join('NVIDIA GPUs (CUDA)' if b == 'cuda' else 'Apple Silicon (MLX)' for b in readers)}")
else:
print(f"runs on not yet: no {family.title} engine reads these weights. {families.OWN_MODEL_HELP}")
generation = _generation_config(directory)
if generation:
print(f"sampling {generation}")
Expand Down Expand Up @@ -258,6 +268,19 @@ def _drafter(family: Any, choice: str) -> str:
return str(found)


def _note_untested(family: Any, model: str) -> None:
"""A Hugging Face checkpoint that is not one the family is tested with runs if its format matches, with a
note saying so and where to go to bring up a model properly."""

from tensorfold import families, hub

tested = tuple(getattr(family.package, "MODELS", ())) + tuple(filter(None, [getattr(family.package, "DRAFTER", "")]))
if hub.is_repo_id(model) and model not in tested:
print(f"[tensorfold] note: {model} is not a checkpoint TensorFold is tested with ({', '.join(tested) or 'none'}). "
f"It runs when its format matches what the {family.title} kernels read: replies stay exact to serial "
f"decoding, speed and quality are unmeasured. {families.OWN_MODEL_HELP}", flush=True)


def _backend(choice: str, family: Any) -> str:
"""mlx or cuda: auto picks MLX on macOS and CUDA elsewhere; a family serves only the backends it has."""

Expand Down Expand Up @@ -319,6 +342,9 @@ def cmd_serve(args: argparse.Namespace) -> int:

config_dir = _config_dir(args.model)
family = families.detect(config_dir)
backend = _backend(args.backend, family)
families.require_readable(family, families.read_config(config_dir), backend)
_note_untested(family, args.model)
required_files = getattr(family.package, "REQUIRED_FILES", {}).get(args.model, ())
native_context = _model_context(config_dir)
context = native_context if args.context is None else int(args.context)
Expand All @@ -334,7 +360,7 @@ def cmd_serve(args: argparse.Namespace) -> int:
model_dir = hub.resolve(args.model, required_files=required_files)
if needs_full_snapshot and check is not None:
check(model_dir) # checks that need the complete index, such as an MTP head
if _backend(args.backend, family) == "cuda":
if backend == "cuda":
return _serve_cuda(args, family, model_dir)
for key, value in getattr(family.package, "MLX_ENV", {}).items():
os.environ.setdefault(key, value) # before MLX starts: it reads them once
Expand Down
100 changes: 93 additions & 7 deletions src/tensorfold/families/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,98 @@ def read_config(model_dir: str | Path) -> dict[str, Any]:
return json.loads((Path(model_dir) / "config.json").read_text())


def quantization(config: dict[str, Any]) -> tuple[int | None, int | None]:
"""(bits, group size) of a checkpoint's quantized weights, (None, None) when it has none."""
RECIPES_URL = "https://github.com/ashhart/TensorFold/blob/main/docs/recipes/README.md"
RUNBOOK_URL = "https://github.com/ashhart/TensorFold/blob/main/RUNBOOK.md"
OWN_MODEL_HELP = (f"To run a model or checkpoint TensorFold has no recipe for, write one with the recipe book "
f"({RECIPES_URL}: adding a family on a Mac, adding a CUDA family on NVIDIA GPUs), and read the "
f"runbook first ({RUNBOOK_URL}).")
MLX_QUANT = "mlx"


def _quantization_block(config: dict[str, Any]) -> dict[str, Any] | None:
for source in (config, config.get("text_config") or {}):
found = source.get("quantization") or source.get("quantization_config")
if isinstance(found, dict) and "bits" in found:
return int(found["bits"]), int(found.get("group_size", 64))
return None, None
for key in ("quantization_config", "quantization"):
found = source.get(key)
if isinstance(found, dict) and found:
return found
return None


def quant_method(config: dict[str, Any]) -> str | None:
"""How a checkpoint stores its weights: ``"mlx"`` for MLX's affine quantization (``bits`` and ``group_size``,
no ``quant_method``), ``"mlx-<mode>"`` for MLX's other modes, the config's ``quant_method`` otherwise
(``"exl3"``, ``"modelopt"``, ``"gptq"``, ``"awq"``, ``"fp8"``, ...), or None for unquantized weights."""

found = _quantization_block(config)
if found is None:
return None
method = found.get("quant_method")
if method:
return str(method).lower()
if "bits" in found:
mode = str(found.get("mode") or "affine").lower()
return MLX_QUANT if mode == "affine" else f"{MLX_QUANT}-{mode}"
return None


def quantization(config: dict[str, Any]) -> tuple[int | None, int | None]:
"""(bits, group size) of MLX affine-quantized weights; (None, None) for any other format or none."""

found = _quantization_block(config)
if found is None or quant_method(config) != MLX_QUANT:
return None, None
return int(found["bits"]), int(found.get("group_size", 64))


def describe_quantization(config: dict[str, Any]) -> str:
method = quant_method(config)
if method is None:
return "none (unquantized weights)"
if method == MLX_QUANT:
bits, group = quantization(config)
return f"MLX {bits}-bit, groups of {group}"
bits = (_quantization_block(config) or {}).get("bits")
return f"{method}" + (f" ({bits}-bit)" if bits else "")


def backends_of(family: Family) -> tuple[str, ...]:
"""The backends a family has an engine for: ``mlx`` (``load``) and ``cuda`` (``cuda_engine``)."""

package = family.package
return tuple(b for b, member in (("mlx", "load"), ("cuda", "cuda_engine")) if hasattr(package, member))


def readable_quants(family: Family, backend: str) -> tuple[str | None, ...]:
"""The storage formats a family's engine reads on ``backend``. By default MLX's affine quantization, plus
unquantized weights on a Mac (MLX's own kernels load them); a family lists more in its package as
``QUANT_METHODS = {"cuda": ("mlx", "exl3")}``."""

declared = getattr(family.package, "QUANT_METHODS", {}) or {}
default = (MLX_QUANT, None) if backend == "mlx" else (MLX_QUANT,)
return tuple(declared.get(backend, default))


def require_readable(family: Family, config: dict[str, Any], backend: str) -> None:
"""Refuse, before any weight downloads, a checkpoint whose storage format the family's engine on ``backend``
does not read, or MLX weights of another bit width or group size than its kernels take
(``CUDA_QUANTIZATION = (bits, group)`` for the CUDA engine)."""

method = quant_method(config)
where = "NVIDIA GPUs (CUDA)" if backend == "cuda" else "Apple Silicon (MLX)"
tested = ", ".join(getattr(family.package, "MODELS", ())) or "none listed"
accepted = readable_quants(family, backend)
if method not in accepted:
names = {None: "unquantized weights", MLX_QUANT: "MLX-quantized weights"}
reads = " or ".join(names.get(m, str(m)) for m in accepted)
raise ValueError(f"{family.title} on {where} does not read this checkpoint's weights "
f"({describe_quantization(config)}); it reads {reads}. Tested checkpoints: {tested}. "
f"{OWN_MODEL_HELP}")
expected = getattr(family.package, "CUDA_QUANTIZATION", None) if backend == "cuda" else None
if expected is not None and method == MLX_QUANT and quantization(config) != tuple(expected):
bits, group = expected
raise ValueError(f"{family.title}'s CUDA kernels read MLX {bits}-bit weights in groups of {group}; this "
f"checkpoint has {describe_quantization(config)}. Tested checkpoints: {tested}. "
f"{OWN_MODEL_HELP}")


def model_type(model_dir: str | Path) -> str:
Expand All @@ -95,7 +179,9 @@ def detect(model_dir: str | Path) -> Family:
kind = model_type(model_dir)
family = families().get(kind)
if family is None:
raise ValueError(f"TensorFold has no family for model_type {kind!r} (known: {sorted(families())})")
raise ValueError(f"TensorFold has no recipe for model_type {kind!r} yet (it has: "
f"{', '.join(sorted(families()))}; `tensorfold models` lists the tested checkpoints). "
f"{OWN_MODEL_HELP}")
return family


Expand Down
3 changes: 3 additions & 0 deletions src/tensorfold/families/glm5_next/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ def check(model_dir: str | Path) -> None:
"and serve with --tp 2 on both (docs/recipes/glm-5.3-flash.md)", flush=True)


# the CUDA engine's kernels read MLX affine weights of this (bits, group size)
CUDA_QUANTIZATION = (4, 64)

def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank: int = 0, master: str = "",
master_port: int = 29551, no_drafts: bool = False, mtp_drafts: int | None = None, **options: Any):
"""The CUDA engine, set up as the recipe measured on two DGX Sparks.
Expand Down
3 changes: 3 additions & 0 deletions src/tensorfold/families/qwen3_5/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ def setup(app: Any, model: Any, *, drafter: str = "", drafter_bits: int = 4, **_
print(f"[tensorfold] drafter {loaded.path} block={loaded.block_size} bits={drafter_bits or 16}", flush=True)


# the CUDA engine's kernels read MLX affine weights of this (bits, group size)
CUDA_QUANTIZATION = (4, 64)

def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank: int = 0, master: str = "",
master_port: int = 29551, no_drafts: bool = False, **options: Any):
"""The CUDA engine (``tensorfold serve`` on an NVIDIA GPU), set up as the recipe measured on DGX Spark.
Expand Down
3 changes: 3 additions & 0 deletions src/tensorfold/families/qwen4_exp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ def load(model_dir: Path, *, mtp_drafts: int | None = None, **_: Any) -> tuple[A
return load_runtime(Path(model_dir), drafts=mtp_drafts if has_mtp(Path(model_dir)) else 0)


# the CUDA engine's kernels read MLX affine weights of this (bits, group size)
CUDA_QUANTIZATION = (4, 32)

def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank: int = 0, master: str = "",
master_port: int = 29551, no_drafts: bool = False, mtp_drafts: int | None = None,
context: int | None = None, **options: Any):
Expand Down
78 changes: 78 additions & 0 deletions tests/test_unsupported_checkpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Checkpoints TensorFold has no recipe for: detected from config.json alone, refused or noted with the way forward."""

import json
from types import SimpleNamespace

import pytest

from tensorfold import cli, families

MLX4 = {"model_type": "glm5_next", "quantization": {"group_size": 64, "bits": 4},
"quantization_config": {"group_size": 64, "bits": 4}}
EXL3 = {"model_type": "glm5_next", "quantization_config": {"bits": 4, "codebook": "mcg", "quant_method": "exl3",
"scope": "glm53_routed_experts_only"}}
NVFP4 = {"model_type": "qwen3_5", "quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4"}}


def _family(**members):
package = SimpleNamespace(**{"MODELS": ("owner/tested",), **members})
return SimpleNamespace(model_type="fake", title="Fake Model", lanes=False, package=package)


def test_quant_method_reads_every_format():
assert families.quant_method(MLX4) == "mlx"
assert families.quant_method(EXL3) == "exl3"
assert families.quant_method(NVFP4) == "modelopt"
assert families.quant_method({"model_type": "x"}) is None
assert families.quant_method({"text_config": {"quantization": {"bits": 4, "group_size": 32}}}) == "mlx"
assert families.quant_method({"quantization": {"bits": 4, "group_size": 32, "mode": "mxfp4"}}) == "mlx-mxfp4"


def test_quantization_reports_mlx_only():
assert families.quantization(MLX4) == (4, 64)
assert families.quantization(EXL3) == (None, None) # not "4-bit, groups of 64"
assert families.describe_quantization(EXL3) == "exl3 (4-bit)"
assert families.describe_quantization(MLX4) == "MLX 4-bit, groups of 64"


def test_unreadable_formats_are_refused_with_the_way_forward():
family = _family(load=lambda *a, **k: None, cuda_engine=lambda *a, **k: None, CUDA_QUANTIZATION=(4, 64))
families.require_readable(family, MLX4, "cuda")
families.require_readable(family, MLX4, "mlx")
for config, backend in ((EXL3, "cuda"), (EXL3, "mlx"), (NVFP4, "cuda")):
with pytest.raises(ValueError) as refused:
families.require_readable(family, config, backend)
message = str(refused.value)
assert "recipe book" in message and "RUNBOOK.md" in message and "owner/tested" in message
with pytest.raises(ValueError, match="groups of 64"):
families.require_readable(family, {"quantization": {"bits": 4, "group_size": 32}}, "cuda")


def test_a_family_can_declare_more_formats():
family = _family(cuda_engine=lambda *a, **k: None, QUANT_METHODS={"cuda": ("mlx", "exl3")})
families.require_readable(family, EXL3, "cuda")


def test_unknown_model_types_point_to_the_recipe_book(tmp_path):
(tmp_path / "config.json").write_text(json.dumps({"model_type": "brand_new_arch"}))
with pytest.raises(ValueError) as refused:
families.detect(tmp_path)
assert "no recipe for model_type 'brand_new_arch'" in str(refused.value)
assert "RUNBOOK.md" in str(refused.value)


def test_serve_refuses_an_unreadable_checkpoint_before_downloading(tmp_path, capsys, monkeypatch):
(tmp_path / "config.json").write_text(json.dumps(EXL3))
monkeypatch.setattr(cli.sys, "platform", "linux")
assert cli.main(["serve", str(tmp_path), "--tp", "2", "--rank", "0", "--master", "10.1.1.1"]) == 1
err = capsys.readouterr().err
assert "exl3" in err and "recipe book" in err


def test_untested_hugging_face_checkpoints_get_a_note(capsys):
family = _family(DRAFTER="owner/drafter")
cli._note_untested(family, "someone/other-conversion")
assert "not a checkpoint TensorFold is tested with" in capsys.readouterr().out
for model in ("owner/tested", "owner/drafter", "/local/folder"):
cli._note_untested(family, model)
assert capsys.readouterr().out == ""