Skip to content

Open-source State-of-the-art TTS model which runs on a CPU 😻

Python

Support small, older NVIDIA and Radeon GPUs in vLLM

haaziq-sl22770123b519
diff --git a/kittenml/get_model.py b/kittenml/get_model.py
index 15b6a10..de474ff 100644
--- a/kittenml/get_model.py
+++ b/kittenml/get_model.py
@@ -72,8 +72,10 @@ class KittenTTS(KittenTTSOnnx):
if model_type == KITTEN2_TYPE:
from .kittentts2 import KittenTTS2
if backend == "vllm":
- from .kittentts2.vllm.backend import check_options, validate_environment
- validate_environment(device, dict(vllm_options or {}).get("dtype"))
+ from .kittentts2.vllm.backend import (check_options, options_for_gpu,
+ validate_environment)
+ capability = validate_environment(device, dict(vllm_options or {}).get("dtype"))
+ vllm_options = options_for_gpu(vllm_options, capability)
# Before the download: an unsupported GPU or a misspelled option
# should not cost gigabytes.
check_options(vllm_options, weights or config.get("default_weights", "packed"))
diff --git a/kittenml/kittentts2/vllm/backend.py b/kittenml/kittentts2/vllm/backend.py
index 2a4d185..707d5e5 100644
--- a/kittenml/kittentts2/vllm/backend.py
+++ b/kittenml/kittentts2/vllm/backend.py
@@ -1,13 +1,19 @@
"""Optional GPU language-model backend; waveform decoding stays in KittenTTS."""
from dataclasses import asdict
+import atexit
import contextlib
import importlib.util
+import logging
+import math
import os
import sys
+import weakref
import torch
+logger = logging.getLogger(__name__)
+
@contextlib.contextmanager
def _engine_environment(forced=None):
@@ -40,40 +46,105 @@ def _engine_environment(forced=None):
def validate_environment(device=None, dtype=None):
"""Check the platform and GPU; `dtype` is vllm_options['dtype'] as given."""
if sys.platform != "linux":
- raise RuntimeError("the vLLM backend requires Linux and an NVIDIA CUDA GPU")
+ raise RuntimeError("the vLLM backend requires Linux and an NVIDIA CUDA GPU "
+ "(or an AMD GPU with ROCm)")
if importlib.util.find_spec("vllm") is None:
raise ImportError('install the optional backend with pip install "kittenml[vllm]"')
selected = torch.device(device or "cuda")
if selected.type != "cuda" or not torch.cuda.is_available():
- raise RuntimeError("the vLLM backend requires an NVIDIA CUDA GPU")
+ raise RuntimeError("the vLLM backend requires an NVIDIA CUDA GPU (or an AMD GPU with ROCm)")
if selected.index not in (None, 0):
raise ValueError("select the GPU with CUDA_VISIBLE_DEVICES and use device='cuda'")
+ from .rocm import check_amd_gpu, is_rocm
+ if is_rocm():
+ # AMD GPUs with a ROCm build of PyTorch and vLLM (rocm.py); the capability
+ # numbers below are NVIDIA's.
+ check_amd_gpu(dtype)
+ check_torchcodec()
+ return
major, minor = torch.cuda.get_device_capability()
- if (major, minor) < (7, 5):
+ if major < 7:
raise RuntimeError(f"this GPU (SM{major}{minor}) is not supported by the vLLM backend, "
- "which needs compute capability 7.5 or newer")
- if major < 8 and dtype != "float16":
- raise RuntimeError(f"this GPU (SM{major}{minor}) has no bfloat16 support, which "
- f"KittenTTS's language model runs in by default. {_FLOAT16_OPT_IN}")
+ "which needs compute capability 7.0 or newer; use the default "
+ "backend on CPU (omit backend='vllm' and set device='cpu')")
+ if major == 7 and dtype == "bfloat16":
+ raise ValueError(f"SM{major}{minor} has no native bfloat16; use dtype='float16' "
+ "or 'float32', or leave dtype unset")
+ if (major, minor) < (7, 5):
+ # CUDA 12.9/13 PyTorch wheels omit Volta. Check before downloading weights;
+ # a compatible CUDA 12.6 build is needed by both PyTorch and vLLM.
+ arches = torch.cuda.get_arch_list()
+ ptx = [int(a.removeprefix("compute_")) for a in arches
+ if a.startswith("compute_") and a.removeprefix("compute_").isdigit()]
+ if f"sm_{major}{minor}" not in arches and not any(a <= major * 10 + minor for a in ptx):
+ raise RuntimeError(
+ f"this PyTorch build does not support SM{major}{minor}; V100 needs PyTorch "
+ "and vLLM built with CUDA 12.6 and SM70 support. See docs/vllm.md. "
+ "The standard CUDA 12.9/13 wheels cannot run on V100")
+ check_torchcodec()
+ return major, minor
+
+
+def options_for_gpu(options, capability):
+ """Choose the measured CC 7.x path; preserve every explicit option and modern GPU path."""
+ if not isinstance(capability, tuple) or capability[0] != 7:
+ return options
+ chosen = dict(options or {})
+ if chosen.get("dtype") is None:
+ chosen["dtype"] = "float16"
+ if capability < (7, 5) and chosen.get("quantization") == "w4a16":
+ raise ValueError("W4A16 requires compute capability 7.5 or newer; on V100 use "
+ "quantization=None")
+ if capability >= (7, 5) and chosen["dtype"] == "float16" and "quantization" not in chosen:
+ try:
+ check_w4a16_environment()
+ except RuntimeError:
+ pass # Preserve the caller's kernel overrides; dense float16 remains available.
+ else:
+ # All three modes tied on WER/drops; this was the fastest and fit 6 GB.
+ chosen["quantization"] = "w4a16"
+ return chosen
+
+
+def check_torchcodec():
+ """Refuse an installed torchcodec that would stop vLLM at start-up.
+
+ vLLM imports torchcodec's audio decoder when it starts and carries on if that
+ fails with ImportError or RuntimeError (no FFmpeg). A torchcodec built for a
+ different CUDA version than PyTorch fails with OSError instead once FFmpeg is
+ installed (PyPI's torchcodec 0.17.0 is a CUDA 13 build, so this happens with the
+ CUDA 12.9 builds of vLLM and PyTorch), and every engine start fails on it.
+ KittenTTS does not use torchcodec.
+ """
+ if importlib.util.find_spec("torchcodec") is None:
+ return
+ try:
+ from torchcodec.decoders import AudioDecoder # noqa: F401
+ except (ImportError, RuntimeError):
+ return
+ except OSError as error:
+ reason = (str(error).strip().splitlines() or [type(error).__name__])[0][:300]
+ raise RuntimeError(
+ f"torchcodec is installed but cannot load ({reason}). It is probably built for "
+ "a different CUDA version than PyTorch, and vLLM stops on this when it starts. "
+ "KittenTTS does not use torchcodec: remove it with `pip uninstall torchcodec` "
+ "(or `uv pip uninstall torchcodec`)") from error
# Engine settings KittenTTS chooses for vLLM, and their defaults.
_ENGINE_DEFAULTS = dict(gpu_memory_utilization=0.5, max_model_len=4096,
max_num_seqs=8, enforce_eager=False)
-# Options KittenTTS interprets itself. None keeps the default behaviour.
-_KITTEN_OPTIONS = ("quantization", "dtype", "kv_cache_memory_bytes")
+# Options KittenTTS interprets itself. None keeps the default behaviour
+# (for max_num_batched_tokens: vLLM's own default).
+_KITTEN_OPTIONS = ("quantization", "dtype", "kv_cache_memory_bytes", "max_num_batched_tokens")
_QUANTIZATIONS = (None, "w4a16")
-_DTYPES = {None: None, "bfloat16": torch.bfloat16, "float16": torch.float16}
+_DTYPES = {None: None, "bfloat16": torch.bfloat16, "float16": torch.float16,
+ "float32": torch.float32}
# W4A16 runs on vLLM's Marlin kernel, the one whose exact output was verified.
# vLLM tries Machete first on Hopper (SM90) GPUs, so it is disabled for the
# engine; the loader then checks that every quantized layer uses Marlin.
_W4A16_KERNEL = "MarlinLinearKernel"
_W4A16_DISABLED_KERNELS = ("MacheteLinearKernel",)
-# GPUs without bfloat16 (compute capability 7.5) can opt in to float16, a
-# rescaled fallback with a precision change (fp16.py).
-_FLOAT16_OPT_IN = ("To run on it anyway, opt in to the float16 fallback with "
- "vllm_options={'dtype': 'float16'}: it is supported but not the optimal "
- "path (a precision change from bfloat16; see the vLLM backend docs)")
def resolve_options(options):
@@ -87,16 +158,18 @@ def resolve_options(options):
raise ValueError(f"vllm_options['quantization'] must be None or 'w4a16', "
f"not {kitten['quantization']!r}")
if kitten["dtype"] not in _DTYPES:
- raise ValueError(f"vllm_options['dtype'] must be None, 'bfloat16' or 'float16', "
+ raise ValueError(f"vllm_options['dtype'] must be None, 'bfloat16', 'float16' or 'float32', "
f"not {kitten['dtype']!r}")
- memory = kitten["kv_cache_memory_bytes"]
- if memory is not None and (isinstance(memory, bool) or not isinstance(memory, int)
- or memory <= 0):
- raise ValueError("vllm_options['kv_cache_memory_bytes'] must be a positive integer")
+ for key in ("kv_cache_memory_bytes", "max_num_batched_tokens"):
+ value = kitten[key]
+ if value is not None and (isinstance(value, bool) or not isinstance(value, int)
+ or value <= 0):
+ raise ValueError(f"vllm_options['{key}'] must be a positive integer")
engine = dict(_ENGINE_DEFAULTS)
engine.update(options)
- if memory is not None:
- engine["kv_cache_memory_bytes"] = memory
+ for key in ("kv_cache_memory_bytes", "max_num_batched_tokens"):
+ if kitten[key] is not None:
+ engine[key] = kitten[key]
return engine, kitten
@@ -104,6 +177,8 @@ def check_options(options, weights):
"""Validate `vllm_options` before anything is downloaded or loaded."""
defaults, kitten = resolve_options(options)
if kitten["quantization"] == "w4a16":
+ if kitten["dtype"] == "float32":
+ raise ValueError("W4A16 needs bfloat16 or float16 activations, not float32")
check_w4a16_environment()
if weights == "emb4" and kitten["dtype"] == "float16":
# The float16 rescale was measured on the exact embedding (fp16.py).
@@ -123,19 +198,32 @@ def check_w4a16_environment(environ=None):
raise RuntimeError(refuse + "VLLM_MARLIN_USE_ATOMIC_ADD=1: it would let Marlin reduce "
"with unordered atomic adds. Unset it to run exact W4A16")
disabled = environ.get("VLLM_DISABLED_KERNELS", "").split(",")
- if _W4A16_KERNEL in disabled:
- raise RuntimeError(refuse + f"VLLM_DISABLED_KERNELS names {_W4A16_KERNEL}, the only "
+ kernel = _w4a16_kernel()
+ if kernel in disabled:
+ raise RuntimeError(refuse + f"VLLM_DISABLED_KERNELS names {kernel}, the only "
"kernel exact W4A16 is verified with. Remove it from the list")
def w4a16_engine_environment(environ=None):
- """VLLM_DISABLED_KERNELS for the engine: the caller's list plus Machete."""
+ """VLLM_DISABLED_KERNELS for the engine: the caller's list plus Machete
+ (on AMD GPUs: plus the RDNA3 kernel, rocm.py)."""
environ = os.environ if environ is None else environ
disabled = [k for k in environ.get("VLLM_DISABLED_KERNELS", "").split(",") if k]
- disabled += [k for k in _W4A16_DISABLED_KERNELS if k not in disabled]
+ disabled += [k for k in _w4a16_disabled_kernels() if k not in disabled]
return {"VLLM_DISABLED_KERNELS": ",".join(disabled)}
+def _w4a16_kernel():
+ """The kernel exact W4A16 is verified with on this platform."""
+ from . import rocm
+ return rocm.W4A16_KERNEL if rocm.is_rocm() else _W4A16_KERNEL
+
+
+def _w4a16_disabled_kernels():
+ from . import rocm
+ return rocm.W4A16_DISABLED_KERNELS if rocm.is_rocm() else _W4A16_DISABLED_KERNELS
+
+
def _main_process_tensor(name):
"""Only these LM tensors are used outside vLLM: prompt embeddings and spk_proj."""
return name == "model.embed_tokens.weight" or name.startswith("spk_proj.")
@@ -159,28 +247,235 @@ def engine_args(quantization, float16):
return args
+# ── Fitting vLLM to the GPU ──────────────────────────────────────────────────
+# With the defaults vLLM takes half the GPU, and this process needs memory next to
+# it for audio decoding. On cards with 8 GB or less that does not fit, so there the
+# settings the caller did not give are chosen from the free memory instead. Larger
+# GPUs keep their defaults unless the CC 7.x path requests fitting; callers who
+# set the memory share themselves keep it, with a warning when it is too small. The byte
+# counts below were measured with vLLM 0.31.0 for KittenTTS 2 on RTX 4060 desktop
+# and laptop GPUs (8 GB).
+MiB = 1 << 20
+# Cards with 8 GB or less (CUDA reports 7.6-7.8 GiB for 8 GB cards, 9.6 GiB or
+# more for 10 GB ones). CC 7.x can also request fitting on larger cards.
+_SMALL_GPU_TOTAL_BYTES = 9 << 30
+# This process beside vLLM: the audio decoder (s3gen, 1,030 MiB in float32) and its
+# working memory for the longest chunk, 1,000 tokens (2,824 MiB reserved at the
+# peak with the default decoder; it grows faster than the chunk's length).
+_MAIN_PROCESS_BYTES = 2816 * MiB
+# vLLM's engine process: its CUDA context (about 125 MiB), taken before vLLM sizes
+# its share.
+_ENGINE_CONTEXT_BYTES = 256 * MiB
+# Inside vLLM's share, besides weights and KV cache: memory outside PyTorch and
+# CUDA graphs, plus the activation peak, which grows with max_num_batched_tokens
+# (measured 0.15 GiB at 2,048 and 0.41 GiB at vLLM's default of 8,192).
+_ENGINE_FIXED_BYTES = 256 * MiB
+_ACTIVATION_BYTES_PER_TOKEN = 56 * 1024
+# vLLM's default max_num_batched_tokens for the LLM class on GPUs under 70 GB.
+_VLLM_BATCHED_TOKENS = 8192
+# On the smallest GPUs: prefill in steps of this many tokens (a typical prompt
+# still fits in one), which lowers the activation peak by 0.26 GiB.
+_SMALL_GPU_BATCHED_TOKENS = 2048
+# KV cache on small GPUs: room for this many full-length requests if it fits, and
+# at least one (vLLM refuses a cache smaller than max_model_len) plus two blocks.
+_KV_TARGET_REQUESTS = 4
+_KV_MARGIN_TOKENS = 32
+# The shortest context a small GPU may fall back to: a long reference prompt plus
+# a full chunk still fits.
+_MIN_MODEL_LEN = 2048
+
+
+def lm_memory(lm_config, quantization=None, float16=False, float32=False):
+ """(weight bytes on the GPU, KV-cache bytes per token) for a Qwen3 language model."""
+ from ..ternary import GROUP_SIZE
+
+ element_bytes = 4 if float32 else 2
+ if float32 and quantization == "w4a16":
+ raise ValueError("W4A16 needs bfloat16 or float16 activations, not float32")
+ hidden, layers = lm_config.hidden_size, lm_config.num_hidden_layers
+ heads, kv_heads = lm_config.num_attention_heads, lm_config.num_key_value_heads
+ head_dim = getattr(lm_config, "head_dim", None) or hidden // heads
+ projections = layers * (2 * hidden * heads * head_dim + 2 * hidden * kv_heads * head_dim
+ + 3 * hidden * lm_config.intermediate_size)
+ embedding = lm_config.vocab_size * hidden
+ if quantization == "w4a16": # 4-bit codes plus one bf16 scale per group
+ projection_bytes = projections // 2 + projections // GROUP_SIZE * 2
+ else:
+ projection_bytes = projections * element_bytes
+ weight_bytes = element_bytes * embedding + projection_bytes
+ if float16 or not getattr(lm_config, "tie_word_embeddings", True):
+ weight_bytes += element_bytes * embedding # a separate output head
+ return weight_bytes, 2 * layers * kv_heads * head_dim * element_bytes
+
+
+def _engine_bytes(weights, batched_tokens, float32=False):
+ """Everything in vLLM's share except the KV cache."""
+ # Float32 also doubles the activation storage (0.25 GiB measured at 2,048
+ # tokens on RTX 2060, including vLLM's profiling overhead).
+ activation_bytes = _ACTIVATION_BYTES_PER_TOKEN * (2 if float32 else 1)
+ return weights + _ENGINE_FIXED_BYTES + activation_bytes * batched_tokens
+
+
+def fit_to_gpu(options, free_bytes, total_bytes, lm_config, float16=False, w4a16=True,
+ force=False):
+ """`vllm_options` with what the caller left out chosen for this GPU's free memory.
+
+ Returns (options, report). The options come back unchanged (report["fitted"]
+ False) when they fit: vLLM's share leaves this process room for audio decoding
+ and holds a KV cache for one full request. They also come back unchanged on
+ GPUs with more than 8 GB (unless `force=True`), and when the caller set the memory share
+ (`gpu_memory_utilization` or `kv_cache_memory_bytes`); if they do not fit there,
+ report["suggested"] holds settings that would. Otherwise, on a card with 8 GB or
+ less or with `force=True`, the options the caller did not give (even None counts as given) are
+ chosen: 4-bit weights (`w4a16`, when allowed) and a share sized for the
+ weights plus a KV cache of up to four full requests; then prefill in 2,048-token
+ steps and a shorter `max_model_len` (not below 2,048), only if one full request
+ would not fit without them. Raises RuntimeError when not even that fits,
+ saying how much free memory is needed.
+ """
+ given = dict(options or {})
+ engine, kitten = resolve_options(given)
+ room = free_bytes - _ENGINE_CONTEXT_BYTES - _MAIN_PROCESS_BYTES
+ report = {"free_mib": free_bytes // MiB, "total_mib": total_bytes // MiB,
+ "room_for_vllm_mib": max(room, 0) // MiB, "fitted": False}
+ float32 = kitten["dtype"] == "float32"
+ w4a16 = w4a16 and not float32
+ weights, kv_token = lm_memory(lm_config, kitten["quantization"], float16, float32)
+ fixed = _engine_bytes(weights, engine.get("max_num_batched_tokens", _VLLM_BATCHED_TOKENS),
+ float32)
+ share = int(engine["gpu_memory_utilization"] * total_bytes)
+ kv = kitten["kv_cache_memory_bytes"] or share - fixed
+ used = share if kitten["kv_cache_memory_bytes"] is None else kv + fixed
+ one_request = (engine["max_model_len"] + _KV_MARGIN_TOKENS) * kv_token
+ if used <= room and kv >= one_request:
+ return given, report
+ report["decoding_room_mib"] = max(free_bytes - _ENGINE_CONTEXT_BYTES - used, 0) // MiB
+ report["cache_short"] = kv < one_request
+ own_share = "gpu_memory_utilization" in given or kitten["kv_cache_memory_bytes"] is not None
+ if (total_bytes > _SMALL_GPU_TOTAL_BYTES and not force) or own_share:
+ # Not fitted: a larger GPU keeps vLLM's defaults, and a share the caller set
+ # stays theirs. Only suggest what would fit.
+ mine = {k: v for k, v in given.items()
+ if k not in ("gpu_memory_utilization", "kv_cache_memory_bytes")}
+ try:
+ report["suggested"] = _choose(mine, free_bytes, total_bytes, lm_config, float16,
+ w4a16, {})[0]
+ except RuntimeError:
+ report["suggested"] = None
+ return given, report
+ fitted, chosen_report = _choose(given, free_bytes, total_bytes, lm_config, float16, w4a16,
+ report)
+ report.update(chosen_report, fitted=True,
+ chosen={k: v for k, v in fitted.items() if k not in given})
+ return fitted, report
+
+
+def _choose(given, free_bytes, total_bytes, lm_config, float16, w4a16, report):
+ """The small-GPU choices for the options not in `given` (see fit_to_gpu)."""
+ fitted, report = dict(given), dict(report)
+ room = free_bytes - _ENGINE_CONTEXT_BYTES - _MAIN_PROCESS_BYTES
+ if "quantization" not in given and w4a16:
+ fitted["quantization"] = "w4a16"
+ engine, kitten = resolve_options(fitted)
+ float32 = kitten["dtype"] == "float32"
+ weights, kv_token = lm_memory(lm_config, kitten["quantization"], float16,
+ float32)
+ one_request = (engine["max_model_len"] + _KV_MARGIN_TOKENS) * kv_token
+ # vLLM sizes its share as ceil(total * utilization), so a utilization rounded
+ # down to 1e-6 loses at most total / 10^6 bytes of the planned cache.
+ step = total_bytes / 1e6
+ if "max_num_batched_tokens" not in given and \
+ room - _engine_bytes(weights, _VLLM_BATCHED_TOKENS, float32) - step < one_request:
+ # vLLM's default step is kept when a full request fits with it: the step size
+ # selects which compiled kernels run, so keeping it gives the same output as
+ # quantization="w4a16" with the defaults (same speed either way, measured).
+ fitted["max_num_batched_tokens"] = _SMALL_GPU_BATCHED_TOKENS
+ engine, kitten = resolve_options(fitted)
+ fixed = _engine_bytes(weights, engine.get("max_num_batched_tokens", _VLLM_BATCHED_TOKENS),
+ float32)
+ available = room - fixed
+ max_len = engine["max_model_len"]
+ if "max_model_len" not in given:
+ while (max_len > _MIN_MODEL_LEN
+ and (max_len + _KV_MARGIN_TOKENS) * kv_token > available - step):
+ max_len = max(_MIN_MODEL_LEN, max_len - 512)
+ if max_len != engine["max_model_len"]:
+ fitted["max_model_len"] = max_len
+ one_request = (max_len + _KV_MARGIN_TOKENS) * kv_token
+ if available - step < one_request:
+ needed = free_bytes - available + one_request + step
+ raise RuntimeError(
+ f"not enough free GPU memory for the vLLM backend: about {needed // MiB:,.0f} MiB "
+ f"free is needed and {free_bytes // MiB:,} MiB is free. Close other programs "
+ "using the GPU, use a GPU with more memory, or run the default backend on CPU "
+ "(omit backend='vllm' and set device='cpu')")
+ kv = min(available, _KV_TARGET_REQUESTS * (max_len + _KV_MARGIN_TOKENS) * kv_token)
+ # Rounded down so vLLM's share never exceeds what was measured as free.
+ fitted["gpu_memory_utilization"] = math.floor((fixed + kv) / total_bytes * 1e6) / 1e6
+ report["planned_kv_cache_tokens"] = int(kv // kv_token)
+ report["full_requests"] = int(kv // one_request)
+ return fitted, report
+
+
+def _stop_engine(backend_ref):
+ """Stop a VLLMBackend's engine process at interpreter exit (see VLLMBackend)."""
+ engine = getattr(backend_ref(), "engine", None)
+ if engine is None:
+ return
+ try:
+ engine.llm_engine.engine_core.shutdown()
+ except Exception: # noqa: BLE001 - nothing to report at exit
+ pass
+
+
+def _free_gpu_memory():
+ """(free, total) bytes on the current GPU, as this process sees them."""
+ return torch.cuda.mem_get_info()
+
+
class VLLMBackend:
def __init__(self, owner, options=None):
- validate_environment(owner.device, dict(options or {}).get("dtype"))
+ options = dict(options or {})
+ capability = validate_environment(owner.device, options.get("dtype"))
+ options = options_for_gpu(options, capability)
from transformers import AutoConfig, AutoTokenizer
from ..speaker import load_speaker_head
+ check_options(options, owner.weights)
+ lm_dir = owner.repo_dir / owner.config.get("lm_dir", "lm")
+ config = AutoConfig.from_pretrained(str(lm_dir))
+ if config.model_type != "qwen3":
+ raise ValueError("the vLLM backend currently supports Qwen3 KittenTTS 2 checkpoints")
+ # Explicit dtypes have known weight/cache sizes; preserve the existing
+ # behavior for custom model configurations without an explicit dtype.
+ half = owner.config.get("dtype", "bf16") == "bf16" or options.get("dtype") is not None
+ legacy = isinstance(capability, tuple) and capability[0] == 7
+ if legacy:
+ options, self.auto_fit = self._fit(options, config, half,
+ legacy_capability=capability)
+ else:
+ options, self.auto_fit = self._fit(options, config, half)
defaults, kitten = check_options(options, owner.weights)
quantization = kitten["quantization"]
forced_environment = w4a16_engine_environment() if quantization == "w4a16" else None
default_dtype = (torch.bfloat16 if owner.config.get("dtype", "bf16") == "bf16"
else torch.float32)
dtype = _DTYPES[kitten["dtype"]] or default_dtype
- # Only an explicit opt-in runs the rescaled float16 model (fp16.py).
+ # CC 7.x defaults to the rescaled model; modern GPUs keep their original dtype.
float16 = dtype is torch.float16
if quantization == "w4a16" and dtype not in (torch.bfloat16, torch.float16):
raise ValueError(f"W4A16 needs bfloat16 or float16 activations, not {dtype}")
+ if legacy:
+ mode = "rounded float16" if float16 else "float32"
+ if quantization == "w4a16":
+ mode += " with 4-bit weights"
+ # Preflight runs twice; warn only here, once the actual mode is known.
+ logger.warning(
+ "KittenTTS: SM%s%s has no native bfloat16; using %s. This is supported, "
+ "not optimal: audio can differ from RTX 30 and newer. See docs/vllm.md "
+ "for measured quality, speed and memory", *capability, mode)
self.max_model_len = defaults["max_model_len"]
self.token_map = owner.token_map
- lm_dir = owner.repo_dir / owner.config.get("lm_dir", "lm")
- config = AutoConfig.from_pretrained(str(lm_dir))
- if config.model_type != "qwen3":
- raise ValueError("the vLLM backend currently supports Qwen3 KittenTTS 2 checkpoints")
owner.dtype = dtype
owner.tokenizer = AutoTokenizer.from_pretrained(str(lm_dir))
# vLLM's own loader reads the full LM; this process only needs the
@@ -225,6 +520,61 @@ class VLLMBackend:
logits_processors=["kittenml.kittentts2.vllm.logits:KittenLogitsProcessor"],
logging_config=LoggingConfig(), disable_log_stats=True,
**engine_args(quantization, float16), **defaults)
+ # vLLM stops its engine process from a weakref finalizer at exit. If Python's
+ # multiprocessing exit handler runs first, it waits for that process, which is
+ # still waiting for work, so a finished script never returns. Exit handlers run
+ # last-registered first, so this one stops the engine before either of them.
+ atexit.register(_stop_engine, weakref.ref(self))
+
+ @staticmethod
+ def _fit(options, lm_config, half=True, legacy_capability=None):
+ """fit_to_gpu with this GPU's free memory, and its warnings.
+
+ The caller's options are returned unchanged if the free memory cannot be
+ read or a custom model's dtype is unknown. Explicit float32 also sizes its
+ weights, cache and activations at four bytes per element.
+ """
+ if not half:
+ return options, {"fitted": False, "skipped": "not a 16-bit model"}
+ try:
+ free, total = _free_gpu_memory()
+ except Exception as error: # noqa: BLE001 - fitting is an aid, not a requirement
+ return options, {"fitted": False, "error": repr(error)[:200]}
+ float16 = options.get("dtype") == "float16"
+ # 4-bit is chosen automatically only where its kernel was verified (Marlin on NVIDIA,
+ # vLLM's RDNA kernel on Radeon RX 7000 and RX 9000, rocm.py), and only when the
+ # environment would not refuse it.
+ from . import rocm
+ w4a16 = not rocm.is_rocm() or rocm.has_w4a16_kernel()
+ if legacy_capability is not None and legacy_capability < (7, 5):
+ w4a16 = False
+ try:
+ check_w4a16_environment()
+ except RuntimeError:
+ w4a16 = False
+ fitted, report = fit_to_gpu(options, free, total, lm_config, float16=float16,
+ w4a16=w4a16, force=legacy_capability is not None)
+ if report["fitted"]:
+ requests = report["full_requests"]
+ limits = [f"the cache holds about {report['planned_kv_cache_tokens']:,} tokens "
+ f"({requests} full-length request{'s' if requests != 1 else ''} at a time)"]
+ if "max_model_len" in report["chosen"]:
+ limits.append(f"the context is {report['chosen']['max_model_len']:,} tokens, "
+ "so longer requests raise an error")
+ logger.warning(
+ "KittenTTS: %s MiB of GPU memory free; vLLM's defaults do not fit next to audio "
+ "decoding, so using %s (set these in vllm_options to choose them yourself). This "
+ "is supported, but not the optimal path: %s", f"{free // MiB:,}",
+ ", ".join(f"{k}={v!r}" for k, v in report["chosen"].items()), "; ".join(limits))
+ elif "suggested" in report:
+ reason = ("the cache cannot hold one full-length request" if report["cache_short"]
+ else f"about {report['decoding_room_mib']:,} MiB of GPU memory is left for "
+ f"audio decoding, which needs up to {_MAIN_PROCESS_BYTES // MiB:,} MiB")
+ hint = (f" Settings that fit the free memory now: vllm_options={report['suggested']!r}"
+ if report["suggested"] else "")
+ logger.warning("KittenTTS: with these vLLM settings %s; nothing was changed.%s",
+ reason, hint)
+ return fitted, report
def prepare_request(self, prompt, speaker_embedding, settings, max_new_tokens, advanced):
from vllm import SamplingParams
diff --git a/kittenml/kittentts2/vllm/fp16.py b/kittenml/kittentts2/vllm/fp16.py
index 95afb87..8f7a1ba 100644
--- a/kittenml/kittentts2/vllm/fp16.py
+++ b/kittenml/kittentts2/vllm/fp16.py
@@ -1,6 +1,11 @@
-"""Opt-in float16 mode for GPUs without bfloat16 (compute capability 7.5).
+"""Rescaled float16 mode for GPUs without bfloat16.
-``vllm_options={"dtype": "float16"}`` is a fallback with a precision change:
+Finite weights that are not exactly representable are rounded once. Loading
+reports the number rounded and the largest absolute error, separately for the
+embedding, projections (or their 4-bit group scales), and other weights.
+Nonfinite values and float16 overflow remain errors.
+
+``vllm_options={"dtype": "float16"}`` brings a precision change:
the language model was trained and is published in bfloat16, whose range
float16 (largest value 65,504) does not have. Measured in bfloat16 over a
multilingual, long-form and cloning corpus, the residual stream (the running
@@ -8,7 +13,7 @@ sum every layer adds to) reaches 69,376 after layer 9 and 3,957,760 at the
final norm, and the MLP's inner activation (the ``down_proj`` input) reaches
154,624. Run as is in float16 these overflow and the model emits no speech.
-The fix rescales the model exactly instead of changing what it computes:
+Before rounding, the rescaling preserves the model's real-valued equations:
- Every read of the residual stream goes through an RMSNorm, and
``RMSNorm(c * x)`` with epsilon ``c**2 * eps`` equals ``RMSNorm(x)`` with
@@ -22,9 +27,9 @@ The fix rescales the model exactly instead of changing what it computes:
inside the branch is scaled too: ``v_proj`` x ``2**-3`` and ``o_proj`` x
``2**-6`` (attention is linear in V), ``up_proj`` x ``2**-5`` and
``down_proj`` x ``2**-4`` (silu(gate) * up is linear in up). Multiplying by
- a power of two only changes the exponent, and every scaled weight of the
- published checkpoint is still exactly representable in float16 (checked at
- load time; the loader refuses otherwise).
+ a power of two only changes the exponent, but small scaled values can enter
+ float16's subnormal range and lose precision. The loader permits and measures
+ this rounding instead of rejecting the whole checkpoint.
- The output head shares the embedding matrix in the checkpoint. It is
untied here and keeps the unscaled values, so the logits are not scaled
either (the final norm already removes the stream's scale).
@@ -32,9 +37,9 @@ The fix rescales the model exactly instead of changing what it computes:
What does change is float16 rounding: activations and weights are stored
with float16's precision instead of bfloat16's, and the scaled embedding
(``2**-9`` of values around 0.03) partly falls into float16's subnormal
-range, where 1.35% of its elements are rounded (worst error 4.6e-4 of a
-token's RMS, a quarter of bfloat16's own rounding step). The untied head
-costs one extra copy of the embedding (158,241 x 2,048, 618 MiB).
+range. The loader reports this rounding separately from the projections and
+the unscaled output head. The untied head costs one extra copy of the embedding
+(158,241 x 2,048, 618 MiB).
The scales were chosen from those measurements: ``2**-9`` leaves 8.5x
headroom below 65,504 at the largest value seen, and the MLP's inner
@@ -44,6 +49,7 @@ checkpoint; another checkpoint needs new measurements.
This module does not import vLLM, so it can be tested on any machine.
"""
+import logging
import re
import torch
@@ -69,7 +75,7 @@ _RESIDUAL_NORM = re.compile(
_SCALED = re.compile(r"^model\.layers\.\d+\.(self_attn\.(?:v|o)_proj|mlp\.(?:up|down)_proj)"
r"\.(weight|weight_scale)$")
# Every projection weight (dense) or W4A16 group scale: converted to float16
-# here, so a lossy conversion is refused rather than left to vLLM's copy.
+# here, so rounding and overflow are measured before vLLM's copy.
_PROJECTION = re.compile(r"^model\.layers\.\d+\.(?:self_attn\.(?:q|k|v|o)_proj|"
r"mlp\.(?:gate|up|down)_proj)\.(?:weight|weight_scale)$")
@@ -120,12 +126,20 @@ def is_exact(tensor, shift):
return _scaled_and_exact(tensor, shift)[1]
-def exact(name, tensor, shift):
- """`scaled`, refusing a weight float16 cannot hold exactly at this scale."""
- result, ok = _scaled_and_exact(tensor, shift)
- if not ok:
- raise ValueError(f"{name} x 2^-{shift} is not exact in float16; the float16 rescale "
- "was measured for the published checkpoint and does not fit this one")
+def rounded(name, tensor, shift, report, group):
+ """Round once, rejecting nonfinite values and accumulating conversion errors."""
+ target = tensor.to(torch.float32) * 2.0 ** -shift
+ result = target.to(torch.float16)
+ if not torch.isfinite(result).all():
+ raise ValueError(f"{name} x 2^-{shift} has nonfinite values or overflows float16")
+ error = (result.to(torch.float32) - target).abs()
+ stats = report.setdefault(group, dict(elements=0, rounded=0, max_absolute_error=0.0,
+ worst_tensor=None))
+ stats["elements"] += tensor.numel()
+ stats["rounded"] += int(torch.count_nonzero(error))
+ worst = float(error.max()) if error.numel() else 0.0
+ if worst > stats["max_absolute_error"]:
+ stats.update(max_absolute_error=worst, worst_tensor=name)
return result
@@ -134,27 +148,34 @@ def scale_embedding(weight):
return scaled(weight, RESIDUAL_SHIFT)
-def rescale_weights(weights):
+def rescale_weights(weights, report=None):
"""Rescale (name, tensor) pairs, dense or W4A16, for the float16 engine.
- ``model.embed_tokens.weight`` becomes the scaled embedding, and an
unscaled float16 copy is added as ``lm_head.weight`` (the untied head);
- every projection weight (dense) or W4A16 group scale becomes float16,
- with its shift for v/o/up/down, and must be exact;
+ with its shift for v/o/up/down, permitting finite rounding;
- everything else (norm weights, W4A16 codes and shapes) passes through
unchanged, and vLLM converts floating-point tensors to float16 itself.
"""
+ report = {} if report is None else report
for name, tensor in weights:
if name == LM_HEAD:
raise ValueError("the float16 rescale expects a checkpoint whose output head is "
"tied to the embedding, not a separate lm_head.weight")
if name == EMBEDDING:
- yield name, scale_embedding(tensor)
- yield LM_HEAD, tensor.to(torch.float16)
+ yield name, rounded(name, tensor, RESIDUAL_SHIFT, report, "embedding")
+ yield LM_HEAD, rounded(LM_HEAD, tensor, 0, report, "output_head")
elif _PROJECTION.match(name):
- yield name, exact(name, tensor, shift_of(name))
+ yield name, rounded(name, tensor, shift_of(name), report, "projections")
else:
+ if tensor.is_floating_point():
+ # Preserve the loader interface: vLLM still converts these tensors.
+ rounded(name, tensor, 0, report, "other")
yield name, tensor
+ # Use vLLM's configured logger so VLLM_LOGGING_LEVEL=INFO also exposes this
+ # diagnostic in its spawned worker. No vLLM import is needed for unit tests.
+ logging.getLogger("vllm.kittenml").info("float16 weight conversion: %s", report)
class ScaledSpeakerHead(torch.nn.Module):
diff --git a/kittenml/kittentts2/vllm/loader.py b/kittenml/kittentts2/vllm/loader.py
index dac411f..fc16061 100644
--- a/kittenml/kittentts2/vllm/loader.py
+++ b/kittenml/kittentts2/vllm/loader.py
@@ -1,5 +1,7 @@
"""vLLM plugin: selected KittenTTS weights, without an intermediate export."""
+import logging
+
from vllm.model_executor.model_loader.base_loader import BaseModelLoader
from ..weights import iter_lm_weights
@@ -10,16 +12,28 @@ class KittenModelLoader(BaseModelLoader):
# KittenTTS resolves the selected files before constructing the engine.
pass
+ def load_model(self, vllm_config, model_config, prefix=""):
+ model = super().load_model(vllm_config, model_config, prefix=prefix)
+ # AMD GPUs: check the 4-bit kernel on the weights as it repacked them (rocm.py).
+ references = getattr(self, "_probe_references", None)
+ self._probe_references = None
+ if references:
+ from .rocm import probe_w4a16
+ report = probe_w4a16(model, references, model_config.dtype)
+ logging.getLogger("vllm.kittenml").info("W4A16 kernel check passed: %s", report)
+ return model
+
def load_weights(self, model, model_config):
options = self.load_config.model_loader_extra_config
quantization = options.get("quantization")
- # The opt-in float16 fallback for GPUs without bfloat16 (fp16.py).
+ # Rescaled float16: finite rounding is measured; overflow remains an error.
float16 = options.get("float16_rescale", False)
if float16:
_check_float16_model(model, model_config)
+ probe = False
if quantization == "w4a16":
# vLLM chose each layer's kernel when it built the model; check before loading.
- _check_w4a16_kernels(model, model_config, float16)
+ probe = _check_w4a16_kernels(model, model_config, float16)
# Exact 4-bit weights straight from the trits, one tensor at a time.
from .w4a16 import iter_w4a16
weights = iter_w4a16(options["repo_dir"], options["config"], options["weights"])
@@ -32,6 +46,10 @@ class KittenModelLoader(BaseModelLoader):
if float16:
from .fp16 import rescale_weights
weights = rescale_weights(weights)
+ if probe:
+ from .rocm import keep_references
+ self._probe_references = {}
+ weights = keep_references(weights, self._probe_references)
loaded = model.load_weights(weights)
missing = set(dict(model.named_parameters())) - loaded - _kv_cache_scale_names(model)
if missing:
@@ -66,7 +84,7 @@ def _quantized_layers(model):
def _check_w4a16_kernels(model, model_config, float16=False):
- """Every quantized linear layer must run exact W4A16 on Marlin.
+ """Every quantized linear layer must run exact W4A16 on Marlin (NVIDIA).
vLLM picks the mixed-precision kernel per GPU (Machete on Hopper, Marlin
elsewhere, others when a kernel is disabled). Exact W4A16 was verified with
@@ -74,10 +92,16 @@ def _check_w4a16_kernels(model, model_config, float16=False):
engine process: VLLM_MARLIN_INPUT_DTYPE keeps the Marlin kernel but quantizes
its activations to 8 bits (W4A8), which shows in the kernel's activation type
(in vLLM 0.31.0 that is the only way the setting acts).
+
+ On AMD GPUs (ROCm), where vLLM has no Marlin, the one allowed kernel is
+ rocm.W4A16_KERNEL; True is returned so the loader checks its results after
+ loading (rocm.probe_w4a16).
"""
import torch
from vllm.model_executor.kernels.linear import MarlinLinearKernel
+ from .rocm import W4A16_KERNEL as ROCM_KERNEL, is_rocm
+
refuse = "W4A16: refusing to load: "
# bfloat16, or float16 in the opt-in float16 mode (its group scales are rescaled).
expected = torch.float16 if float16 else torch.bfloat16
@@ -91,12 +115,15 @@ def _check_w4a16_kernels(model, model_config, float16=False):
activations.setdefault(str(act_type), []).append(name)
if not chosen:
raise RuntimeError("W4A16: vLLM created no quantized linear layers")
- other = {kind: names for kind, names in chosen.items()
- if kind != MarlinLinearKernel.__name__}
+ rocm = is_rocm()
+ allowed = ROCM_KERNEL if rocm else MarlinLinearKernel.__name__
+ other = {kind: names for kind, names in chosen.items() if kind != allowed}
if other:
layers = sum(map(len, other.values()))
+ where = (f"on AMD GPUs only with {ROCM_KERNEL} (Radeon RX 7000 and RX 9000 series)"
+ if rocm else "only with MarlinLinearKernel")
raise RuntimeError(f"W4A16: vLLM chose {sorted(other)} for {layers} linear layers, but "
- "exact W4A16 is verified only with MarlinLinearKernel (check "
+ f"exact W4A16 is verified {where} (check "
"VLLM_DISABLED_KERNELS; with VLLM_ENABLE_V1_MULTIPROCESSING=0 vLLM "
"may still use the value from the first engine in this process)")
wrong = {act: names for act, names in activations.items() if act != str(model_config.dtype)}
@@ -105,6 +132,7 @@ def _check_w4a16_kernels(model, model_config, float16=False):
raise RuntimeError(refuse + f"{layers} linear layers would quantize their activations to "
f"{sorted(wrong)} instead of computing in {model_config.dtype} (check "
"VLLM_MARLIN_INPUT_DTYPE)")
+ return rocm
def _kv_cache_scale_names(model):
diff --git a/kittenml/kittentts2/vllm/rocm.py b/kittenml/kittentts2/vllm/rocm.py
new file mode 100644
index 0000000..6b47c5c
--- /dev/null
+++ b/kittenml/kittentts2/vllm/rocm.py
@@ -0,0 +1,150 @@
+"""AMD GPUs (ROCm) for the vLLM backend: the GPU check, and which kernel runs 4-bit weights.
+
+On NVIDIA GPUs vLLM runs KittenTTS's 4-bit (W4A16) layers with its Marlin kernel. Marlin is
+written with NVIDIA-only instructions (tensor-core ``mma.sync``, ``ldmatrix`` and ``cp.async`` in
+inline PTX), so vLLM does not build it for ROCm. On AMD GPUs vLLM 0.31.0 tries, in this order:
+
+- ``RDNA3W4A16LinearKernel`` (gfx1100, Radeon RX 7900 only). It splits every dot product into
+ 256-wide slices and adds each slice's float32 result into the bfloat16 output with an atomic
+ add, so a sum is rounded to bfloat16 once per slice (8 to 24 times for this model) and in an
+ order that changes from run to run. KittenTTS disables it.
+- ``RDNAHybridW4A16LinearKernel`` (gfx11 and gfx12: Radeon RX 7000 and RX 9000). For up to 5
+ rows (decoding), a HIP kernel keeps one float32 sum per output over the whole row and adds the
+ lanes of a wave in a fixed order; for more rows (prefill), a Triton kernel that also sums in
+ float32. KittenTTS allows this one, after the check below.
+- Triton, Conch and Exllama kernels: not checked, so 4-bit is refused (e.g. on Instinct GPUs).
+
+``probe_w4a16`` runs in vLLM's engine process once the kernel has repacked its weights, on two
+layers (one attention, one MLP projection), through both of the kernel's paths (1 and 64 rows):
+
+1. One-hot rows: each output is a single weight times 1 + 2^-7 (a value 8-bit activation formats
+ cannot hold), so it must equal that product rounded once, bit for bit. A wrong unpacking or
+ group scale, or quantized activations, change it.
+2. Random rows, run twice: the results must be bit-identical (a fixed summation order), and
+ within one unit in the last place plus 2^-14 of sum(|w*x|) of the exact sum (float32
+ accumulation; rounding the running sum to bfloat16 misses this by several units).
+"""
+
+import torch
+
+# The kernel KittenTTS allows for 4-bit weights on AMD GPUs, and the one it disables.
+W4A16_KERNEL = "RDNAHybridW4A16LinearKernel"
+W4A16_DISABLED_KERNELS = ("RDNA3W4A16LinearKernel",)
+# One attention and one MLP projection (inputs 2,048 and 6,144 wide).
+PROBE_LAYERS = ("model.layers.0.self_attn.o_proj", "model.layers.0.mlp.down_proj")
+# vLLM's hybrid kernel decodes up to 5 rows with its HIP kernel and prefills more with Triton.
+_PROBE_ROWS = (1, 64)
+_ONE_HOT = 1 + 2 ** -7
+_TOLERANCE = 2 ** -14
+
+
+def is_rocm():
+ """True when PyTorch is a ROCm (AMD) build; the GPU is then still called "cuda"."""
+ return bool(getattr(torch.version, "hip", None))
+
+
+def check_amd_gpu(dtype=None):
+ """Refuse AMD GPUs the installed ROCm build of PyTorch (and so vLLM) has no code for."""
+ arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
+ built = sorted({name.split(":")[0] for name in torch.cuda.get_arch_list()})
+ if built and arch not in built:
+ raise RuntimeError(f"this AMD GPU ({arch}) is not supported by the installed ROCm build "
+ f"of PyTorch and vLLM, which has code for {', '.join(built)} "
+ "(for Radeon: RX 7900 and RX 9000 series)")
+ if dtype == "float16":
+ raise RuntimeError("vllm_options['dtype']='float16' is not supported on AMD GPUs; "
+ "the AMD GPUs that vLLM supports have bfloat16, so leave dtype out")
+
+
+def has_w4a16_kernel():
+ """True on the AMD GPUs the allowed 4-bit kernel covers: gfx11 and gfx12 (Radeon RX 7000
+ and RX 9000 series). gfx1250 is excluded: vLLM counts it with its data-center GPUs
+ (platforms/rocm.py, _ON_CDNA) and its RDNAHybrid kernel refuses it."""
+ try:
+ arch = torch.cuda.get_device_properties(0).gcnArchName
+ except Exception: # noqa: BLE001 - no GPU to ask: no automatic 4-bit
+ return False
+ return arch.startswith(("gfx11", "gfx12")) and not arch.startswith("gfx1250")
+
+
+def keep_references(weights, references):
+ """Pass the weights through, keeping a CPU copy of the probed layers' 4-bit tensors."""
+ wanted = {f"{layer}.{part}" for layer in PROBE_LAYERS
+ for part in ("weight_packed", "weight_scale")}
+ for name, tensor in weights:
+ if name in wanted:
+ references[name] = tensor.detach().to("cpu", copy=True)
+ yield name, tensor
+
+
+def dequantize(packed, scale):
+ """compressed-tensors uint4b8 words and group scales -> the float32 weight they encode."""
+ from .w4a16 import GROUP_SIZE, NUM_BITS, OFFSET, PACK_FACTOR
+
+ words = packed.to(torch.int64) & 0xFFFFFFFF
+ shifts = torch.arange(PACK_FACTOR, dtype=torch.int64) * NUM_BITS
+ codes = (words.unsqueeze(-1) >> shifts) & ((1 << NUM_BITS) - 1)
+ signs = codes.reshape(packed.shape[0], -1) - OFFSET
+ # Exact: every code here times its group's scale is a product of two small floats.
+ return signs.to(torch.float32) * scale.to(torch.float32).repeat_interleave(GROUP_SIZE, dim=1)
+
+
+def _ulp(values, dtype):
+ """One unit in the last place of `dtype` at each value's magnitude (0 for 0)."""
+ _, exponent = torch.frexp(values)
+ ulp = torch.finfo(dtype).eps * torch.exp2((exponent - 1).to(values.dtype))
+ return torch.where(values == 0, torch.zeros_like(ulp), ulp)
+
+
+def probe_w4a16(model, references, dtype):
+ """Raise RuntimeError unless the 4-bit kernel computes the probed layers as described above."""
+ from .w4a16 import bit_equal
+
+ modules = dict(model.named_modules())
+ generator = torch.Generator().manual_seed(0)
+ report = {}
+ for layer in PROBE_LAYERS:
+ module = modules[layer]
+ kernel = type(module.scheme.kernel).__name__
+ weight = dequantize(references[f"{layer}.weight_packed"],
+ references[f"{layer}.weight_scale"])
+ out_features, in_features = weight.shape
+ device = next(module.parameters()).device
+
+ def run(x):
+ with torch.inference_mode():
+ return module.scheme.apply_weights(module, x.to(device), None).to("cpu")
+
+ def refuse(what):
+ raise RuntimeError(f"W4A16: refusing to load: {kernel} {what} for {layer}; 4-bit "
+ "weights are not available on this GPU: use bf16 weights with "
+ "vllm_options={'quantization': None}")
+
+ rows = max(_PROBE_ROWS)
+ picked = torch.linspace(0, in_features - 1, rows).round().long()
+ one_hot = torch.zeros(rows, in_features, dtype=dtype)
+ one_hot[torch.arange(rows), picked] = _ONE_HOT
+ expected = (weight[:, picked].T * _ONE_HOT).to(dtype)
+ random = torch.randn(rows, in_features, generator=generator).to(dtype)
+ exact = random.double() @ weight.double().T
+ bound = random.double().abs() @ weight.double().abs().T
+ worst = 0.0
+ for count in _PROBE_ROWS:
+ got = run(one_hot[:count])
+ if not bit_equal(got, expected[:count]):
+ wrong = int((got.float() != expected[:count].float()).sum())
+ refuse(f"does not reproduce the 4-bit weights exactly ({wrong} of "
+ f"{got.numel()} one-hot outputs differ, {count} rows)")
+ got = run(random[:count])
+ if not bit_equal(got, run(random[:count])):
+ refuse(f"gives different results for the same input ({count} rows)")
+ error = (got.double() - exact[:count]).abs()
+ allowed = _ulp(exact[:count], dtype) + _TOLERANCE * bound[:count]
+ if bool((error > allowed).any()):
+ over = int((error > allowed).sum())
+ refuse(f"does not sum in float32 ({over} of {error.numel()} outputs are further "
+ f"from the exact result than one unit in the last place, {count} rows)")
+ worst = max(worst, float((error / allowed.clamp_min(1e-30)).max()))
+ report[layer] = {"kernel": kernel, "shape": [out_features, in_features],
+ "worst_error_vs_allowed": round(worst, 4)}
+ return report
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..6df260c
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,27 @@
+"""Shared test setup."""
+
+import pytest
+import torch
+
+
[email protected](autouse=True)
+def _nvidia_platform_for_nvidia_tests(request, monkeypatch):
+ """The vLLM tests describe NVIDIA GPUs (none of them use a GPU). On a ROCm build of PyTorch
+ they would take the AMD paths, so make it look like a CUDA build for them;
+ tests/test_vllm_rocm.py sets the platform itself."""
+ if getattr(torch.version, "hip", None) and not request.module.__name__.endswith("test_vllm_rocm"):
+ monkeypatch.setattr(torch.version, "hip", None)
+
+
[email protected](autouse=True)
+def _no_real_gpu_memory(monkeypatch):
+ """Unit tests never size vLLM from the real GPU of the machine they run on (on a GPU host
+ the small-GPU fitting would otherwise read its free memory and size the tests' stub model
+ configs). Tests that need free/total numbers patch _free_gpu_memory themselves."""
+ def no_gpu():
+ raise RuntimeError("unit tests do not read the real GPU's free memory")
+ try:
+ import kittenml.kittentts2.vllm.backend as backend
+ except ImportError:
+ return
+ monkeypatch.setattr(backend, "_free_gpu_memory", no_gpu)
diff --git a/tests/test_vllm.py b/tests/test_vllm.py
index cb50d55..2e05463 100644
--- a/tests/test_vllm.py
+++ b/tests/test_vllm.py
@@ -587,57 +587,90 @@ def test_vllm_options_validate_quantization_dtype_and_cache_size():
engine, kitten = resolve_options(None)
assert engine == dict(gpu_memory_utilization=0.5, max_model_len=4096, max_num_seqs=8,
enforce_eager=False)
- assert kitten == dict(quantization=None, dtype=None, kv_cache_memory_bytes=None)
+ assert kitten == dict(quantization=None, dtype=None, kv_cache_memory_bytes=None,
+ max_num_batched_tokens=None)
engine, kitten = resolve_options({"quantization": "w4a16", "dtype": "bfloat16",
"kv_cache_memory_bytes": 1 << 30, "max_num_seqs": 4})
assert engine["kv_cache_memory_bytes"] == 1 << 30 and engine["max_num_seqs"] == 4
assert "quantization" not in engine and "dtype" not in engine
assert kitten["quantization"] == "w4a16" and kitten["dtype"] == "bfloat16"
+ engine, _ = resolve_options({"max_num_batched_tokens": 2048})
+ assert engine["max_num_batched_tokens"] == 2048
+ assert "max_num_batched_tokens" not in resolve_options({"max_num_batched_tokens": None})[0]
for bad, match in [({"quantization": "w8a8"}, "quantization"),
({"quantization": "W4A16"}, "quantization"),
({"dtype": "fp16"}, "dtype"),
- ({"dtype": "float32"}, "dtype"),
+ ({"dtype": "float64"}, "dtype"),
({"kv_cache_memory_bytes": 0}, "kv_cache_memory_bytes"),
({"kv_cache_memory_bytes": 1.5e9}, "kv_cache_memory_bytes"),
({"kv_cache_memory_bytes": True}, "kv_cache_memory_bytes"),
+ ({"max_num_batched_tokens": 0}, "max_num_batched_tokens"),
+ ({"max_num_batched_tokens": 2048.0}, "max_num_batched_tokens"),
({"kv_cache_dtype": "fp8"}, "unknown vllm_options")]:
with pytest.raises(ValueError, match=match):
resolve_options(bad)
def test_float16_is_an_explicit_option():
- # float16 is the opt-in fallback for GPUs without bfloat16 (fp16.py); it is
- # never chosen unless asked for.
+ # Explicit dtype overrides are kept separate from vLLM's engine options.
from kittenml.kittentts2.vllm.backend import resolve_options
for options in ({"dtype": "float16"}, {"dtype": "float16", "quantization": "w4a16"}):
engine, kitten = resolve_options(options)
assert kitten["dtype"] == "float16" and "dtype" not in engine
assert resolve_options(None)[1]["dtype"] is None
+ assert resolve_options({"dtype": "float32"})[1]["dtype"] == "float32"
-def test_dtype_follows_hardware_and_gpus_without_bfloat16_need_the_float16_opt_in():
+def test_gpu_capability_and_explicit_dtype_are_checked_before_download():
from kittenml.kittentts2.vllm.backend import validate_environment
with mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec", return_value=object()), \
- mock.patch("torch.cuda.is_available", return_value=True):
+ mock.patch("torch.cuda.is_available", return_value=True), \
+ mock.patch("torch.cuda.get_arch_list", return_value=["sm_70", "sm_75", "sm_80"]):
for capability in ((8, 0), (8, 6), (12, 0)):
with mock.patch("torch.cuda.get_device_capability", return_value=capability):
- for dtype in (None, "bfloat16", "float16"):
- validate_environment(dtype=dtype)
- with mock.patch("torch.cuda.get_device_capability", return_value=(7, 5)):
- for dtype in (None, "bfloat16"):
- with pytest.raises(RuntimeError, match=r"SM75\) has no bfloat16.*opt in to the "
- r"float16 fallback with vllm_options="
- r"\{'dtype': 'float16'\}.*not the optimal"):
- validate_environment(dtype=dtype)
- validate_environment(dtype="float16")
- for capability, name in (((7, 0), "SM70"), ((6, 1), "SM61")):
+ for dtype in (None, "bfloat16", "float16", "float32"):
+ assert validate_environment(dtype=dtype) == capability
+ for capability in ((7, 5), (7, 0)):
with mock.patch("torch.cuda.get_device_capability", return_value=capability):
- for dtype in (None, "float16"):
- with pytest.raises(RuntimeError, match=name + r"\) is not supported by the "
- r"vLLM backend.*7.5 or newer"):
- validate_environment(dtype=dtype)
+ for dtype in (None, "float16", "float32"):
+ assert validate_environment(dtype=dtype) == capability
+ with pytest.raises(ValueError, match="no native bfloat16"):
+ validate_environment(dtype="bfloat16")
+ with mock.patch("torch.cuda.get_device_capability", return_value=(6, 1)):
+ for dtype in (None, "float16", "float32"):
+ with pytest.raises(RuntimeError, match="SM61.*default backend"):
+ validate_environment(dtype=dtype)
+
+
+def test_v100_requires_a_pytorch_build_that_can_execute_sm70():
+ from kittenml.kittentts2.vllm.backend import validate_environment
+
+ with mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec", return_value=object()), \
+ mock.patch("torch.cuda.is_available", return_value=True), \
+ mock.patch("torch.cuda.get_device_capability", return_value=(7, 0)):
+ with mock.patch("torch.cuda.get_arch_list", return_value=["sm_75", "sm_80", "compute_80"]):
+ with pytest.raises(RuntimeError, match="does not support SM70.*CUDA 12.6"):
+ validate_environment()
+ with mock.patch("torch.cuda.get_arch_list", return_value=["sm_75", "compute_70"]):
+ assert validate_environment() == (7, 0)
+
+
+def test_legacy_gpu_options_choose_the_measured_mode_and_respect_overrides(monkeypatch):
+ from kittenml.kittentts2.vllm.backend import options_for_gpu
+
+ for capability in ((8, 0), (8, 6), (12, 0), None):
+ for given in (None, {}, {"quantization": None}, {"dtype": "bfloat16"}):
+ assert options_for_gpu(given, capability) is given
+ assert options_for_gpu(None, (7, 5)) == {"dtype": "float16", "quantization": "w4a16"}
+ assert options_for_gpu(None, (7, 0)) == {"dtype": "float16"}
+ assert options_for_gpu({"quantization": None}, (7, 5)) == {"dtype": "float16", "quantization": None}
+ assert options_for_gpu({"dtype": "float32"}, (7, 5)) == {"dtype": "float32"}
+ with pytest.raises(ValueError, match="W4A16 requires compute capability 7.5"):
+ options_for_gpu({"quantization": "w4a16"}, (7, 0))
+ monkeypatch.setenv("VLLM_MARLIN_INPUT_DTYPE", "int8")
+ assert options_for_gpu(None, (7, 5)) == {"dtype": "float16"}
def test_vllm_options_are_checked_before_model_download(monkeypatch):
@@ -656,20 +689,19 @@ def test_vllm_options_are_checked_before_model_download(monkeypatch):
download.assert_not_called()
-def test_gpus_without_bfloat16_are_refused_before_model_download():
+def test_old_gpu_and_automatic_float16_emb4_errors_precede_model_download():
resolved = (None, "example/repo", {"type": "KITTEN2"})
with mock.patch("kittenml.get_model.resolve_repo", return_value=resolved), \
mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec", return_value=object()), \
mock.patch("torch.cuda.is_available", return_value=True), \
- mock.patch("torch.cuda.get_device_capability", return_value=(7, 5)), \
mock.patch("kittenml.get_model.snapshot_download") as download:
- with pytest.raises(RuntimeError, match="SM75.*no bfloat16.*'dtype': 'float16'"):
- KittenTTS("example/repo", backend="vllm")
+ with mock.patch("torch.cuda.get_device_capability", return_value=(6, 1)):
+ with pytest.raises(RuntimeError, match="SM61.*default backend"):
+ KittenTTS("example/repo", backend="vllm")
+ with mock.patch("torch.cuda.get_device_capability", return_value=(7, 5)):
+ with pytest.raises(ValueError, match="float16.*emb4"):
+ KittenTTS("example/repo", backend="vllm", weights="emb4")
download.assert_not_called()
- # With the opt-in, the checks pass and the download starts.
- download.side_effect = RuntimeError("download started")
- with pytest.raises(RuntimeError, match="download started"):
- KittenTTS("example/repo", backend="vllm", vllm_options={"dtype": "float16"})
def test_w4a16_refuses_marlin_environment_overrides(monkeypatch, tmp_path):
@@ -1107,14 +1139,21 @@ def test_float16_rescale_dense_and_w4a16_give_the_same_exact_float16_weights(tmp
assert bit_equal(rebuilt, dense[name]), name
-def test_float16_rescale_refuses_weights_it_cannot_hold_exactly():
+def test_float16_rescale_rounds_small_weights_and_reports_the_error(caplog):
from kittenml.kittentts2.vllm.fp16 import is_exact, rescale_weights
weight = torch.full((2, 128), 0.25, dtype=torch.bfloat16)
weight[1, 7] = 2.0 ** -20 # x 2^-6 = 2^-26: below float16's smallest subnormal
pairs = [("model.layers.0.self_attn.o_proj.weight", weight)]
- with pytest.raises(ValueError, match=r"o_proj.weight x 2\^-6 is not exact in float16"):
- dict(rescale_weights(pairs))
+ report = {}
+ with caplog.at_level("INFO", logger="vllm.kittenml"):
+ converted = dict(rescale_weights(pairs, report))
+ assert converted[pairs[0][0]][1, 7] == 0
+ assert converted[pairs[0][0]][0, 0] == 2.0 ** -8
+ assert report["projections"] == {
+ "elements": 256, "rounded": 1, "max_absolute_error": 2.0 ** -26,
+ "worst_tensor": pairs[0][0]}
+ assert sum("float16 weight conversion" in r.message for r in caplog.records) == 1
# The same value is exact without a shift (q_proj) ... and -0.0 must stay -0.0.
assert len(dict(rescale_weights([("model.layers.0.self_attn.q_proj.weight", weight)]))) == 1
zero = torch.tensor([-0.0], dtype=torch.bfloat16)
@@ -1124,6 +1163,32 @@ def test_float16_rescale_refuses_weights_it_cannot_hold_exactly():
dict(rescale_weights([("lm_head.weight", weight)]))
[email protected]("name", ["model.embed_tokens.weight", "model.norm.weight",
+ "model.layers.0.self_attn.q_proj.weight",
+ "model.layers.0.mlp.down_proj.weight_scale"])
[email protected]("value", [float("nan"), float("inf"), 2.0 ** 24])
+def test_float16_rescale_still_refuses_nonfinite_and_overflowing_weights(name, value):
+ from kittenml.kittentts2.vllm.fp16 import rescale_weights
+
+ with pytest.raises(ValueError, match="nonfinite values or overflows float16"):
+ dict(rescale_weights([(name, torch.tensor([value]))]))
+
+
+def test_float16_rescale_tracks_embedding_rounding_separately_and_keeps_codes():
+ from kittenml.kittentts2.vllm.fp16 import rescale_weights
+
+ embedding = torch.tensor([[2.0 ** -20, -0.0]], dtype=torch.bfloat16)
+ codes = torch.tensor([1, 2], dtype=torch.int32)
+ report = {}
+ converted = dict(rescale_weights([("model.embed_tokens.weight", embedding),
+ ("model.layers.0.mlp.up_proj.weight_packed", codes)], report))
+ assert report["embedding"]["rounded"] == 1
+ assert report["output_head"]["rounded"] == 0
+ assert converted["model.layers.0.mlp.up_proj.weight_packed"] is codes
+ assert torch.signbit(converted["model.embed_tokens.weight"][0, 1])
+ assert converted["lm_head.weight"][0, 0] == 2.0 ** -20
+
+
def test_float16_prompt_embeddings_match_the_engine_scale():
pytest.importorskip("vllm")
from kittenml.kittentts2.vllm.backend import VLLMBackend
@@ -1244,7 +1309,7 @@ def test_vllm_loader_bfloat16_paths_hand_over_the_checkpoint_tensors_untouched()
if hasattr(module, "variance_epsilon"))
-def test_engine_receives_the_float16_rescale_only_when_asked(tmp_path):
+def test_engine_receives_float16_when_selected_and_warns_once_on_legacy_gpu(tmp_path, caplog):
pytest.importorskip("vllm")
from kittenml.kittentts2.vllm.backend import VLLMBackend
from kittenml.kittentts2.vllm.fp16 import PLAN, ScaledSpeakerHead, scale_embedding
@@ -1252,11 +1317,11 @@ def test_engine_receives_the_float16_rescale_only_when_asked(tmp_path):
seen = []
embedding = torch.full((2, 4), 0.03, dtype=torch.bfloat16)
- def run(options):
+ def run(options, capability=None):
owner = SimpleNamespace(device="cpu", repo_dir=tmp_path, config={}, weights="packed",
token_map=None, _load_lm_weights=mock.Mock(return_value={
"model.embed_tokens.weight": embedding}))
- with mock.patch("kittenml.kittentts2.vllm.backend.validate_environment") as validate, \
+ with mock.patch("kittenml.kittentts2.vllm.backend.validate_environment", return_value=capability) as validate, \
mock.patch("transformers.AutoConfig.from_pretrained", return_value=SimpleNamespace(
model_type="qwen3", hidden_size=4)), \
mock.patch("transformers.AutoTokenizer.from_pretrained"), \
@@ -1287,3 +1352,325 @@ def test_engine_receives_the_float16_rescale_only_when_asked(tmp_path):
embedding)
assert backend.spk_proj is head.return_value
assert head.call_args.args[3] is torch.bfloat16
+ caplog.clear()
+ with caplog.at_level("WARNING"):
+ owner, backend, head, kwargs = run(None, (7, 5))
+ assert kwargs["dtype"] is torch.float16 and kwargs["quantization"] == "compressed-tensors"
+ assert sum("has no native bfloat16" in record.message for record in caplog.records) == 1
+ assert "rounded float16 with 4-bit weights" in caplog.text
+ assert "supported, not optimal" in caplog.text
+
+
+# ── Fitting vLLM to the GPU's free memory ─────────────────────────────────────
+GIB = 1 << 30
+# KittenTTS 2's language model (lm/config.json).
+_LM = SimpleNamespace(hidden_size=2048, num_hidden_layers=28, num_attention_heads=16,
+ num_key_value_heads=8, head_dim=128, intermediate_size=6144,
+ vocab_size=158241, tie_word_embeddings=True)
+
+
+def test_lm_memory_matches_what_vllm_reports_for_the_weights():
+ from kittenml.kittentts2.vllm.backend import lm_memory
+
+ # vLLM 0.31.0 logs "Model loading took 3.24 GiB" (bf16) and "1.29 GiB" (w4a16).
+ bf16, kv_token = lm_memory(_LM)
+ assert round(bf16 / GIB, 2) == 3.23 and kv_token == 112 * 1024
+ assert round(lm_memory(_LM, "w4a16")[0] / GIB, 2) == 1.28
+ # float16 keeps a separate output head (618 MiB, docs/vllm.md).
+ assert (lm_memory(_LM, None, float16=True)[0] - bf16) >> 20 == 618
+ assert lm_memory(_LM, float32=True) == (bf16 * 2, kv_token * 2)
+
+
+def test_float32_fits_weights_and_double_width_cache_without_choosing_w4a16():
+ from kittenml.kittentts2.vllm.backend import check_options, fit_to_gpu, lm_memory
+
+ free, total = 11600 << 20, 12288 << 20
+ options, report = fit_to_gpu({"dtype": "float32"}, free, total, _LM, force=True)
+ assert report["fitted"]
+ assert options["dtype"] == "float32" and "quantization" not in options
+ assert options["max_num_batched_tokens"] == 2048
+ assert options.get("max_model_len", 4096) == 4096
+ assert report["planned_kv_cache_tokens"] >= 4096
+ assert options["gpu_memory_utilization"] * total + (2816 + 256) * (1 << 20) <= free
+ with pytest.raises(ValueError, match="W4A16.*not float32"):
+ check_options({"dtype": "float32", "quantization": "w4a16"}, "packed")
+ with pytest.raises(RuntimeError, match="not enough free GPU memory"):
+ fit_to_gpu({"dtype": "float32"}, 5600 << 20, 6000 << 20, _LM)
+
+
[email protected]("total_gib, free_gib", [(95.0, 94.0), (31.4, 30.8), (23.5, 23.0),
+ (15.6, 15.0), (11.6, 11.2), (9.6, 9.3)])
+def test_defaults_are_kept_on_gpus_with_room_for_them(total_gib, free_gib):
+ from kittenml.kittentts2.vllm.backend import fit_to_gpu
+
+ for options in ({}, {"quantization": "w4a16"}, {"max_num_seqs": 2}):
+ fitted, report = fit_to_gpu(options, int(free_gib * GIB), int(total_gib * GIB), _LM)
+ assert fitted == options and report["fitted"] is False and "suggested" not in report
+
+
[email protected]("total_gib, free_gib, options", [
+ (31.4, 30.8, {"gpu_memory_utilization": 0.9}), # vLLM's own default share
+ (23.5, 23.0, {"gpu_memory_utilization": 0.9}),
+ (79.15, 41.5, {}), # a shared 80 GB GPU
+ (9.77, 7.8, {}), # a 10 GB card with a busy desktop
+ (11.6, 5.0, {}), # a 12 GB card that is mostly in use
+])
+def test_larger_gpus_and_short_settings_are_never_changed_only_given_a_suggestion(
+ total_gib, free_gib, options):
+ from kittenml.kittentts2.vllm.backend import fit_to_gpu
+
+ fitted, report = fit_to_gpu(options, int(free_gib * GIB), int(total_gib * GIB), _LM)
+ assert fitted == options and report["fitted"] is False
+ # The settings leave too little room for audio decoding, so a fitting set is suggested.
+ assert report["decoding_room_mib"] < 2816
+ assert report["suggested"] is None or "gpu_memory_utilization" in report["suggested"]
+
+
+def test_small_gpus_get_4bit_and_a_share_that_leaves_room_for_decoding():
+ from kittenml.kittentts2.vllm.backend import (_ENGINE_CONTEXT_BYTES, _MAIN_PROCESS_BYTES,
+ fit_to_gpu)
+
+ total, free = int(7.62 * GIB), int(7.39 * GIB) # RTX 4060 8 GB
+ fitted, report = fit_to_gpu({}, free, total, _LM)
+ assert report["fitted"] and fitted["quantization"] == "w4a16"
+ # vLLM's default prefill step still fits here, so it is kept.
+ assert "max_num_batched_tokens" not in fitted and "max_model_len" not in fitted
+ share = fitted["gpu_memory_utilization"] * total
+ assert share <= free - _ENGINE_CONTEXT_BYTES - _MAIN_PROCESS_BYTES
+ # The planned cache holds four full requests (4,096 + 32 tokens each).
+ assert report["planned_kv_cache_tokens"] == 4 * 4128 and report["full_requests"] == 4
+ assert set(report["chosen"]) == {"quantization", "gpu_memory_utilization"}
+ # With 5.25 GiB free a full request fits only with 2,048-token prefill steps.
+ fitted, _ = fit_to_gpu({}, int(5.25 * GIB), total, _LM)
+ assert fitted["max_num_batched_tokens"] == 2048 and "max_model_len" not in fitted
+
+
+def test_prefill_step_choice_keeps_the_same_rounding_margin_as_the_context_check():
+ from kittenml.kittentts2.vllm.backend import (_ENGINE_CONTEXT_BYTES, _KV_MARGIN_TOKENS,
+ _MAIN_PROCESS_BYTES, _VLLM_BATCHED_TOKENS,
+ _engine_bytes, fit_to_gpu, lm_memory)
+
+ # Free memory inside the window where a full request fits with vLLM's 8,192-token prefill
+ # step, but not once the share's rounding margin (total / 10^6) is taken off: the 2,048
+ # step must be chosen then, keeping the full 4,096-token context instead of cutting it.
+ total = int(7.62 * GIB)
+ weights, kv_token = lm_memory(_LM, "w4a16")
+ one_request = (4096 + _KV_MARGIN_TOKENS) * kv_token
+ free = int(_ENGINE_CONTEXT_BYTES + _MAIN_PROCESS_BYTES
+ + _engine_bytes(weights, _VLLM_BATCHED_TOKENS) + one_request + total / 2e6)
+ fitted, _ = fit_to_gpu({}, free, total, _LM)
+ assert fitted["max_num_batched_tokens"] == 2048 and "max_model_len" not in fitted
+
+
+def test_options_the_caller_gives_are_never_changed():
+ from kittenml.kittentts2.vllm.backend import fit_to_gpu
+
+ total, free = int(7.62 * GIB), int(7.39 * GIB)
+ given = {"quantization": None, "max_num_batched_tokens": None, "max_model_len": 4096}
+ fitted, report = fit_to_gpu(given, free, total, _LM)
+ assert {k: fitted[k] for k in given} == given and set(report["chosen"]) == {
+ "gpu_memory_utilization"}
+ # A memory share the caller set is theirs: nothing else is chosen around it, even when
+ # it leaves too little room (then only a suggestion is made).
+ for options in ({"gpu_memory_utilization": 0.45}, {"gpu_memory_utilization": 0.7},
+ {"kv_cache_memory_bytes": 1 << 29}):
+ fitted, report = fit_to_gpu(options, free, total, _LM)
+ assert fitted == options and report["fitted"] is False
+ assert report["suggested"]["quantization"] == "w4a16"
+ # 4-bit is not chosen where it is not allowed (non-NVIDIA, or a refusing environment).
+ fitted, _ = fit_to_gpu({}, free, total, _LM, w4a16=False)
+ assert "quantization" not in fitted
+
+
+def test_tight_gpus_shorten_the_context_and_hopeless_ones_are_refused_with_a_size():
+ from kittenml.kittentts2.vllm.backend import fit_to_gpu
+
+ total = int(7.62 * GIB)
+ fitted, report = fit_to_gpu({}, int(4.95 * GIB), total, _LM)
+ assert 2048 <= fitted["max_model_len"] < 4096 and report["planned_kv_cache_tokens"] > 2048
+ with pytest.raises(RuntimeError, match=r"about [\d,]+ MiB free is needed and 4,096 MiB"):
+ fit_to_gpu({}, 4 * GIB, total, _LM)
+ # An explicit max_model_len is not shortened: it is refused instead.
+ with pytest.raises(RuntimeError, match="not enough free GPU memory"):
+ fit_to_gpu({"max_model_len": 4096}, int(4.95 * GIB), total, _LM)
+
+
+def test_rounded_share_still_holds_one_full_request():
+ """vLLM's cache is ceil(total * utilization) - the rest; rounding must not cut below a request."""
+ import math
+ from kittenml.kittentts2.vllm.backend import _engine_bytes, fit_to_gpu, lm_memory
+
+ total = int(7.62 * GIB)
+ for free_mib in range(4800, 8000, 7):
+ try:
+ fitted, _ = fit_to_gpu({}, free_mib << 20, total, _LM)
+ except RuntimeError:
+ continue
+ weights, kv_token = lm_memory(_LM, fitted.get("quantization"))
+ fixed = _engine_bytes(weights, fitted.get("max_num_batched_tokens", 8192))
+ cache = math.ceil(total * fitted["gpu_memory_utilization"]) - fixed
+ assert cache >= (fitted.get("max_model_len", 4096) + 32) * kv_token, free_mib
+
+
+def test_fit_never_picks_4bit_on_amd_or_when_the_environment_refuses_it(monkeypatch):
+ from kittenml.kittentts2.vllm.backend import VLLMBackend
+
+ small = (int(7.39 * GIB), int(7.62 * GIB))
+ with mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory", return_value=small):
+ assert VLLMBackend._fit({}, _LM)[0]["quantization"] == "w4a16"
+ # An AMD GPU without the checked RDNA 4-bit kernel (Radeon RX 7000/9000 have it,
+ # tests/test_vllm_rocm.py).
+ with mock.patch("torch.version.hip", "6.3"), \
+ mock.patch("torch.cuda.get_device_properties",
+ return_value=SimpleNamespace(gcnArchName="gfx942:sramecc+:xnack-")):
+ fitted, report = VLLMBackend._fit({}, _LM)
+ assert report["fitted"] and "quantization" not in fitted
+ monkeypatch.setenv("VLLM_MARLIN_USE_ATOMIC_ADD", "1")
+ fitted, report = VLLMBackend._fit({}, _LM)
+ assert report["fitted"] and "quantization" not in fitted
+ # A model that is not 16-bit is left alone (the byte counts assume 2-byte weights).
+ assert VLLMBackend._fit({}, _LM, half=False) == ({}, {"fitted": False,
+ "skipped": "not a 16-bit model"})
+
+
+def test_fit_warnings_label_the_fallback_and_say_when_nothing_was_changed(caplog):
+ from kittenml.kittentts2.vllm.backend import VLLMBackend
+
+ with mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(int(7.39 * GIB), int(7.62 * GIB))), caplog.at_level("WARNING"):
+ VLLMBackend._fit({}, _LM)
+ assert "supported, but not the optimal path" in caplog.text
+ assert "16,512 tokens (4 full-length requests at a time)" in caplog.text
+ caplog.clear()
+ with mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(5691 << 20, 5798 << 20)), caplog.at_level("WARNING"):
+ VLLMBackend._fit({}, _LM)
+ assert "(1 full-length request at a time)" in caplog.text
+ caplog.clear()
+ with mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(int(30.8 * GIB), int(31.4 * GIB))), caplog.at_level("WARNING"):
+ fitted, _ = VLLMBackend._fit({"gpu_memory_utilization": 0.9}, _LM)
+ assert fitted == {"gpu_memory_utilization": 0.9}
+ assert "nothing was changed" in caplog.text and "left for audio decoding" in caplog.text
+ caplog.clear()
+ with mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(int(30.8 * GIB), int(31.4 * GIB))), caplog.at_level("WARNING"):
+ VLLMBackend._fit({}, _LM)
+ assert caplog.text == ""
+
+
+def test_backend_passes_the_unchanged_defaults_on_a_large_gpu_and_fitted_ones_on_a_small_one(
+ tmp_path):
+ pytest.importorskip("vllm")
+ from kittenml.kittentts2.vllm.backend import VLLMBackend
+
+ def run(free, total, options=None):
+ seen = {}
+ owner = SimpleNamespace(device="cuda", repo_dir=tmp_path, config={}, weights="packed",
+ token_map=None, _load_lm_weights=mock.Mock(return_value={
+ "model.embed_tokens.weight": torch.zeros(2, 4)}))
+ with mock.patch("kittenml.kittentts2.vllm.backend.validate_environment"), \
+ mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(free, total)), \
+ mock.patch("transformers.AutoConfig.from_pretrained",
+ return_value=SimpleNamespace(model_type="qwen3", **vars(_LM))), \
+ mock.patch("transformers.AutoTokenizer.from_pretrained"), \
+ mock.patch("kittenml.kittentts2.speaker.load_speaker_head"), \
+ mock.patch("vllm.LLM", side_effect=lambda **kw: seen.update(kw)):
+ backend = VLLMBackend(owner, options)
+ return backend, seen
+
+ backend, large = run(int(30.8 * GIB), int(31.4 * GIB))
+ _, explicit = run(int(30.8 * GIB), int(31.4 * GIB), {"gpu_memory_utilization": 0.5,
+ "max_model_len": 4096})
+ assert large == explicit and backend.auto_fit["fitted"] is False
+ assert {"quantization", "max_num_batched_tokens", "kv_cache_memory_bytes"}.isdisjoint(large)
+ assert large["gpu_memory_utilization"] == 0.5 and large["max_model_len"] == 4096
+ backend, small = run(int(7.39 * GIB), int(7.62 * GIB))
+ assert backend.auto_fit["fitted"] and small["quantization"] == "compressed-tensors"
+ assert "max_num_batched_tokens" not in small and small["gpu_memory_utilization"] < 0.5
+ _, smaller = run(int(5.25 * GIB), int(7.62 * GIB))
+ assert smaller["max_num_batched_tokens"] == 2048
+ assert small["model_loader_extra_config"]["quantization"] == "w4a16"
+
+
+def test_a_torchcodec_that_cannot_load_is_refused_with_what_to_do():
+ import sys
+ import types
+ from kittenml.kittentts2.vllm.backend import check_torchcodec
+
+ class Broken(types.ModuleType):
+ def __init__(self, error):
+ super().__init__("torchcodec.decoders")
+ self.error = error
+
+ def __getattr__(self, name):
+ raise self.error
+
+ def run(error):
+ modules = {"torchcodec": types.ModuleType("torchcodec"),
+ "torchcodec.decoders": Broken(error)}
+ with mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec",
+ return_value=object()), mock.patch.dict(sys.modules, modules):
+ check_torchcodec()
+
+ # What vLLM copes with passes: no FFmpeg (RuntimeError), an incomplete install.
+ run(RuntimeError("Could not load libtorchcodec. Likely causes: FFmpeg is not installed"))
+ run(ImportError("cannot import name AudioDecoder"))
+ # A build for another CUDA version, with FFmpeg present, raises OSError: refused.
+ with pytest.raises(RuntimeError, match=r"torchcodec is installed but cannot load \(Could "
+ r"not load this library.*pip uninstall torchcodec"):
+ run(OSError("Could not load this library: .../libtorchcodec_core6.so\nmore detail"))
+ # Not installed: nothing to check.
+ with mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec",
+ return_value=None):
+ check_torchcodec()
+
+
+def test_engine_is_stopped_at_exit_before_multiprocessing_waits_for_it():
+ import weakref
+ from kittenml.kittentts2.vllm.backend import _stop_engine
+
+ class Backend: # VLLMBackend stand-in; SimpleNamespace takes no weak references
+ pass
+
+ calls = []
+ backend = Backend()
+ backend.engine = SimpleNamespace(llm_engine=SimpleNamespace(
+ engine_core=SimpleNamespace(shutdown=lambda: calls.append("shutdown"))))
+ ref = weakref.ref(backend)
+ _stop_engine(ref)
+ assert calls == ["shutdown"]
+
+ def refuse():
+ raise RuntimeError("already stopped")
+ backend.engine.llm_engine.engine_core.shutdown = refuse
+ _stop_engine(ref) # errors at exit are swallowed
+ del backend
+ _stop_engine(ref) # a backend already collected is skipped
+
+
+def test_backend_registers_the_engine_stop_at_exit(tmp_path):
+ pytest.importorskip("vllm")
+ import weakref
+ from kittenml.kittentts2.vllm.backend import VLLMBackend, _stop_engine
+
+ owner = SimpleNamespace(device="cuda", repo_dir=tmp_path, config={}, weights="packed",
+ token_map=None, _load_lm_weights=mock.Mock(return_value={
+ "model.embed_tokens.weight": torch.zeros(2, 4)}))
+ with mock.patch("kittenml.kittentts2.vllm.backend.validate_environment"), \
+ mock.patch("torch.cuda.get_device_capability", return_value=(8, 6)), \
+ mock.patch("transformers.AutoConfig.from_pretrained", return_value=SimpleNamespace(
+ model_type="qwen3", hidden_size=4)), \
+ mock.patch("transformers.AutoTokenizer.from_pretrained"), \
+ mock.patch("kittenml.kittentts2.speaker.load_speaker_head"), \
+ mock.patch("vllm.LLM", return_value=mock.sentinel.engine), \
+ mock.patch("kittenml.kittentts2.vllm.backend.atexit") as fake_atexit:
+ backend = VLLMBackend(owner)
+ # Registered once, after the engine exists, with a weak reference so the
+ # handler does not keep the backend (and its engine) alive.
+ fake_atexit.register.assert_called_once()
+ handler, ref = fake_atexit.register.call_args.args
+ assert handler is _stop_engine
+ assert isinstance(ref, weakref.ref) and ref() is backend
+ assert backend.engine is mock.sentinel.engine
diff --git a/tests/test_vllm_rocm.py b/tests/test_vllm_rocm.py
new file mode 100644
index 0000000..47994b0
--- /dev/null
+++ b/tests/test_vllm_rocm.py
@@ -0,0 +1,298 @@
+"""AMD (ROCm) paths of the vLLM backend and the audio decoder; no GPU, model download or ROCm
+build required."""
+
+from types import SimpleNamespace
+from unittest import mock
+
+import pytest
+import torch
+
+from kittenml.kittentts2.vllm import rocm
+from kittenml.kittentts2.vllm.w4a16 import GROUP_SIZE, pack_int4
+
+
+def _amd(arch="gfx1100", built=("gfx90a", "gfx942", "gfx1100", "gfx1201")):
+ """Patches that make this PyTorch look like a ROCm build on an AMD GPU."""
+ return [mock.patch.object(torch.version, "hip", "7.2.53211"),
+ mock.patch("torch.cuda.is_available", return_value=True),
+ mock.patch("torch.cuda.get_device_properties",
+ return_value=SimpleNamespace(gcnArchName=f"{arch}:sramecc-:xnack-")),
+ mock.patch("torch.cuda.get_arch_list", return_value=list(built)),
+ mock.patch("torch.cuda.get_device_capability",
+ side_effect=AssertionError("NVIDIA capability checked on AMD"))]
+
+
+def _apply(patches):
+ for patch in patches:
+ patch.start()
+
+
+def test_amd_gpus_are_checked_by_architecture_not_nvidia_capability():
+ from kittenml.kittentts2.vllm.backend import validate_environment
+ find = mock.patch("kittenml.kittentts2.vllm.backend.importlib.util.find_spec",
+ return_value=object())
+ for arch in ("gfx1100", "gfx1201"):
+ with find, mock.patch("kittenml.kittentts2.vllm.backend.check_torchcodec") as torchcodec:
+ _apply(_amd(arch))
+ try:
+ validate_environment()
+ # vLLM imports torchcodec on AMD too, so a broken one is refused there as well.
+ torchcodec.assert_called_once_with()
+ with pytest.raises(RuntimeError, match="'float16' is not supported on AMD GPUs"):
+ validate_environment(dtype="float16")
+ finally:
+ mock.patch.stopall()
+ with find:
+ _apply(_amd("gfx1030"))
+ try:
+ with pytest.raises(RuntimeError, match=r"AMD GPU \(gfx1030\) is not supported.*"
+ r"gfx1100, gfx1201"):
+ validate_environment()
+ finally:
+ mock.patch.stopall()
+
+
+def test_w4a16_on_amd_disables_the_rdna3_kernel_and_keeps_the_hybrid_one():
+ from kittenml.kittentts2.vllm.backend import (check_w4a16_environment,
+ w4a16_engine_environment)
+ with mock.patch.object(torch.version, "hip", "7.2.53211"):
+ assert w4a16_engine_environment({}) == {"VLLM_DISABLED_KERNELS": "RDNA3W4A16LinearKernel"}
+ assert w4a16_engine_environment({"VLLM_DISABLED_KERNELS": "ExllamaLinearKernel"}) == {
+ "VLLM_DISABLED_KERNELS": "ExllamaLinearKernel,RDNA3W4A16LinearKernel"}
+ check_w4a16_environment({"VLLM_DISABLED_KERNELS": "MarlinLinearKernel"})
+ with pytest.raises(RuntimeError, match="RDNAHybridW4A16LinearKernel"):
+ check_w4a16_environment({"VLLM_DISABLED_KERNELS": "RDNAHybridW4A16LinearKernel"})
+ # NVIDIA GPUs are unchanged.
+ with mock.patch.object(torch.version, "hip", None):
+ assert w4a16_engine_environment({}) == {"VLLM_DISABLED_KERNELS": "MacheteLinearKernel"}
+ check_w4a16_environment({"VLLM_DISABLED_KERNELS": "RDNAHybridW4A16LinearKernel"})
+
+
+def _kernel(name):
+ kernel = object.__new__(type(name, (), {}))
+ kernel.config = SimpleNamespace(act_type=torch.bfloat16)
+ module = torch.nn.Module()
+ module.scheme = SimpleNamespace(kernel=kernel)
+ return module
+
+
+def test_loader_allows_only_the_hybrid_kernel_on_amd_and_asks_for_the_probe():
+ pytest.importorskip("vllm")
+ from kittenml.kittentts2.vllm.loader import _check_w4a16_kernels
+
+ bf16 = SimpleNamespace(dtype=torch.bfloat16)
+ model = torch.nn.Module()
+ model.a = _kernel("RDNAHybridW4A16LinearKernel")
+ with mock.patch.object(torch.version, "hip", "7.2.53211"):
+ assert _check_w4a16_kernels(model, bf16) is True
+ for other in ("RDNA3W4A16LinearKernel", "TritonW4A16LinearKernel", "MarlinLinearKernel"):
+ model.b = _kernel(other)
+ with pytest.raises(RuntimeError, match=rf"\['{other}'\] for 1 linear layers.*AMD"):
+ _check_w4a16_kernels(model, bf16)
+ with mock.patch.object(torch.version, "hip", None):
+ model.b = _kernel("RDNAHybridW4A16LinearKernel")
+ with pytest.raises(RuntimeError, match="only with MarlinLinearKernel"):
+ _check_w4a16_kernels(model, bf16)
+
+
+# ── The probe, with stand-in kernels on the CPU ──────────────────────────────────────────
+
+
+def _layer(out_features, in_features, generator):
+ signs = torch.randint(-1, 2, (out_features, in_features), generator=generator,
+ dtype=torch.int8)
+ scale = (torch.rand(out_features, in_features // GROUP_SIZE, generator=generator) * 0.05
+ + 0.01).to(torch.bfloat16)
+ return pack_int4(signs), scale
+
+
+def _model(compute, generator):
+ """Two probed layers whose kernels compute y = compute(x, w) with w the exact weight."""
+ model, references = torch.nn.Module(), {}
+ modules = {}
+ for layer, in_features in zip(rocm.PROBE_LAYERS, (2048, 6144)):
+ packed, scale = _layer(64, in_features, generator)
+ references[f"{layer}.weight_packed"], references[f"{layer}.weight_scale"] = packed, scale
+ weight = rocm.dequantize(packed, scale)
+ module = torch.nn.Module()
+ module.register_parameter("w", torch.nn.Parameter(torch.zeros(1), requires_grad=False))
+ kernel = object.__new__(type("RDNAHybridW4A16LinearKernel", (), {}))
+ kernel.config = SimpleNamespace(act_type=torch.bfloat16)
+ module.scheme = SimpleNamespace(kernel=kernel,
+ apply_weights=lambda _, x, bias, w=weight: compute(x, w))
+ modules[layer] = module
+ model.named_modules = lambda *args, **kwargs: iter(modules.items())
+ return model, references
+
+
+def _float32(x, w):
+ return (x.float() @ w.T).to(x.dtype)
+
+
+def _bfloat16_split_k(x, w, shuffle=False):
+ """Like vLLM's RDNA3 kernel: float32 sums over 256-wide slices, added into bfloat16
+ (with `shuffle`, in a different order on every call, as atomic adds can be)."""
+ out = torch.zeros(x.shape[0], w.shape[0], dtype=x.dtype)
+ starts = list(range(0, x.shape[1], 256))
+ if shuffle:
+ starts = [starts[i] for i in torch.randperm(len(starts))]
+ for start in starts:
+ part = x[:, start:start + 256].float() @ w[:, start:start + 256].T
+ out = (out.float() + part).to(x.dtype)
+ return out
+
+
+def test_probe_passes_a_float32_kernel_with_the_exact_weights():
+ model, references = _model(_float32, torch.Generator().manual_seed(1))
+ report = rocm.probe_w4a16(model, references, torch.bfloat16)
+ assert set(report) == set(rocm.PROBE_LAYERS)
+ assert all(r["worst_error_vs_allowed"] <= 1 for r in report.values())
+
+
[email protected]("compute, message", [
+ (_bfloat16_split_k, "does not sum in float32"),
+ # Codes read in the wrong nibble order.
+ (lambda x, w: _float32(x, w.reshape(w.shape[0], -1, 8).flip(-1).reshape(w.shape)),
+ "does not reproduce the 4-bit weights"),
+ # Activations rounded to 8 bits (W4A8-like).
+ (lambda x, w: _float32(x.float().to(torch.float8_e4m3fn).to(x.dtype), w),
+ "does not reproduce the 4-bit weights"),
+ # A different summation order on every call.
+ (lambda x, w: _bfloat16_split_k(x, w, shuffle=True), "different results for the same input"),
+])
+def test_probe_refuses_kernels_that_change_the_result(compute, message):
+ model, references = _model(compute, torch.Generator().manual_seed(2))
+ with pytest.raises(RuntimeError, match=message) as refused:
+ rocm.probe_w4a16(model, references, torch.bfloat16)
+ # Advice that also works when small-GPU fitting chose 4-bit by itself.
+ assert "vllm_options={'quantization': None}" in str(refused.value)
+
+
+def test_references_keep_only_the_probed_tensors_and_pass_everything_through():
+ tensors = [(f"{layer}.{part}", torch.ones(2)) for layer in rocm.PROBE_LAYERS
+ for part in ("weight_packed", "weight_scale", "weight_shape")]
+ tensors.append(("model.layers.1.mlp.down_proj.weight_packed", torch.ones(2)))
+ references = {}
+ assert [n for n, _ in rocm.keep_references(iter(tensors), references)] == [n for n, _ in tensors]
+ assert sorted(references) == sorted(f"{layer}.{part}" for layer in rocm.PROBE_LAYERS
+ for part in ("weight_packed", "weight_scale"))
+
+
+def test_decoder_convolutions_bypass_miopen_only_on_amd():
+ from kittenml.kittentts2.vocoder import _convolutions
+
+ before = torch.backends.cudnn.enabled
+ with mock.patch.object(torch.version, "hip", None):
+ with _convolutions():
+ assert torch.backends.cudnn.enabled == before
+ with mock.patch.object(torch.version, "hip", "7.2.53211"):
+ with _convolutions():
+ assert torch.backends.cudnn.enabled is False
+ assert torch.backends.cudnn.enabled == before
+
+
+def test_vocoder_source_mix_avoids_the_gemm_only_on_amd_gpus():
+ from kittenml.kittentts2.vocoder import _SmallLinear, _mix_source_without_blas
+
+ def s3gen():
+ torch.manual_seed(0)
+ source = SimpleNamespace(l_linear=torch.nn.Linear(9, 1))
+ return SimpleNamespace(mel2wav=SimpleNamespace(m_source=source))
+
+ for hip, device in ((None, "cuda"), ("7.2.53211", "cpu")):
+ model = s3gen()
+ linear = model.mel2wav.m_source.l_linear
+ with mock.patch.object(torch.version, "hip", hip):
+ _mix_source_without_blas(model, device)
+ assert model.mel2wav.m_source.l_linear is linear # NVIDIA and CPU: unchanged
+ model = s3gen()
+ linear = model.mel2wav.m_source.l_linear
+ with mock.patch.object(torch.version, "hip", "7.2.53211"):
+ _mix_source_without_blas(model, "cuda")
+ mix = model.mel2wav.m_source.l_linear
+ assert isinstance(mix, _SmallLinear)
+ # Same parameters (same state dict keys and tensors), same result as the linear layer.
+ assert [name for name, _ in mix.named_parameters()] == ["weight", "bias"]
+ assert mix.weight is linear.weight and mix.bias is linear.bias
+ x = torch.randn(1, 4096, 9, dtype=torch.float64)
+ with torch.no_grad():
+ expected = torch.nn.functional.linear(x, linear.weight.double(), linear.bias.double())
+ mix.double()
+ torch.testing.assert_close(mix(x), expected, rtol=0, atol=1e-12)
+
+
+def test_auto_fit_chooses_4bit_on_radeon_rx_7000_and_9000_only():
+ from kittenml.kittentts2.vllm.backend import VLLMBackend
+
+ gib = 1 << 30
+ lm = SimpleNamespace(hidden_size=2048, num_hidden_layers=28, num_attention_heads=16,
+ num_key_value_heads=8, head_dim=128, intermediate_size=6144,
+ vocab_size=158241, tie_word_embeddings=True)
+ # gfx1250 is a gfx12 name, but vLLM treats it as a data-center GPU and its RDNA kernel refuses it.
+ for arch, expected in (("gfx1100", "w4a16"), ("gfx1201", "w4a16"), ("gfx942", None),
+ ("gfx1250", None)):
+ with mock.patch.object(torch.version, "hip", "7.2.53211"), \
+ mock.patch("torch.cuda.get_device_properties",
+ return_value=SimpleNamespace(gcnArchName=f"{arch}:sramecc-:xnack-")), \
+ mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(int(7.39 * gib), int(7.62 * gib))):
+ fitted, report = VLLMBackend._fit({}, lm)
+ assert report["fitted"] and fitted.get("quantization") == expected, arch
+
+
[email protected]("compute, passes", [(_float32, True), (_bfloat16_split_k, False)])
+def test_loader_keeps_the_probed_weights_and_checks_the_kernel_after_loading(compute, passes):
+ # The wiring between load_weights (keeps CPU copies of the probed layers' 4-bit tensors)
+ # and load_model (runs the probe on the repacked layers, then drops the copies).
+ pytest.importorskip("vllm")
+ from vllm.model_executor.model_loader.base_loader import BaseModelLoader
+ from kittenml.kittentts2.vllm.loader import KittenModelLoader
+
+ model, references = _model(compute, torch.Generator().manual_seed(3))
+ weights = list(references.items()) + [("model.norm.weight", torch.ones(4))]
+ def load_weights(tensors):
+ for _ in tensors:
+ pass
+ return set(dict(model.named_parameters()))
+ model.load_weights = load_weights
+ loader = object.__new__(KittenModelLoader)
+ loader.load_config = SimpleNamespace(model_loader_extra_config={
+ "repo_dir": "unused", "config": {}, "weights": "packed", "quantization": "w4a16"})
+ bf16 = SimpleNamespace(dtype=torch.bfloat16)
+
+ def base_load_model(self, vllm_config, model_config, prefix=""):
+ self.load_weights(model, model_config)
+ return model
+
+ probe = mock.Mock(wraps=rocm.probe_w4a16)
+ with mock.patch.object(torch.version, "hip", "7.2.53211"), \
+ mock.patch.object(BaseModelLoader, "load_model", base_load_model), \
+ mock.patch("kittenml.kittentts2.vllm.w4a16.iter_w4a16", return_value=iter(weights)), \
+ mock.patch.object(rocm, "probe_w4a16", probe):
+ if passes:
+ assert loader.load_model(None, bf16) is model
+ else:
+ with pytest.raises(RuntimeError, match="does not sum in float32"):
+ loader.load_model(None, bf16)
+ probe.assert_called_once()
+ seen = probe.call_args.args[1]
+ assert sorted(seen) == sorted(references)
+ assert all(torch.equal(seen[name], references[name]) for name in references)
+ assert loader._probe_references is None
+
+
+def test_auto_fit_does_not_choose_4bit_on_amd_when_the_environment_refuses_it(monkeypatch):
+ from kittenml.kittentts2.vllm.backend import VLLMBackend
+
+ gib = 1 << 30
+ lm = SimpleNamespace(hidden_size=2048, num_hidden_layers=28, num_attention_heads=16,
+ num_key_value_heads=8, head_dim=128, intermediate_size=6144,
+ vocab_size=158241, tie_word_embeddings=True)
+ monkeypatch.setenv("VLLM_DISABLED_KERNELS", "RDNAHybridW4A16LinearKernel")
+ with mock.patch.object(torch.version, "hip", "7.2.53211"), \
+ mock.patch("torch.cuda.get_device_properties",
+ return_value=SimpleNamespace(gcnArchName="gfx1201")), \
+ mock.patch("kittenml.kittentts2.vllm.backend._free_gpu_memory",
+ return_value=(int(7.39 * gib), int(7.62 * gib))):
+ fitted, report = VLLMBackend._fit({}, lm)
+ assert report["fitted"] and "quantization" not in fitted