Skip to content

AirLLM 2.8T LLM inference with single 4GB GPU

fix: make Kimi K3 actually generate end to end

Yu Li6d9c840f49a9
diff --git a/air_llm/airllm/airllm_base.py b/air_llm/airllm/airllm_base.py
index a3a1f73..119de79 100644
--- a/air_llm/airllm/airllm_base.py
+++ b/air_llm/airllm/airllm_base.py
@@ -14,8 +14,9 @@ from transformers.quantizers import AutoHfQuantizer
from .profiler import LayeredProfiler
-from .utils import clean_memory, load_layer, \
+from .utils import clean_memory, load_layer, layer_tensor_names, load_layer_subset, \
find_or_create_local_splitted_path
+from .persist import ModelPersister
try:
import bitsandbytes as bnb
@@ -26,6 +27,32 @@ except ImportError:
bitsandbytes_installed = False
+# Helpers that transformers 5.0 moved out of transformers.utils.generic. Remote model code is
+# routinely written against an older transformers and still imports them from the old location,
+# which makes such models fail to import at all. Re-exporting is enough to load them.
+_RELOCATED_TRANSFORMERS_SYMBOLS = {
+ 'OutputRecorder': 'transformers.utils.output_capturing',
+ 'check_model_inputs': 'transformers.utils.output_capturing',
+}
+
+
+def restore_relocated_transformers_symbols():
+ """Re-export moved transformers helpers under their old names, where they are missing."""
+ import importlib
+ import transformers.utils.generic as generic
+
+ for name, new_home in _RELOCATED_TRANSFORMERS_SYMBOLS.items():
+ if hasattr(generic, name):
+ continue
+ try:
+ module = importlib.import_module(new_home)
+ except ImportError:
+ continue
+ symbol = getattr(module, name, None)
+ if symbol is not None:
+ setattr(generic, name, symbol)
+
+
class AirLLMBaseModel:
"""
Memory-frugal wrapper around a Hugging Face ``*ForCausalLM`` model.
@@ -97,6 +124,8 @@ class AirLLMBaseModel:
self.compression = compression
self.hf_token = hf_token
+ restore_relocated_transformers_symbols()
+
self.set_layer_names_dict()
self.model_local_path, self.checkpoint_path = find_or_create_local_splitted_path(
@@ -181,11 +210,32 @@ class AirLLMBaseModel:
# ---- model construction -----------------------------------------------------------------
+ def _propagate_attn_implementation(self, impl):
+ """Push the attention choice down into nested sub-configs.
+
+ Multimodal wrappers keep the real decoder under a sub-config -- Kimi K3 uses ``text_config``
+ -- and transformers records the request only on the config it was handed. The sub-model then
+ reads an unset value and falls through to a flash-attention path, which fails outright on a
+ machine without flash-attn installed.
+ """
+ from transformers import PretrainedConfig
+
+ def walk(cfg, depth=0):
+ if depth > 2:
+ return
+ for sub in vars(cfg).values():
+ if isinstance(sub, PretrainedConfig):
+ sub._attn_implementation = impl
+ walk(sub, depth + 1)
+
+ walk(self.config)
+
def init_model(self):
# Build the real model on meta (no memory). include_buffers=False so non-persistent
# buffers such as rotary inv_freq are actually computed (they aren't in the checkpoint).
self.model = None
try:
+ self._propagate_attn_implementation("sdpa")
with init_empty_weights(include_buffers=False):
self.model = AutoModelForCausalLM.from_config(
self.config, attn_implementation="sdpa", trust_remote_code=self.trust_remote_code)
@@ -195,15 +245,27 @@ class AirLLMBaseModel:
if self.model is None:
# Some (often remote-code) architectures don't support sdpa and also default to it, so we
# must request eager explicitly; otherwise transformers re-selects sdpa and errors again.
+ self._propagate_attn_implementation("eager")
with init_empty_weights(include_buffers=False):
self.model = AutoModelForCausalLM.from_config(
self.config, attn_implementation="eager", trust_remote_code=self.trust_remote_code)
quantization_config = getattr(self.config, "quantization_config", None)
+ if quantization_config is None:
+ # Nested multimodal configs (Kimi K3) keep it under text_config.
+ quantization_config = getattr(getattr(self.config, "text_config", None),
+ "quantization_config", None)
if quantization_config is not None:
self.hf_quantizer = AutoHfQuantizer.from_config(quantization_config, pre_quantized=True)
device_map = self.hf_quantizer.update_device_map(None)
self.hf_quantizer.preprocess_model(model=self.model, device_map=device_map)
+ # compressed-tensors registers a hook that expands every packed module on the first
+ # forward. That undoes per-expert streaming (a K3 layer becomes ~56GB) and is also
+ # unnecessary: we decompress each expert ourselves as it loads. Remove the hook.
+ hook = getattr(self.model, "ct_decompress_hook", None)
+ if hook is not None:
+ hook.remove()
+ delattr(self.model, "ct_decompress_hook")
self.model.eval()
self.model.tie_weights()
@@ -301,7 +363,149 @@ class AirLLMBaseModel:
return state_dict
+ def _restore_plain_weight_modules(self, state_dict):
+ """Undo CT's packed-parameter layout when the checkpoint still ships a plain ``weight``.
+
+ Some checkpoints (Kimi K3) list residual/router Linears under the MXFP4 target list but
+ store them as bf16. After ``preprocess_model`` those modules expose ``weight_packed`` and
+ reject the real ``weight`` tensor. Restore a meta ``weight`` Parameter so the shard can load.
+ """
+ plain = {k[:-len('.weight')] for k in state_dict if k.endswith('.weight')}
+ packed = {k[:-len('.weight_packed')] for k in state_dict if k.endswith('.weight_packed')}
+ for prefix in plain - packed:
+ try:
+ module = self.model.get_submodule(prefix)
+ except AttributeError:
+ continue
+ names = list(module._parameters.keys())
+ if 'weight' in names or 'weight_packed' not in names:
+ continue
+ weight = state_dict[f'{prefix}.weight']
+ for name in names:
+ if name == 'weight' or name.startswith('weight_'):
+ module._parameters.pop(name, None)
+ module.register_parameter(
+ 'weight',
+ torch.nn.Parameter(torch.empty(weight.shape, device='meta', dtype=weight.dtype),
+ requires_grad=False),
+ )
+ for attr in ('quantization_scheme', 'quantization_status', 'quantization_format'):
+ if hasattr(module, attr):
+ delattr(module, attr)
+
+ def _decompress_state_dict(self, state_dict):
+ """Expand packed payloads into the plain weights the modules expect.
+
+ compressed-tensors has no quantized compute kernels: it registers a hook that decompresses
+ the whole model before the first forward, after which every quantized module wants a plain
+ ``weight``. Our shards still hold ``weight_packed``/``weight_scale``, so we expand them here.
+
+ The expansion happens on the GPU, after transferring the *packed* bytes. For MXFP4 that
+ moves 4x less data across PCIe than transferring an already-expanded weight would.
+ """
+ if self.hf_quantizer is None:
+ return state_dict
+
+ packed_prefixes = {k[: -len('.weight_packed')]
+ for k in state_dict if k.endswith('.weight_packed')}
+ if not packed_prefixes:
+ return state_dict
+
+ from compressed_tensors.compressors.base import BaseCompressor
+ try:
+ from compressed_tensors.linear.compressed_linear import CompressedLinear
+ except ImportError:
+ CompressedLinear = None
+
+ out = dict(state_dict)
+ for prefix in packed_prefixes:
+ try:
+ module = self.model.get_submodule(prefix)
+ except AttributeError:
+ continue
+ # CompressedLinear's own forward consumes the packed payload, so leave it packed.
+ if CompressedLinear is not None and isinstance(module, CompressedLinear):
+ continue
+ scheme = getattr(module, 'quantization_scheme', None)
+ if scheme is None or getattr(scheme, 'format', None) is None:
+ continue
+
+ local = {k[len(prefix) + 1:]: v.to(self.running_device)
+ for k, v in state_dict.items() if k.startswith(prefix + '.')}
+ # scheme.format is an enum on some compressed-tensors versions and a plain str on others.
+ fmt = getattr(scheme.format, 'value', scheme.format)
+ compressor = BaseCompressor.get_value_from_registry(fmt)
+ decompressed = compressor.decompress(local, scheme)
+
+ for k in local:
+ out.pop(f'{prefix}.{k}', None)
+ if 'weight' in decompressed:
+ # Once expanded, the module reads only `weight`; the scales that came back merely
+ # describe how the checkpoint stored it, and keeping them would waste VRAM.
+ out[f'{prefix}.weight'] = decompressed['weight']
+ self._expose_plain_weight(module, decompressed['weight'])
+ else:
+ for k, v in decompressed.items():
+ out[f'{prefix}.{k}'] = v
+ return out
+
+ def _expose_plain_weight(self, module, weight):
+ """Swap a module's packed parameters for the plain ``weight`` its forward reads.
+
+ compressed-tensors patches a ``quantized_forward`` onto quantized Linears that reads
+ ``self.weight``; the packed parameters only describe how the checkpoint stores the value.
+ Marking the module COMPRESSED tells that forward the weight is already on the quantization
+ grid, so it skips a fake-quantize that would only reproduce what we just decompressed.
+ """
+ existing = module._parameters.get('weight')
+ if existing is None or existing.shape != weight.shape:
+ for name in [n for n in list(module._parameters) if n.startswith('weight')]:
+ module._parameters.pop(name, None)
+ module.register_parameter(
+ 'weight',
+ torch.nn.Parameter(torch.empty(weight.shape, device='meta', dtype=weight.dtype),
+ requires_grad=False),
+ )
+ try:
+ from compressed_tensors.quantization import QuantizationStatus
+ except ImportError:
+ return
+ module.quantization_status = QuantizationStatus.COMPRESSED
+
+ def _adopt_checkpoint_shape(self, param_name, value):
+ """Resize a meta placeholder whose shape disagrees with the checkpoint.
+
+ A model class builds its parameters from the config, and that construction can disagree
+ with the weights actually shipped. Kimi K3 sizes ``A_log`` from ``num_heads`` while its
+ checkpoint stores one entry per head channel, which would abort the load. For a parameter
+ still on meta -- i.e. one we have never materialised -- the checkpoint is the source of
+ truth, so adopt its shape.
+ """
+ module_path, _, attr = param_name.rpartition('.')
+ try:
+ module = self.model.get_submodule(module_path) if module_path else self.model
+ except AttributeError:
+ return
+ current = module._parameters.get(attr)
+ if current is None or current.device.type != 'meta' or current.shape == value.shape:
+ return
+
+ if not hasattr(self, '_shape_adoption_warned'):
+ self._shape_adoption_warned = set()
+ if attr not in self._shape_adoption_warned:
+ self._shape_adoption_warned.add(attr)
+ print(f"{attr}: checkpoint ships {tuple(value.shape)} but the model class builds "
+ f"{tuple(current.shape)}; using the checkpoint shape.")
+
+ module.register_parameter(
+ attr,
+ torch.nn.Parameter(torch.empty(value.shape, device='meta', dtype=current.dtype),
+ requires_grad=False),
+ )
+
def move_layer_to_device(self, state_dict):
+ self._restore_plain_weight_modules(state_dict)
+ state_dict = self._decompress_state_dict(state_dict)
moved = []
for param_name in self._param_names_from_state_dict(state_dict):
if self.hf_quantizer is not None and self._needs_quantization(param_name):
@@ -313,6 +517,7 @@ class AirLLMBaseModel:
# Normal load. Only ordinary high-precision tensors get cast to the runtime dtype;
# pre-quantized payloads must be placed verbatim (see _should_load_verbatim).
value = state_dict[param_name]
+ self._adopt_checkpoint_shape(param_name, value)
if self._should_load_verbatim(param_name, value):
set_module_tensor_to_device(self.model, param_name, self.running_device, value=value)
else:
@@ -400,16 +605,117 @@ class AirLLMBaseModel:
self._streamed_set = set(self._streamed_indices)
+ self._setup_expert_streaming()
+
for idx in self._streamed_indices:
module = self.layers[idx]
module._airllm_idx = idx
module.register_forward_pre_hook(self._pre_hook)
module.register_forward_hook(self._post_hook)
+ # ---- per-expert streaming ---------------------------------------------------------------
+
+ def _setup_expert_streaming(self):
+ """Stream individual MoE experts instead of whole decoder layers, where that is possible.
+
+ A sparse MoE layer holds hundreds of experts but routes each token to a handful of them.
+ Materialising the whole layer is therefore enormously wasteful: for Kimi K3 a layer's
+ experts are ~55GB expanded, of which a token touches ~1GB. Because the model calls each
+ selected expert as its own module (and skips unselected ones), a forward hook per expert
+ loads exactly the experts that actually run.
+
+ This needs `expert_prefix` in layer_names_dict and safetensors shards, since it relies on
+ reading individual tensors out of a shard.
+ """
+ self._expert_streaming = False
+ self._expert_keys = {}
+ self._non_expert_keys = {}
+
+ expert_prefix = self.layer_names_dict.get('expert_prefix')
+ if not expert_prefix:
+ return
+ if type(ModelPersister.get_model_persister()).__name__ != 'SafetensorModelPersister':
+ return
+
+ layer_prefix = self.layer_names_dict['layer_prefix']
+ hooked = 0
+
+ for idx in self._streamed_indices:
+ layer_name = self.layer_names[idx]
+ if not layer_name.startswith(layer_prefix + '.'):
+ continue
+ try:
+ names = layer_tensor_names(self.checkpoint_path, layer_name)
+ except Exception:
+ continue
+
+ marker = f'.{expert_prefix}.'
+ per_expert = {}
+ others = []
+ for key in names:
+ pos = key.find(marker)
+ if pos == -1:
+ others.append(key)
+ continue
+ rest = key[pos + len(marker):]
+ head = rest.split('.', 1)[0]
+ if not head.isdigit():
+ others.append(key)
+ continue
+ per_expert.setdefault(int(head), []).append(key)
+
+ if not per_expert:
+ continue
+
+ layer_module = self.layers[idx]
+ experts_container = layer_module
+ try:
+ for attr in expert_prefix.split('.'):
+ experts_container = getattr(experts_container, attr)
+ except AttributeError:
+ continue
+
+ self._non_expert_keys[idx] = others
+ self._expert_keys[idx] = per_expert
+
+ for expert_idx, keys in per_expert.items():
+ if expert_idx >= len(experts_container):
+ continue
+ expert_module = experts_container[expert_idx]
+ expert_module._airllm_expert = (idx, expert_idx)
+ expert_module.register_forward_pre_hook(self._expert_pre_hook)
+ expert_module.register_forward_hook(self._expert_post_hook)
+ hooked += 1
+
+ if hooked:
+ self._expert_streaming = True
+ n_layers = len(self._expert_keys)
+ print(f"per-expert streaming enabled: {hooked} experts across {n_layers} layers "
+ f"load on demand, so only the experts a token routes to are materialised.")
+
+ def _expert_pre_hook(self, module, args):
+ layer_idx, expert_idx = module._airllm_expert
+ keys = self._expert_keys[layer_idx][expert_idx]
+ state_dict = load_layer_subset(self.checkpoint_path, self.layer_names[layer_idx], keys)
+ module._airllm_moved = self.move_layer_to_device(state_dict)
+
+ def _expert_post_hook(self, module, args, output):
+ for param_name in getattr(module, '_airllm_moved', []):
+ set_module_tensor_to_device(self.model, param_name, 'meta')
+ module._airllm_moved = []
+ return output
+
def _next_streamed_idx(self, idx):
nxt = idx + 1
return nxt if nxt in self._streamed_set else None
+ def _load_streamed_layer(self, idx):
+ """Load one streamed module's weights. Experts are excluded when they stream themselves."""
+ keys = self._non_expert_keys.get(idx) if getattr(self, '_expert_streaming', False) else None
+ if keys is None:
+ return self.load_layer_to_cpu(self.layer_names[idx])
+ return load_layer_subset(self.checkpoint_path, self.layer_names[idx], keys)
+
def _pre_hook(self, module, args):
idx = module._airllm_idx
@@ -417,18 +723,20 @@ class AirLLMBaseModel:
state_dict = self._prefetch_future.result()
self._prefetch_future = None
else:
- state_dict = self.load_layer_to_cpu(self.layer_names[idx])
+ state_dict = self._load_streamed_layer(idx)
module._airllm_moved = self.move_layer_to_device(state_dict)
if self.prefetching:
nxt = self._next_streamed_idx(idx)
if nxt is not None:
- self._prefetch_future = self._executor.submit(self.load_layer_to_cpu, self.layer_names[nxt])
+ self._prefetch_future = self._executor.submit(self._load_streamed_layer, nxt)
self._prefetched_idx = nxt
def _post_hook(self, module, args, output):
- if self.hf_quantizer is not None:
+ # module.to('meta') would also evict the experts, which manage their own lifetime, so with
+ # expert streaming we only release exactly what this hook placed.
+ if self.hf_quantizer is not None or getattr(self, '_expert_streaming', False):
for param_name in getattr(module, '_airllm_moved', []):
set_module_tensor_to_device(self.model, param_name, 'meta')
else:
diff --git a/air_llm/airllm/airllm_kimi_k3.py b/air_llm/airllm/airllm_kimi_k3.py
index 3732f6f..0406496 100644
--- a/air_llm/airllm/airllm_kimi_k3.py
+++ b/air_llm/airllm/airllm_kimi_k3.py
@@ -9,6 +9,10 @@ class AirLLMKimiK3(AirLLMBaseModel):
It also adds a pair of top-level Attention Residual modules that sit outside the normal
embed -> layers -> norm -> lm_head sequence. Everything else (MXFP4 weights, per-layer
streaming) is handled by the generic base class.
+
+ Each layer holds 896 experts and routes a token to 16 of them, so the experts are streamed
+ individually rather than by layer: expanded, a layer's experts are ~55GB but a token needs
+ ~1GB of them.
"""
def set_layer_names_dict(self):
@@ -17,6 +21,7 @@ class AirLLMKimiK3(AirLLMBaseModel):
'layer_prefix': 'language_model.model.layers',
'norm': 'language_model.model.norm',
'lm_head': 'language_model.lm_head',
+ 'expert_prefix': 'block_sparse_moe.experts',
# Not streamed: loaded once and kept resident. Together these are well under 1GB.
'resident': [
'language_model.model.output_attn_res_norm',
diff --git a/air_llm/airllm/utils.py b/air_llm/airllm/utils.py
index af7153d..ad45f99 100644
--- a/air_llm/airllm/utils.py
+++ b/air_llm/airllm/utils.py
@@ -20,6 +20,7 @@ if platform == "darwin":
import torch
import torch.nn as nn
+from safetensors import safe_open
from safetensors.torch import load_file, save_file
from .persist import ModelPersister
@@ -112,6 +113,25 @@ def uncompress_layer_state_dict(layer_state_dict):
return layer_state_dict if uncompressed_layer_state_dict is None else uncompressed_layer_state_dict
+def layer_tensor_names(local_path, layer_name):
+ """List the tensors in a layer shard without reading any tensor data."""
+ with safe_open(str(Path(local_path) / (layer_name + ".safetensors")), framework="pt") as f:
+ return list(f.keys())
+
+
+def load_layer_subset(local_path, layer_name, keys):
+ """Read only `keys` from a layer shard.
+
+ safetensors can seek to individual tensors, so a single MoE expert costs its own few MB rather
+ than the whole ~16GB layer file. That is what makes per-expert streaming worthwhile.
+ """
+ out = {}
+ with safe_open(str(Path(local_path) / (layer_name + ".safetensors")), framework="pt") as f:
+ for k in keys:
+ out[k] = f.get_tensor(k)
+ return out
+
+
def load_layer(local_path, layer_name, profiling=False):
#layer_state_dict = load_file(Path(local_path) / (layer_name + ".safetensors"), device="cpu")
layer_state_dict = ModelPersister.get_model_persister().load_model(layer_name, local_path)