Skip to content

AirLLM 2.8T LLM inference with single 4GB GPU

feat: streamed LoRA training for Qwen3.8 on 6GB (4.0.0)

Yu Lid7716a37ae7d
diff --git a/README.md b/README.md
index fbf5597..0ca91e9 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[**Example notebooks**](#example-python-notebook) |
[**FAQ**](#faq)
-**AirLLM** dramatically reduces inference memory usage, letting 70B large language models run on a single 4GB GPU card — without quantization, distillation, or pruning. You can even run **405B Llama 3.1** on **8GB**, **DeepSeek-V3 (671B)** on **~12GB**, and **Kimi K3 (2.8T)** — the largest open-source model released to date — on **under 4GB**, because sparse MoE models stream one expert at a time rather than a whole layer.
+**AirLLM** dramatically reduces inference memory usage, letting 70B large language models run on a single 4GB GPU card — without quantization, distillation, or pruning. You can even run **Kimi K3 (2.8T)** — the largest open-source model released to date — on **under 4GB**, **Qwen3.8-Flash-Next (125B)** on **6GB**, and **DeepSeek-V3 (671B)** on **~12GB**. We now also support training huge models on small VRAM: Qwen3.8-Flash-Next under **6GB**.
<a href="https://github.com/lyogavin/airllm/stargazers">![GitHub Repo stars](https://img.shields.io/github/stars/lyogavin/airllm?style=social)</a>
[![Downloads](https://static.pepy.tech/personalized-badge/airllm?period=total&units=international_system&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/airllm)
@@ -29,6 +29,8 @@
* [Best AI Facial Expression Editor](https://crazyfaceai.com)
## Updates
+[2026/09] **Training** support: stream frozen weights one layer at a time and keep adapters on the GPU. **Qwen3.8-Flash-Next (125B)** trains under **6GB** (RTX 3060 Ti); **Qwen3.8-27B** trains in **~2GB** at seq 512. See [Training](#training).
+
[2026/08] **Qwen3.8-Flash-Next** support: Qwen's 125B MoE flagship (`Qwen4ExpForConditionalGeneration`) with a ~51B n-gram embedding runs in **5.95GB** of VRAM, measured end to end on one RTX 4090. The n-gram table is file-mapped on the host (a 64GB machine is enough); decoder layers stream. Needs a `transformers` build with in-tree `qwen4_exp` (`pip install git+https://github.com/huggingface/transformers.git` today) and ~360GB of checkpoint disk (`delete_original=True` reclaims the originals after the split).
[2026/08] **Qwen3.8-27B** support: Qwen's new dense VL (Gated DeltaNet + Gated Attention, native vision) runs in **3.33GB** of VRAM, measured end to end on one RTX 3090. Needs `transformers` 5.8+.
@@ -78,6 +80,7 @@
* [Run on MacOS](#macos)
* [Example notebooks](#example-python-notebook)
* [Supported Models](#supported-models)
+* [Training](#training)
* [Acknowledgement](#acknowledgement)
* [FAQ](#faq)
@@ -295,6 +298,50 @@ The trick: AirLLM only ever keeps **one layer on the GPU at a time**, so the VRA
Same one line of code for all of them — no special setup.
+## Training
+
+AirLLM can fine-tune huge models on a small GPU. Frozen base weights stream from disk one decoder layer at a time; only the adapters stay resident. **Qwen3.8-Flash-Next** trains under **6GB**; **Qwen3.8-27B** trains in **~2GB** at seq 512.
+
+This is not Hugging Face Trainer / bitsandbytes QLoRA. Flash-Next needs a `transformers` build with in-tree `qwen4_exp` (`pip install git+https://github.com/huggingface/transformers.git` today).
+
+```python
+from airllm import AirLLMLoRAQwen4Exp
+
+trainer = AirLLMLoRAQwen4Exp(
+ "Qwen/Qwen3.8-Flash-Next",
+ max_seq_len=512,
+ lora_r=16,
+ delete_original=True,
+)
+
+tok = trainer.tokenizer
+if tok.pad_token_id is None:
+ tok.pad_token = tok.eos_token
+
+encoded = tok(
+ "Your training text here.",
+ return_tensors="pt",
+ truncation=True,
+ max_length=512,
+)
+loss = trainer.train_step(
+ encoded["input_ids"].cuda(),
+ attention_mask=encoded.get("attention_mask"),
+)
+print(loss)
+trainer.save_adapter("qwen38-flash-next-lora.pt")
+```
+
+For the 27B dense model, use `AirLLMLoRA` instead:
+
+```python
+from airllm import AirLLMLoRA
+
+trainer = AirLLMLoRA("Qwen/Qwen3.8-27B", max_seq_len=512, lora_r=16)
+```
+
+CLI examples: `air_llm/examples/train_qwen38_flash_next_lora.py` and `air_llm/examples/train_qwen38_lora.py`.
+
## Acknowledgement
A lot of the code are based on SimJeg's great work in the Kaggle exam competition. Big shoutout to SimJeg:
diff --git a/air_llm/airllm/__init__.py b/air_llm/airllm/__init__.py
index 5ce56df..f2eef16 100644
--- a/air_llm/airllm/__init__.py
+++ b/air_llm/airllm/__init__.py
@@ -34,6 +34,8 @@ else:
("AirLLMKimiK3", ".airllm_kimi_k3"),
("AirLLMQwen3_5", ".airllm_qwen3_5"),
("AirLLMQwen4Exp", ".airllm_qwen4_exp"),
+ ("AirLLMLoRA", ".airllm_lora"),
+ ("AirLLMLoRAQwen4Exp", ".airllm_lora"),
):
try:
_mod = __import__(__name__ + _module, fromlist=[_name])
diff --git a/air_llm/airllm/airllm_base.py b/air_llm/airllm/airllm_base.py
index 8da7ab9..b05eed9 100644
--- a/air_llm/airllm/airllm_base.py
+++ b/air_llm/airllm/airllm_base.py
@@ -83,7 +83,8 @@ class AirLLMBaseModel:
def __init__(self, model_local_path_or_repo_id, device="cuda:0", dtype=None, max_seq_len=512,
layer_shards_saving_path=None, profiling_mode=False, compression=None,
- hf_token=None, prefetching=True, delete_original=False):
+ hf_token=None, prefetching=True, delete_original=False,
+ install_hooks=True, load_resident=True):
"""
Parameters
----------
@@ -109,6 +110,13 @@ class AirLLMBaseModel:
overlap the next layer's disk load with the current layer's compute
delete_original: bool, optional
delete the original downloaded checkpoint after splitting to save disk space
+ install_hooks: bool, optional
+ attach inference streaming hooks. Training drives load/evict itself, so LoRA
+ training passes False — the hooks call ``module.to('meta')`` after forward and
+ that breaks backward.
+ load_resident: bool, optional
+ load ``resident`` modules (e.g. a vision tower) onto the GPU. Text-only LoRA
+ training leaves them on meta.
"""
self.profiling_mode = profiling_mode
@@ -198,9 +206,11 @@ class AirLLMBaseModel:
self.max_seq_len = max_seq_len
self.set_layers_from_layer_names()
- self._load_resident_modules()
+ if load_resident:
+ self._load_resident_modules()
self._load_cpu_resident_modules()
- self._install_streaming_hooks()
+ if install_hooks:
+ self._install_streaming_hooks()
# ---- customization hooks for subclasses -------------------------------------------------
diff --git a/air_llm/airllm/airllm_lora.py b/air_llm/airllm/airllm_lora.py
new file mode 100644
index 0000000..ddc55d0
--- /dev/null
+++ b/air_llm/airllm/airllm_lora.py
@@ -0,0 +1,562 @@
+"""Layer-wise LoRA training with AirLLM disk offload.
+
+Hugging Face Trainer / PEFT keep a full autograd graph (or 4-bit weights of the
+whole 27B) on the GPU. This module instead:
+
+* reuses the per-layer shards already built for inference
+* gathers embed rows and lm_head rows from CPU
+* runs one decoder layer at a time, with frozen base weights streamed from disk
+* keeps LoRA A/B + Adam on the GPU
+* holds the autograd graph's hidden states on CPU so 64 layers do not occupy VRAM
+
+v1 is text-only Qwen3.5 / Qwen3.8. Vision stays on meta. Dropout is 0 so the
+backward recompute matches the forward.
+"""
+
+from accelerate.utils.modeling import set_module_tensor_to_device
+import torch
+import torch.nn.functional as F
+
+from .airllm_qwen3_5 import AirLLMQwen3_5
+from .airllm_qwen4_exp import AirLLMQwen4Exp
+from .chunked_ce import chunked_linear_cross_entropy
+from .lora_linear import (
+ DEFAULT_LORA_TARGETS,
+ FLASH_NEXT_LORA_TARGETS,
+ inject_lora,
+ inject_packed_expert_lora,
+ load_lora_state_dict,
+ lora_parameters,
+ lora_state_dict,
+)
+from .utils import clean_memory
+
+
+class _StreamedModule(torch.autograd.Function):
+ """One module's forward under no_grad; recompute with grad in backward.
+
+ Inputs and outputs of ``apply`` are CPU tensors so the 64-layer graph does
+ not pin 64 hidden states on the GPU. LoRA grads are written on the inner
+ ``out.backward(g)`` and are *not* Function outputs.
+ """
+
+ trainer = None
+ kind = None
+ extras = None
+
+ @staticmethod
+ def forward(ctx, hidden):
+ trainer = _StreamedModule.trainer
+ kind = _StreamedModule.kind
+ extras = _StreamedModule.extras
+ ctx.trainer = trainer
+ ctx.kind = kind
+ ctx.extras = extras
+ h_cpu = hidden.detach().cpu() if hidden.device.type != "cpu" else hidden.detach()
+ with torch.no_grad():
+ out = trainer._run_streamed(kind, h_cpu, extras, grad=False)
+ ctx.save_for_backward(h_cpu)
+ return out
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ trainer = ctx.trainer
+ h = ctx.saved_tensors[0].to(trainer.device).detach().requires_grad_(True)
+ g = grad_output.to(device=trainer.device, dtype=h.dtype)
+ out = trainer._run_streamed(ctx.kind, h, ctx.extras, grad=True)
+ if not torch.is_tensor(out):
+ out = out[0]
+ try:
+ out.backward(g)
+ finally:
+ stream_idx = trainer._stream_idx_for_kind(ctx.kind)
+ trainer._evict(stream_idx)
+ trainer._prefetch_stream(stream_idx - 1)
+ grad_hidden = h.grad if h.grad is not None else torch.zeros_like(h)
+ return grad_hidden.cpu()
+
+
+class AirLLMLoRA(AirLLMQwen3_5):
+ """Streamed LoRA trainer for Qwen3.5 / Qwen3.8 dense VL (text-only)."""
+
+ def set_layer_names_dict(self):
+ super().set_layer_names_dict()
+ self.layer_names_dict["resident"] = []
+ self.layer_names_dict["cpu_resident"] = [
+ self.layer_names_dict["embed"],
+ self.layer_names_dict["lm_head"],
+ ]
+
+ def __init__(
+ self,
+ model_local_path_or_repo_id,
+ device="cuda:0",
+ dtype=None,
+ max_seq_len=512,
+ layer_shards_saving_path=None,
+ profiling_mode=False,
+ compression=None,
+ hf_token=None,
+ prefetching=True,
+ delete_original=False,
+ lora_r=16,
+ lora_alpha=32,
+ lora_dropout=0.0,
+ target_modules=None,
+ lr=1e-4,
+ ce_chunk_size=4096,
+ weight_decay=0.0,
+ ):
+ super().__init__(
+ model_local_path_or_repo_id,
+ device=device,
+ dtype=dtype,
+ max_seq_len=max_seq_len,
+ layer_shards_saving_path=layer_shards_saving_path,
+ profiling_mode=profiling_mode,
+ compression=compression,
+ hf_token=hf_token,
+ prefetching=prefetching,
+ delete_original=delete_original,
+ install_hooks=False,
+ load_resident=False,
+ )
+ self.lora_r = lora_r
+ self.lora_alpha = lora_alpha
+ self.ce_chunk_size = ce_chunk_size
+ self.target_modules = tuple(target_modules or DEFAULT_LORA_TARGETS)
+
+ self.model.config.use_cache = False
+ text_cfg = getattr(self.config, "text_config", None)
+ if text_cfg is not None:
+ text_cfg.use_cache = False
+ if hasattr(self.model, "gradient_checkpointing_disable"):
+ self.model.gradient_checkpointing_disable()
+ self.model.eval()
+
+ self._finish_lora_setup(
+ lora_r, lora_alpha, lora_dropout, lr, weight_decay, packed_experts=False)
+
+ def _finish_lora_setup(self, lora_r, lora_alpha, lora_dropout, lr, weight_decay,
+ packed_experts=False):
+ n = inject_lora(
+ self._decoder_container(),
+ target_modules=self.target_modules,
+ r=lora_r,
+ alpha=lora_alpha,
+ dropout=lora_dropout,
+ device=self.device,
+ dtype=self.running_dtype,
+ )
+ n_exp = 0
+ if packed_experts:
+ n_exp = inject_packed_expert_lora(
+ self._decoder_container(),
+ r=lora_r,
+ alpha=lora_alpha,
+ device=self.device,
+ dtype=self.running_dtype,
+ )
+ for name, param in self.model.named_parameters():
+ if "lora_" in name:
+ param.requires_grad_(True)
+ else:
+ param.requires_grad_(False)
+
+ trainable = lora_parameters(self.model)
+ n_params = sum(p.numel() for p in trainable)
+ extra = f", packed-expert modules {n_exp}" if packed_experts else ""
+ print(
+ f"AirLLM LoRA: wrapped {n} linears{extra}, rank {lora_r}, "
+ f"{n_params / 1e6:.1f}M trainable params "
+ f"({sum(p.numel() * p.element_size() for p in trainable) / 1e6:.0f}MB)"
+ )
+ self.optimizer = torch.optim.AdamW(trainable, lr=lr, weight_decay=weight_decay)
+
+ def _module(self, dotted):
+ mod = self.model
+ for attr in dotted.split("."):
+ mod = getattr(mod, attr)
+ return mod
+
+ def _decoder_container(self):
+ return self._module(self.layer_names_dict["layer_prefix"])
+
+ def _text_model(self):
+ embed_path = self.layer_names_dict["embed"]
+ return self._module(embed_path.rsplit(".", 1)[0])
+
+ def _n_decoder_layers(self):
+ return len(self.layers) - 3
+
+ def _materialize(self, stream_idx):
+ if self.prefetching and self._prefetch_future is not None and self._prefetched_idx == stream_idx:
+ state = self._prefetch_future.result()
+ self._prefetch_future = None
+ self._prefetched_idx = None
+ else:
+ if self._prefetch_future is not None:
+ self._prefetch_future.result()
+ self._prefetch_future = None
+ state = self.load_layer_to_cpu(self.layer_names[stream_idx])
+ module = self.layers[stream_idx]
+ module._airllm_moved = self.move_layer_to_device(state)
+
+ def _evict(self, stream_idx):
+ module = self.layers[stream_idx]
+ for param_name in getattr(module, "_airllm_moved", []):
+ set_module_tensor_to_device(self.model, param_name, "meta")
+ module._airllm_moved = []
+ clean_memory()
+
+ def _prefetch_stream(self, stream_idx):
+ if not self.prefetching or self._executor is None:
+ return
+ if stream_idx < 1 or stream_idx > len(self.layer_names) - 2:
+ return
+ self._prefetch_future = self._executor.submit(
+ self.load_layer_to_cpu, self.layer_names[stream_idx])
+ self._prefetched_idx = stream_idx
+
+ def _stream_idx_for_kind(self, kind):
+ if kind[0] == "decoder":
+ return 1 + kind[1]
+ if kind[0] == "norm":
+ return len(self.layers) - 2
+ raise ValueError(f"unknown streamed kind {kind}")
+
+ def _run_decoder_layer(self, layer_i, hidden, extras):
+ layer = self.layers[1 + layer_i]
+ mask_map = extras.get("mask_map")
+ text_cfg = getattr(self.config, "text_config", self.config)
+ layer_types = getattr(text_cfg, "layer_types", None)
+ if isinstance(mask_map, dict) and layer_types is not None:
+ attn_mask = mask_map[layer_types[layer_i]]
+ else:
+ attn_mask = mask_map
+ out = layer(
+ hidden,
+ position_embeddings=extras["position_embeddings"],
+ attention_mask=attn_mask,
+ position_ids=extras["position_ids"],
+ past_key_values=None,
+ use_cache=False,
+ )
+ if torch.is_tensor(out):
+ return out
+ return out[0]
+
+ def _run_streamed(self, kind, hidden, extras, grad):
+ """Run one streamed module. When ``grad`` is True the caller must evict after backward."""
+ h = hidden.to(device=self.device, dtype=self.running_dtype)
+ stream_idx = self._stream_idx_for_kind(kind)
+ self._materialize(stream_idx)
+ ctx = torch.enable_grad() if grad else torch.no_grad()
+ with ctx:
+ if kind[0] == "decoder":
+ out = self._run_decoder_layer(kind[1], h, extras)
+ elif kind[0] == "norm":
+ out = self.layers[-2](h)
+ else:
+ raise ValueError(f"unknown streamed kind {kind}")
+ if grad:
+ return out
+ self._evict(stream_idx)
+ self._prefetch_stream(stream_idx + 1)
+ return out.detach().cpu()
+
+ def _apply_streamed(self, hidden, kind, extras):
+ _StreamedModule.trainer = self
+ _StreamedModule.kind = kind
+ _StreamedModule.extras = extras
+ try:
+ return _StreamedModule.apply(hidden)
+ finally:
+ _StreamedModule.trainer = None
+ _StreamedModule.kind = None
+ _StreamedModule.extras = None
+
+ def _make_masks(self, hidden_shape, attention_mask, text_position_ids):
+ try:
+ from transformers.masking_utils import create_causal_mask, create_recurrent_attention_mask
+ except ImportError:
+ return None
+ dummy = torch.empty(
+ hidden_shape, device=self.device, dtype=self.running_dtype)
+ cfg = getattr(self.config, "text_config", self.config)
+ mask_kwargs = {
+ "config": cfg,
+ "inputs_embeds": dummy,
+ "attention_mask": attention_mask,
+ "past_key_values": None,
+ "position_ids": text_position_ids,
+ }
+ try:
+ return {
+ "full_attention": create_causal_mask(**mask_kwargs),
+ "linear_attention": create_recurrent_attention_mask(**mask_kwargs),
+ }
+ except Exception as e: # noqa: BLE001 - fall back to the layer's is_causal path
+ print(f"AirLLM LoRA: could not build Qwen3.5 masks ({e}); using None")
+ return None
+
+ def _embed_and_context(self, input_ids, attention_mask):
+ embed = self.layers[0]
+ hidden = F.embedding(input_ids.cpu(), embed.weight)
+ hidden = hidden.to(dtype=self.running_dtype)
+ hidden.requires_grad_(True)
+
+ batch, seq = input_ids.shape
+ pos = torch.arange(seq, device=self.device)
+ pos4 = pos.view(1, 1, -1).expand(4, batch, -1)
+ text_position_ids = pos4[0]
+ rope_position_ids = pos4[1:]
+ probe = torch.zeros(1, 1, hidden.shape[-1], device=self.device, dtype=self.running_dtype)
+ position_embeddings = self._text_model().rotary_emb(probe, rope_position_ids)
+ mask_map = self._make_masks(hidden.shape, attention_mask, text_position_ids)
+ extras_base = {
+ "position_embeddings": position_embeddings,
+ "position_ids": text_position_ids,
+ "mask_map": mask_map,
+ }
+ return hidden, extras_base
+
+ def _vram_gb(self):
+ if not torch.cuda.is_available():
+ return 0.0
+ return torch.cuda.max_memory_allocated(self.device) / 1024 ** 3
+
+ def train_step(self, input_ids, labels=None, attention_mask=None, verbose=False):
+ """One SFT step. ``input_ids`` is ``[B, S]``. Returns a Python float loss."""
+ if input_ids.dim() != 2:
+ raise ValueError("input_ids must be [batch, seq]")
+ if labels is None:
+ labels = input_ids
+ input_ids = input_ids.to(self.device)
+ labels = labels.to(self.device)
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(self.device)
+
+ self.optimizer.zero_grad(set_to_none=True)
+
+ hidden, extras = self._embed_and_context(input_ids, attention_mask)
+ n_dec = self._n_decoder_layers()
+ if verbose:
+ print(f"fwd start seq={input_ids.shape[1]} peak_vram={self._vram_gb():.2f}GB", flush=True)
+ for i in range(n_dec):
+ hidden = self._apply_streamed(hidden, ("decoder", i), extras)
+ if verbose and (i % 8 == 0 or i + 1 == n_dec):
+ print(f"fwd layer {i}/{n_dec} peak_vram={self._vram_gb():.2f}GB", flush=True)
+ hidden = self._apply_streamed(hidden, ("norm",), extras)
+ if verbose:
+ print(f"ce start peak_vram={self._vram_gb():.2f}GB", flush=True)
+
+ shift_h = hidden[:, :-1, :]
+ shift_y = labels[:, 1:]
+ if attention_mask is not None:
+ shift_y = shift_y.masked_fill(attention_mask[:, 1:] == 0, -100)
+
+ weight = self.layers[-1].weight
+ loss = chunked_linear_cross_entropy(
+ shift_h, weight, shift_y, chunk_size=self.ce_chunk_size)
+ if verbose:
+ print(f"backward start loss={float(loss.detach().cpu()):.4f} peak_vram={self._vram_gb():.2f}GB", flush=True)
+ loss.backward()
+ self.optimizer.step()
+ if verbose:
+ print(f"step done peak_vram={self._vram_gb():.2f}GB", flush=True)
+ return float(loss.detach().cpu())
+
+ def save_adapter(self, path):
+ torch.save(lora_state_dict(self.model), path)
+
+ def load_adapter(self, path):
+ try:
+ state = torch.load(path, map_location="cpu", weights_only=True)
+ except TypeError:
+ state = torch.load(path, map_location="cpu")
+ load_lora_state_dict(self.model, state)
+
+
+class AirLLMLoRAQwen4Exp(AirLLMQwen4Exp):
+ """Streamed LoRA for Qwen3.8-Flash-Next (125B MoE + 51B PLE).
+
+ A packed MoE layer is ~5GB of bf16, so this is not a 4GB recipe — peak is
+ one MoE layer plus LoRA/Adam. The n-gram table stays file-mapped on the host.
+ Vision stays on meta (text-only).
+ """
+
+ def set_layer_names_dict(self):
+ super().set_layer_names_dict()
+ self.layer_names_dict["resident"] = []
+ self.layer_names_dict["cpu_resident"] = [
+ self.layer_names_dict["embed"],
+ self.layer_names_dict["lm_head"],
+ ]
+
+ def __init__(
+ self,
+ model_local_path_or_repo_id,
+ device="cuda:0",
+ dtype=None,
+ max_seq_len=512,
+ layer_shards_saving_path=None,
+ profiling_mode=False,
+ compression=None,
+ hf_token=None,
+ prefetching=True,
+ delete_original=False,
+ lora_r=16,
+ lora_alpha=32,
+ lora_dropout=0.0,
+ target_modules=None,
+ lr=1e-4,
+ ce_chunk_size=4096,
+ weight_decay=0.0,
+ packed_experts=False,
+ ):
+ super().__init__(
+ model_local_path_or_repo_id,
+ device=device,
+ dtype=dtype,
+ max_seq_len=max_seq_len,
+ layer_shards_saving_path=layer_shards_saving_path,
+ profiling_mode=profiling_mode,
+ compression=compression,
+ hf_token=hf_token,
+ prefetching=prefetching,
+ delete_original=delete_original,
+ install_hooks=False,
+ load_resident=False,
+ )
+ self.lora_r = lora_r
+ self.lora_alpha = lora_alpha
+ self.ce_chunk_size = ce_chunk_size
+ self.target_modules = tuple(target_modules or FLASH_NEXT_LORA_TARGETS)
+
+ self.model.config.use_cache = False
+ text_cfg = getattr(self.config, "text_config", None)
+ if text_cfg is not None:
+ text_cfg.use_cache = False
+ if hasattr(self.model, "gradient_checkpointing_disable"):
+ self.model.gradient_checkpointing_disable()
+ self.model.eval()
+
+ # transformers defaults MoE to grouped_mm. On a 4090 that is the Python
+ # fallback, whose autograd always allocates a full-size dW for the packed
+ # expert tensors (~3.4GB) even though those weights are frozen. Eager
+ # F.linear on routed slices does not.
+ if hasattr(self.model, "set_experts_implementation"):
+ self.model.set_experts_implementation("eager")
+ print("AirLLM LoRA Flash-Next: experts_implementation=eager (skip packed-expert dW)")
+
+ # Packed-expert LoRA is off by default: 48 layers × 512 experts × r=16 is ~5.5GB of
+ # adapters and ~22GB of fp32 Adam. Shared-expert / attention / hyper / PLE Linears
+ # still train. Pass packed_experts=True only if you have the VRAM.
+ self._finish_lora_setup(
+ lora_r, lora_alpha, lora_dropout, lr, weight_decay, packed_experts=packed_experts)
+
+ _finish_lora_setup = AirLLMLoRA._finish_lora_setup
+ _module = AirLLMLoRA._module
+ _decoder_container = AirLLMLoRA._decoder_container
+ _text_model = AirLLMLoRA._text_model
+ _n_decoder_layers = AirLLMLoRA._n_decoder_layers
+ _materialize = AirLLMLoRA._materialize
+ _evict = AirLLMLoRA._evict
+ _prefetch_stream = AirLLMLoRA._prefetch_stream
+ _stream_idx_for_kind = AirLLMLoRA._stream_idx_for_kind
+ _run_streamed = AirLLMLoRA._run_streamed
+ _apply_streamed = AirLLMLoRA._apply_streamed
+ _vram_gb = AirLLMLoRA._vram_gb
+ train_step = AirLLMLoRA.train_step
+ save_adapter = AirLLMLoRA.save_adapter
+ load_adapter = AirLLMLoRA.load_adapter
+
+ def _hc_count(self):
+ cfg = getattr(self.config, "text_config", self.config)
+ return int(getattr(cfg, "hc_count", 1) or 1)
+
+ def _make_masks(self, hidden_shape, attention_mask, text_position_ids):
+ try:
+ from transformers.masking_utils import create_causal_mask, create_recurrent_attention_mask
+ except ImportError:
+ return None
+ # Masks are built from token-width embeds (hidden), not the 4-stream hyper state.
+ dummy = torch.empty(
+ hidden_shape, device=self.device, dtype=self.running_dtype)
+ cfg = getattr(self.config, "text_config", self.config)
+ mask_kwargs = {
+ "config": cfg,
+ "inputs_embeds": dummy,
+ "attention_mask": attention_mask,
+ "past_key_values": None,
+ "position_ids": text_position_ids,
+ "allow_is_causal_skip": False,
+ }
+ try:
+ return {
+ "qwen_sparse_attention": create_causal_mask(**mask_kwargs),
+ "linear_attention": create_recurrent_attention_mask(**mask_kwargs),
+ }
+ except Exception as e: # noqa: BLE001
+ print(f"AirLLM LoRA Flash-Next: could not build masks ({e}); using None")
+ return None
+
+ def _embed_and_context(self, input_ids, attention_mask):
+ embed = self.layers[0]
+ hidden = F.embedding(input_ids.cpu(), embed.weight)
+ hidden = hidden.to(dtype=self.running_dtype)
+ hidden = hidden.repeat(1, 1, self._hc_count())
+ hidden.requires_grad_(True)
+
+ batch, seq = input_ids.shape
+ pos = torch.arange(seq, device=self.device)
+ pos4 = pos.view(1, 1, -1).expand(4, batch, -1)
+ text_position_ids = pos4[0]
+ rope_position_ids = pos4[1:]
+ probe = torch.zeros(
+ 1, 1, embed.weight.shape[-1], device=self.device, dtype=self.running_dtype)
+ position_embeddings = self._text_model().rotary_emb(probe, rope_position_ids)
+ token_shape = (batch, seq, embed.weight.shape[-1])
+ mask_map = self._make_masks(token_shape, attention_mask, text_position_ids)
+ conv_mask = None
+ if isinstance(mask_map, dict):
+ conv_mask = mask_map.get("linear_attention")
+ ple_ids = input_ids
+ if conv_mask is not None:
+ cfg = getattr(self.config, "text_config", self.config)
+ eos = getattr(cfg, "eos_token_id", None)
+ if isinstance(eos, (list, tuple)):
+ eos = eos[0] if eos else None
+ if eos is not None:
+ try:
+ ple_ids = torch.where(conv_mask.bool(), input_ids, eos)
+ except RuntimeError:
+ ple_ids = input_ids
+ return hidden, {
+ "position_embeddings": position_embeddings,
+ "position_ids": text_position_ids,
+ "mask_map": mask_map,
+ "conv_mask": conv_mask,
+ "ple_input_ids": ple_ids,
+ }
+
+ def _run_decoder_layer(self, layer_i, hidden, extras):
+ layer = self.layers[1 + layer_i]
+ mask_map = extras.get("mask_map")
+ if isinstance(mask_map, dict):
+ attn_mask = mask_map.get("qwen_sparse_attention")
+ else:
+ attn_mask = mask_map
+ out = layer(
+ hidden,
+ position_embeddings=extras["position_embeddings"],
+ attention_mask=attn_mask,
+ conv_mask=extras.get("conv_mask"),
+ past_key_values=None,
+ ple_input_ids=extras.get("ple_input_ids"),
+ use_cache=False,
+ )
+ if torch.is_tensor(out):
+ return out
+ return out[0]
diff --git a/air_llm/airllm/chunked_ce.py b/air_llm/airllm/chunked_ce.py
new file mode 100644
index 0000000..b5ed1d3
--- /dev/null
+++ b/air_llm/airllm/chunked_ce.py
@@ -0,0 +1,144 @@
+"""Fused linear-cross-entropy that never materialises ``[N, vocab]`` logits.
+
+Qwen3.8's lm_head is 248320 × 5120 (2.54GB bf16). A naive ``hidden @ W.T`` at
+seq 2048 is another ~2GB of fp32 logits. This walks the vocabulary in chunks,
+keeps a running log-sum-exp, and recomputes the same chunks in backward to get
+``d_hidden``. ``W`` may live on CPU.
+"""
+
+import torch
+
+
+def _compute_device(hidden):
+ """Matmuls follow ``hidden`` unless it is on CPU and CUDA is available."""
+ if hidden.is_cuda or not torch.cuda.is_available():
+ return hidden.device
+ return torch.device("cuda")
+
+
+class _ChunkedCE(torch.autograd.Function):
+ """Tensor-only front door. ``weight`` is stashed on the class for one apply()."""
+
+ weight = None
+ chunk_size = 4096
+ ignore_index = -100
+ reduction = "mean"
+
+ @staticmethod
+ def forward(ctx, hidden, labels):
+ weight = _ChunkedCE.weight
+ chunk_size = int(_ChunkedCE.chunk_size)
+ ignore_index = int(_ChunkedCE.ignore_index)
+ reduction = _ChunkedCE.reduction
+ if weight is None:
+ raise RuntimeError("chunked CE weight was not set")
+
+ compute_device = _compute_device(hidden)
+ h = hidden.to(compute_device)
+ n, _hidden = h.shape
+ vocab = weight.shape[0]
+ if chunk_size < 1:
+ chunk_size = vocab
+
+ labels = labels.reshape(-1).to(device=compute_device)
+ if labels.numel() != n:
+ raise ValueError(f"labels has {labels.numel()} elements, hidden has {n} rows")
+
+ valid = labels != ignore_index
+ logz = torch.full((n,), float("-inf"), device=compute_device, dtype=torch.float32)
+ target_logit = torch.zeros(n, device=compute_device, dtype=torch.float32)
+
+ with torch.no_grad():
+ for start in range(0, vocab, chunk_size):
+ end = min(start + chunk_size, vocab)
+ w = weight[start:end].to(device=compute_device, dtype=h.dtype)
+ logits = (h @ w.t()).float()
+ logz = torch.logaddexp(logz, logits.logsumexp(dim=-1))
+ in_chunk = valid & (labels >= start) & (labels < end)
+ if in_chunk.any():
+ rows = in_chunk.nonzero(as_tuple=False).squeeze(-1)
+ target_logit[rows] = logits[rows, labels[rows] - start]
+
+ n_valid = valid.sum().clamp(min=1).to(dtype=torch.float32)
+ per_token = torch.where(valid, logz - target_logit, torch.zeros_like(logz))
+ if reduction == "sum":
+ loss = per_token.sum()
+ elif reduction == "none":
+ loss = per_token
+ else:
+ loss = per_token.sum() / n_valid
+
+ ctx.save_for_backward(hidden, labels.to(hidden.device))
+ ctx.weight = weight
+ ctx.chunk_size = chunk_size
+ ctx.ignore_index = ignore_index
+ ctx.n_valid = int(n_valid.item())
+ ctx.valid = valid.to(hidden.device)
+ ctx.compute_device = compute_device
+ ctx.reduction = reduction
+ ctx.logz = logz.to(hidden.device)
+ return loss if hidden.is_cuda or loss.device == hidden.device else loss.to(hidden.device)
+
+ @staticmethod
+ def backward(ctx, grad_loss):
+ hidden, labels = ctx.saved_tensors
+ weight = ctx.weight
+ compute_device = ctx.compute_device
+ h = hidden.to(compute_device)
+ labels = labels.to(compute_device)
+ valid = ctx.valid.to(compute_device)
+ logz = ctx.logz.to(compute_device)
+ vocab = weight.shape[0]
+ chunk_size = ctx.chunk_size
+
+ scale = grad_loss.to(compute_device)
+ if ctx.reduction == "mean":
+ scale = scale / max(ctx.n_valid, 1)
+ elif ctx.reduction == "none":
+ scale = scale.reshape(-1)
+
+ d_hidden = torch.zeros(h.shape, device=compute_device, dtype=torch.float32)
+
+ for start in range(0, vocab, chunk_size):
+ end = min(start + chunk_size, vocab)
+ w = weight[start:end].to(device=compute_device, dtype=h.dtype)
+ logits = (h @ w.t()).float()
+ probs = torch.exp(logits - logz.unsqueeze(-1))
+ in_chunk = valid & (labels >= start) & (labels < end)
+ if in_chunk.any():
+ rows = in_chunk.nonzero(as_tuple=False).squeeze(-1)
+ probs[rows, labels[rows] - start] -= 1.0
+ probs = probs.masked_fill(~valid.unsqueeze(-1), 0.0)
+ if ctx.reduction == "none":
+ d_hidden += (probs * scale.unsqueeze(-1)) @ w.float()
+ else:
+ d_hidden += (probs @ w.float()) * scale
+
+ d_hidden = d_hidden.to(dtype=hidden.dtype, device=hidden.device)
+ return d_hidden, None
+
+
+def chunked_linear_cross_entropy(
+ hidden,
+ weight,
+ labels,
+ chunk_size=4096,
+ ignore_index=-100,
+ reduction="mean",
+):
+ """Cross-entropy of ``hidden @ weight.T`` vs ``labels``, chunked over vocab.
+
+ ``hidden`` is ``[N, H]`` or ``[B, S, H]`` and may live on CPU. ``weight`` is
+ ``[V, H]`` and may live on CPU. ``labels`` matches hidden's token layout.
+ """
+ if hidden.dim() == 3:
+ hidden = hidden.reshape(-1, hidden.shape[-1])
+ labels = labels.reshape(-1)
+ _ChunkedCE.weight = weight
+ _ChunkedCE.chunk_size = chunk_size
+ _ChunkedCE.ignore_index = ignore_index
+ _ChunkedCE.reduction = reduction
+ try:
+ return _ChunkedCE.apply(hidden, labels)
+ finally:
+ _ChunkedCE.weight = None
diff --git a/air_llm/airllm/lora_linear.py b/air_llm/airllm/lora_linear.py
new file mode 100644
index 0000000..b185194
--- /dev/null
+++ b/air_llm/airllm/lora_linear.py
@@ -0,0 +1,201 @@
+"""Minimal LoRA wrapper that keeps the original ``weight`` Parameter in place.
+
+PEFT is not used: it expects materialised base weights and will try to move the
+whole model. AirLLM training swaps frozen ``weight`` tensors from disk onto a
+``meta`` module; the adapter matrices stay on the GPU for the whole run.
+"""
+
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+DEFAULT_LORA_TARGETS = (
+ "q_proj",
+ "k_proj",
+ "v_proj",
+ "o_proj",
+ "in_proj_qkv",
+ "in_proj_z",
+ "in_proj_b",
+ "in_proj_a",
+ "out_proj",
+ "gate_proj",
+ "up_proj",
+ "down_proj",
+)
+
+# Flash-Next extra Linears: hyper-connections, PLE, shared-expert gate.
+FLASH_NEXT_LORA_TARGETS = DEFAULT_LORA_TARGETS + (
+ "shared_expert_gate",
+ "input_mix_weight_down",
+ "input_mix_weight_up",
+ "block_inject_weight",
+ "key_proj",
+ "value_proj",
+)
+
+
+class LoRALinear(nn.Module):
+ """``y = x W^T + (x A^T) B^T * (alpha / r)``. Base ``W`` is frozen."""
+
+ def __init__(self, linear, r=16, alpha=32, dropout=0.0, device=None, dtype=None):
+ super().__init__()
+ if r < 1:
+ raise ValueError(f"LoRA rank must be >= 1, got {r}")
+ self.in_features = linear.in_features
+ self.out_features = linear.out_features
+ self.r = r
+ self.alpha = alpha
+ self.scaling = alpha / r
+
+ # Keep the same Parameter object so AirLLM can still load shard keys
+ # named ``<module>.weight`` / ``<module>.bias``.
+ self.weight = linear.weight
+ self.bias = linear.bias
+ self.weight.requires_grad_(False)
+ if self.bias is not None:
+ self.bias.requires_grad_(False)
+
+ if device is None:
+ device = self.weight.device if self.weight.device.type != "meta" else torch.device("cpu")
+ if dtype is None:
+ dtype = self.weight.dtype if self.weight.device.type != "meta" else torch.float32
+
+ self.lora_A = nn.Parameter(torch.empty(r, self.in_features, device=device, dtype=dtype))
+ self.lora_B = nn.Parameter(torch.empty(self.out_features, r, device=device, dtype=dtype))
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
+ nn.init.zeros_(self.lora_B)
+ self.lora_dropout = nn.Dropout(dropout) if dropout else nn.Identity()
+
+ def forward(self, x):
+ base = F.linear(x, self.weight, self.bias)
+ z = self.lora_dropout(x)
+ a = self.lora_A.to(dtype=z.dtype)
+ b = self.lora_B.to(dtype=z.dtype)
+ return base + (z @ a.t() @ b.t()) * self.scaling
+
+
+def inject_lora(module, target_modules=DEFAULT_LORA_TARGETS, r=16, alpha=32,
+ dropout=0.0, device=None, dtype=None):
+ """Replace matching ``nn.Linear`` children with ``LoRALinear``. Returns count."""
+ targets = set(target_modules)
+ n = 0
+ for name, child in list(module.named_children()):
+ if isinstance(child, LoRALinear):
+ continue
+ if isinstance(child, nn.Linear) and name in targets:
+ setattr(module, name, LoRALinear(
+ child, r=r, alpha=alpha, dropout=dropout, device=device, dtype=dtype))
+ n += 1
+ else:
+ n += inject_lora(child, targets, r, alpha, dropout, device, dtype)
+ return n
+
+
+class LoRAPackedExperts(nn.Module):
+ """LoRA on Qwen4Exp's 3D packed expert tensors (not ``nn.Linear``).
+
+ Base ``gate_up_proj`` is ``[E, 2I, H]`` and ``down_proj`` is ``[E, H, I]``.
+ The original forward only touches the routed experts, so the extra matmuls
+ stay on those rows too.
+ """
+
+ def __init__(self, experts, r=16, alpha=32, device=None, dtype=None):
+ super().__init__()
+ self.num_experts = experts.num_experts
+ self.hidden_dim = experts.hidden_dim
+ self.intermediate_dim = experts.intermediate_dim
+ self.act_fn = experts.act_fn
+ self.r = r
+ self.scaling = alpha / r
+ self.gate_up_proj = experts.gate_up_proj
+ self.down_proj = experts.down_proj
+ self.gate_up_proj.requires_grad_(False)
+ self.down_proj.requires_grad_(False)
+
+ if device is None:
+ device = torch.device("cpu") if self.gate_up_proj.device.type == "meta" else self.gate_up_proj.device
+ if dtype is None:
+ dtype = torch.bfloat16 if self.gate_up_proj.device.type == "meta" else self.gate_up_proj.dtype
+
+ self.lora_A_gate_up = nn.Parameter(
+ torch.empty(self.num_experts, r, self.hidden_dim, device=device, dtype=dtype))
+ self.lora_B_gate_up = nn.Parameter(
+ torch.empty(self.num_experts, 2 * self.intermediate_dim, r, device=device, dtype=dtype))
+ self.lora_A_down = nn.Parameter(
+ torch.empty(self.num_experts, r, self.intermediate_dim, device=device, dtype=dtype))
+ self.lora_B_down = nn.Parameter(
+ torch.empty(self.num_experts, self.hidden_dim, r, device=device, dtype=dtype))
+ nn.init.kaiming_uniform_(self.lora_A_gate_up, a=math.sqrt(5))
+ nn.init.kaiming_uniform_(self.lora_A_down, a=math.sqrt(5))
+ nn.init.zeros_(self.lora_B_gate_up)
+ nn.init.zeros_(self.lora_B_down)
+
+ def forward(self, hidden_states, top_k_index, top_k_weights):
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ e = int(expert_idx)
+ gate_up = F.linear(current_state, self.gate_up_proj[e])
+ a_gu = self.lora_A_gate_up[e].to(dtype=current_state.dtype)
+ b_gu = self.lora_B_gate_up[e].to(dtype=current_state.dtype)
+ gate_up = gate_up + (current_state @ a_gu.t() @ b_gu.t()) * self.scaling
+ gate, up = gate_up.chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ down = F.linear(current_hidden_states, self.down_proj[e])
+ a_d = self.lora_A_down[e].to(dtype=current_hidden_states.dtype)
+ b_d = self.lora_B_down[e].to(dtype=current_hidden_states.dtype)
+ down = down + (current_hidden_states @ a_d.t() @ b_d.t()) * self.scaling
+ current_hidden_states = down * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(
+ 0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+ return final_hidden_states
+
+
+def inject_packed_expert_lora(module, r=16, alpha=32, device=None, dtype=None):
+ """Wrap ``Qwen4ExpTextExperts`` modules. Returns count."""
+ n = 0
+ for name, child in list(module.named_children()):
+ if isinstance(child, LoRAPackedExperts):
+ continue
+ if type(child).__name__ == "Qwen4ExpTextExperts":
+ setattr(module, name, LoRAPackedExperts(
+ child, r=r, alpha=alpha, device=device, dtype=dtype))
+ n += 1
+ else:
+ n += inject_packed_expert_lora(child, r, alpha, device, dtype)
+ return n
+
+
+def lora_parameters(module):
+ return [p for n, p in module.named_parameters() if "lora_" in n]
+
+
+def lora_state_dict(module):
+ return {n: p.detach().cpu() for n, p in module.named_parameters() if "lora_" in n}
+
+
+def load_lora_state_dict(module, state, strict=True):
+ missing = []
+ owned = dict(module.named_parameters())
+ for name, value in state.items():
+ param = owned.get(name)
+ if param is None:
+ missing.append(name)
+ continue
+ param.data.copy_(value.to(device=param.device, dtype=param.dtype))
+ if strict and missing:
+ raise KeyError(f"LoRA keys not found in module: {missing[:8]}")
+ return missing
diff --git a/air_llm/examples/train_qwen38_flash_next_lora.py b/air_llm/examples/train_qwen38_flash_next_lora.py
new file mode 100644
index 0000000..eb254cd
--- /dev/null
+++ b/air_llm/examples/train_qwen38_flash_next_lora.py
@@ -0,0 +1,123 @@
+"""Smoke-test streamed LoRA on Qwen3.8-Flash-Next (125B MoE + 51B PLE).
+
+Shared-expert / attention / hyper-connection / PLE Linears train; packed-expert
+LoRA is off by default (48 layers of 512-expert adapters plus Adam will not
+fit). Measured peak is under 6GB at seq 512 (RTX 3060 Ti / 4090). The n-gram
+table stays mmap'd.
+
+Needs a transformers build with in-tree ``qwen4_exp``::
+
+ pip install git+https://github.com/huggingface/transformers.git
+ python examples/train_qwen38_flash_next_lora.py --seq-len 512 --steps 1 --verbose
+"""
+
+import argparse
+import os
+import sys
+import time
+
+import torch
+
+_AIRLLM = os.path.join(os.path.dirname(__file__), "..")
+if _AIRLLM not in sys.path:
+ sys.path.insert(0, os.path.abspath(_AIRLLM))
+
+from airllm.airllm_lora import AirLLMLoRAQwen4Exp
+
+
+def parse_args():
+ p = argparse.ArgumentParser(description="AirLLM streamed LoRA smoke test (Qwen3.8-Flash-Next)")
+ p.add_argument("--model", default="Qwen/Qwen3.8-Flash-Next")
+ p.add_argument("--device", default="cuda:0")
+ p.add_argument("--seq-len", type=int, default=512)
+ p.add_argument("--steps", type=int, default=1)
+ p.add_argument("--lora-r", type=int, default=16)
+ p.add_argument("--lora-alpha", type=int, default=32)
+ p.add_argument("--lr", type=float, default=1e-4)
+ p.add_argument("--ce-chunk-size", type=int, default=4096)
+ p.add_argument("--max-seq-len", type=int, default=None,
+ help="shard/runtime cap; defaults to --seq-len")
+ p.add_argument("--save-adapter", default=None)
+ p.add_argument("--packed-expert-lora", action="store_true",
+ help="also LoRA the 512 packed experts (VRAM-heavy)")
+ p.add_argument("--keep-original", action="store_true",
+ help="keep the Hugging Face shard files after splitting")
+ p.add_argument("--verbose", action="store_true")
+ p.add_argument("--log-csv", default=None,
+ help="write step,loss,peak_vram_gb,elapsed_s")
+ return p.parse_args()
+
+
+def main():
+ args = parse_args()
+ if not torch.cuda.is_available():
+ print("CUDA is required for this smoke test.")
+ sys.exit(1)
+
+ max_seq_len = args.max_seq_len or args.seq_len
+ trainer = AirLLMLoRAQwen4Exp(
+ args.model,
+ device=args.device,
+ max_seq_len=max_seq_len,
+ lora_r=args.lora_r,
+ lora_alpha=args.lora_alpha,
+ lr=args.lr,
+ ce_chunk_size=args.ce_chunk_size,
+ delete_original=not args.keep_original,
+ packed_experts=args.packed_expert_lora,
+ )
+
+ tok = trainer.tokenizer
+ if tok.pad_token_id is None:
+ tok.pad_token = tok.eos_token
+
+ # Unique SFT-style passage (not one sentence repeated) so the curve is next-token
+ # learning, not trivial copy-memorization of a looped line.
+ text = (
+ "AirLLM trains LoRA with one decoder layer on the GPU at a time. "
+ "Frozen Qwen3.8-Flash-Next experts stay on disk until a layer is needed. "
+ "The n-gram PLE table is file-mapped on the host and never copied into VRAM. "
+ "Hyper-connections mix four residual streams before the language-model head. "
+ "Gated DeltaNet layers use a recurrent state; sparse-attention layers use QSA. "
+ "Adam keeps only the adapter matrices resident, about 168 megabytes at rank 16. "
+ "A packed MoE layer is five gigabytes of bfloat16; streaming it is the whole trick. "
+ "Loss should fall as the adapters fit this short supervised sequence. "
+ ) * 32
+ encoded = tok(text, return_tensors="pt", truncation=True, max_length=args.seq_len)
+ input_ids = encoded["input_ids"].to(trainer.device)
+ attention_mask = encoded.get("attention_mask")
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(trainer.device)
+ print(f"tokens={input_ids.shape[1]} requested={args.seq_len}", flush=True)
+
+ csv_f = None
+ if args.log_csv:
+ csv_f = open(args.log_csv, "w", encoding="utf-8")
+ csv_f.write("step,loss,peak_vram_gb,elapsed_s\n")
+ csv_f.flush()
+
+ torch.cuda.reset_peak_memory_stats(trainer.device)
+ t0 = time.time()
+ for step in range(args.steps):
+ loss = trainer.train_step(
+ input_ids, attention_mask=attention_mask, verbose=args.verbose)
+ peak = torch.cuda.max_memory_allocated(trainer.device) / 1024 ** 3
+ elapsed = time.time() - t0
+ print(
+ f"step {step} loss={loss:.6f} peak_vram={peak:.2f}GB "
+ f"seq={input_ids.shape[1]} elapsed_s={elapsed:.1f}",
+ flush=True,
+ )
+ if csv_f is not None:
+ csv_f.write(f"{step},{loss:.8f},{peak:.4f},{elapsed:.2f}\n")
+ csv_f.flush()
+ if csv_f is not None:
+ csv_f.close()
+
+ if args.save_adapter:
+ trainer.save_adapter(args.save_adapter)
+ print(f"saved adapter to {args.save_adapter}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/air_llm/examples/train_qwen38_lora.py b/air_llm/examples/train_qwen38_lora.py
new file mode 100644
index 0000000..1da570f
--- /dev/null
+++ b/air_llm/examples/train_qwen38_lora.py
@@ -0,0 +1,84 @@
+"""Smoke-test streamed LoRA on Qwen3.8-27B and print peak VRAM.
+
+v1 is text-only, batch=1. Start at ``--seq-len 512`` on a 4GB card; 2048 is the
+8GB target. This is not Hugging Face Trainer / bitsandbytes QLoRA — see
+``airllm.airllm_lora.AirLLMLoRA``.
+
+Example::
+
+ python examples/train_qwen38_lora.py --model Qwen/Qwen3.8-27B --seq-len 512 --steps 1
+"""
+
+import argparse
+import os
+import sys
+
+import torch
+
+_AIRLLM = os.path.join(os.path.dirname(__file__), "..")
+if _AIRLLM not in sys.path:
+ sys.path.insert(0, os.path.abspath(_AIRLLM))
+
+from airllm.airllm_lora import AirLLMLoRA
+
+
+def parse_args():
+ p = argparse.ArgumentParser(description="AirLLM streamed LoRA smoke test (Qwen3.8-27B)")
+ p.add_argument("--model", default="Qwen/Qwen3.8-27B")
+ p.add_argument("--device", default="cuda:0")
+ p.add_argument("--seq-len", type=int, default=512)
+ p.add_argument("--steps", type=int, default=1)
+ p.add_argument("--lora-r", type=int, default=16)
+ p.add_argument("--lora-alpha", type=int, default=32)
+ p.add_argument("--lr", type=float, default=1e-4)
+ p.add_argument("--ce-chunk-size", type=int, default=4096)
+ p.add_argument("--max-seq-len", type=int, default=None,
+ help="shard/runtime cap; defaults to --seq-len")
+ p.add_argument("--save-adapter", default=None)
+ p.add_argument("--verbose", action="store_true")
+ return p.parse_args()
+
+
+def main():
+ args = parse_args()
+ if not torch.cuda.is_available():
+ print("CUDA is required for this smoke test.")
+ sys.exit(1)
+
+ max_seq_len = args.max_seq_len or args.seq_len
+ trainer = AirLLMLoRA(
+ args.model,
+ device=args.device,
+ max_seq_len=max_seq_len,
+ lora_r=args.lora_r,
+ lora_alpha=args.lora_alpha,
+ lr=args.lr,
+ ce_chunk_size=args.ce_chunk_size,
+ )
+
+ tok = trainer.tokenizer
+ if tok.pad_token_id is None:
+ tok.pad_token = tok.eos_token
+
+ text = "AirLLM trains LoRA with one decoder layer on the GPU at a time. " * 256
+ encoded = tok(text, return_tensors="pt", truncation=True, max_length=args.seq_len)
+ input_ids = encoded["input_ids"].to(trainer.device)
+ attention_mask = encoded.get("attention_mask")
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(trainer.device)
+ print(f"tokens={input_ids.shape[1]} requested={args.seq_len}", flush=True)
+
+ torch.cuda.reset_peak_memory_stats(trainer.device)
+ for step in range(args.steps):
+ loss = trainer.train_step(
+ input_ids, attention_mask=attention_mask, verbose=args.verbose)
+ peak = torch.cuda.max_memory_allocated(trainer.device) / 1024 ** 3
+ print(f"step {step} loss={loss:.4f} peak_vram={peak:.2f}GB seq={input_ids.shape[1]}", flush=True)
+
+ if args.save_adapter:
+ trainer.save_adapter(args.save_adapter)
+ print(f"saved adapter to {args.save_adapter}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/air_llm/setup.py b/air_llm/setup.py
index b349ed7..692b8f2 100644
--- a/air_llm/setup.py
+++ b/air_llm/setup.py
@@ -15,12 +15,12 @@ for _readme in (os.path.join(here, "README.md"), os.path.join(here, os.pardir, "
setuptools.setup(
name="airllm",
- version="3.3.0",
+ version="4.0.0",
author="Gavin Li",
author_email="[email protected]",
description="AirLLM runs 70B large language models on a single 4GB GPU without quantization, "
- "distillation or pruning. 405B Llama 3.1 on 8GB, DeepSeek-V3 671B on ~12GB, "
- "Kimi K3 2.8T on under 4GB, Qwen3.8-27B on 3.3GB, Qwen3.8-Flash-Next on 6GB.",
+ "distillation or pruning. Kimi K3 2.8T on under 4GB, Qwen3.8-Flash-Next 125B on 6GB, "
+ "DeepSeek-V3 671B on ~12GB. Train Qwen3.8-Flash-Next under 6GB.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/lyogavin/airllm",
@@ -30,7 +30,7 @@ setuptools.setup(
install_requires=[
'tqdm',
'torch>=2.4',
- 'transformers>=4.49,<5.13',
+ 'transformers>=4.49,<6',
'accelerate>=1.0',
'safetensors',
'huggingface-hub',
diff --git a/air_llm/tests/test_streamed_lora.py b/air_llm/tests/test_streamed_lora.py
new file mode 100644
index 0000000..eb09813
--- /dev/null
+++ b/air_llm/tests/test_streamed_lora.py
@@ -0,0 +1,237 @@
+"""Unit tests for streamed LoRA pieces that do not need a GPU or Qwen weights."""
+
+import math
+import sys
+import types
+import unittest
+from pathlib import Path
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+_AIRLLM_DIR = Path(__file__).resolve().parents[1] / "airllm"
+
+if "airllm" not in sys.modules:
+ _pkg = types.ModuleType("airllm")
+ _pkg.__path__ = [str(_AIRLLM_DIR)]
+ sys.modules["airllm"] = _pkg
+
+from airllm.chunked_ce import chunked_linear_cross_entropy
+from airllm.lora_linear import (
+ LoRALinear,
+ LoRAPackedExperts,
+ inject_lora,
+ inject_packed_expert_lora,
+ lora_parameters,
+ lora_state_dict,
+ load_lora_state_dict,
+)
+
+
+class TestLoRALinear(unittest.TestCase):
+ def test_base_is_frozen_adapters_train(self):
+ torch.manual_seed(0)
+ linear = nn.Linear(8, 4, bias=False)
+ with torch.no_grad():
+ linear.weight.copy_(torch.randn(4, 8))
+ frozen = linear.weight.detach().clone()
+ wrap = LoRALinear(linear, r=2, alpha=4, device=torch.device("cpu"), dtype=torch.float32)
+ x = torch.randn(3, 8)
+ y = torch.randn(3, 4)
+ opt = torch.optim.Adam(lora_parameters(wrap), lr=0.05)
+ before = F.mse_loss(wrap(x), y).item()
+ for _ in range(30):
+ opt.zero_grad()
+ F.mse_loss(wrap(x), y).backward()
+ opt.step()
+ after = F.mse_loss(wrap(x), y).item()
+ self.assertTrue(math.isfinite(after))
+ self.assertLess(after, before)
+ self.assertTrue(torch.equal(wrap.weight, frozen))
+ self.assertFalse(wrap.weight.requires_grad)
+ self.assertTrue(wrap.lora_A.requires_grad)
+
+ def test_inject_and_roundtrip_state(self):
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(4, 4, bias=False)
+ self.other = nn.Linear(4, 4, bias=False)
+
+ block = Block()
+ n = inject_lora(block, target_modules=("q_proj",), r=2, alpha=2,
+ device=torch.device("cpu"), dtype=torch.float32)
+ self.assertEqual(n, 1)
+ self.assertIsInstance(block.q_proj, LoRALinear)
+ self.assertIsInstance(block.other, nn.Linear)
+ state = lora_state_dict(block)
+ self.assertTrue(any("lora_A" in k for k in state))
+ block.q_proj.lora_A.data.zero_()
+ load_lora_state_dict(block, state)
+ self.assertTrue(torch.allclose(block.q_proj.lora_A.cpu(), state["q_proj.lora_A"]))
+
+
+class TestChunkedCE(unittest.TestCase):
+ def test_matches_full_cross_entropy(self):
+ torch.manual_seed(1)
+ n, h, v = 6, 8, 21
+ hidden = torch.randn(n, h, requires_grad=True)
+ weight = torch.randn(v, h)
+ labels = torch.tensor([0, 3, 20, -100, 7, 1])
+
+ loss_ref = F.cross_entropy(hidden @ weight.t(), labels, ignore_index=-100)
+ loss = chunked_linear_cross_entropy(
+ hidden, weight, labels, chunk_size=5, ignore_index=-100)
+
+ self.assertTrue(torch.allclose(loss, loss_ref, rtol=1e-4, atol=1e-5))
+
+ loss_ref.backward()
+ g_ref = hidden.grad.clone()
+ hidden.grad = None
+ hidden2 = hidden.detach().clone().requires_grad_(True)
+ loss2 = chunked_linear_cross_entropy(
+ hidden2, weight, labels, chunk_size=5, ignore_index=-100)
+ loss2.backward()
+ self.assertTrue(torch.allclose(hidden2.grad, g_ref, rtol=1e-4, atol=1e-5))
+
+ def test_batched_shape_and_cpu_weight(self):
+ torch.manual_seed(2)
+ hidden = torch.randn(2, 4, 8, requires_grad=True)
+ weight = torch.randn(11, 8)
+ labels = torch.randint(0, 11, (2, 4))
+ loss = chunked_linear_cross_entropy(hidden, weight, labels, chunk_size=3)
+ loss.backward()
+ self.assertEqual(tuple(hidden.grad.shape), (2, 4, 8))
+ self.assertTrue(math.isfinite(loss.item()))
+
+
+class _OffloadPack:
+ """Stand-in for disk offload: weight lives in a CPU dict between calls."""
+
+ def __init__(self, module, key="weight"):
+ self.module = module
+ self.key = key
+ self.store = {key: module.weight.detach().clone()}
+
+ def load(self):
+ with torch.no_grad():
+ self.module.weight.copy_(self.store[self.key])
+
+ def evict(self):
+ with torch.no_grad():
+ self.module.weight.zero_()
+
+
+class _TinyStream(torch.autograd.Function):
+ pack = None
+
+ @staticmethod
+ def forward(ctx, hidden):
+ pack = _TinyStream.pack
+ ctx.pack = pack
+ h = hidden.detach()
+ pack.load()
+ with torch.no_grad():
+ out = pack.module(h)
+ pack.evict()
+ ctx.save_for_backward(h)
+ return out.detach()
+
+ @staticmethod
+ def backward(ctx, grad):
+ pack = ctx.pack
+ h = ctx.saved_tensors[0].detach().requires_grad_(True)
+ pack.load()
+ with torch.enable_grad():
+ out = pack.module(h)
+ out.backward(grad)
+ pack.evict()
+ return h.grad
+
+
+class TestStreamedLoRA(unittest.TestCase):
+ def test_streamed_lora_matches_resident_grads(self):
+ torch.manual_seed(3)
+ linear = nn.Linear(8, 8, bias=False)
+ nn.init.normal_(linear.weight)
+ wrap = LoRALinear(linear, r=2, alpha=4, device=torch.device("cpu"), dtype=torch.float32)
+ x = torch.randn(4, 8)
+ go = torch.randn(4, 8)
+
+ y = wrap(x)
+ y.backward(go)
+ gA = wrap.lora_A.grad.clone()
+ gB = wrap.lora_B.grad.clone()
+ wrap.lora_A.grad = None
+ wrap.lora_B.grad = None
+
+ pack = _OffloadPack(wrap)
+ pack.evict()
+ _TinyStream.pack = pack
+ try:
+ x2 = x.detach().requires_grad_(True)
+ y2 = _TinyStream.apply(x2)
+ y2.backward(go)
+ finally:
+ _TinyStream.pack = None
+ pack.load()
+
+ self.assertTrue(torch.allclose(wrap.lora_A.grad, gA, rtol=1e-4, atol=1e-5))
+ self.assertTrue(torch.allclose(wrap.lora_B.grad, gB, rtol=1e-4, atol=1e-5))
+
+
+class _FakePackedExperts(nn.Module):
+ """Stand-in for transformers' Qwen4ExpTextExperts (3D Parameters, not Linear)."""
+
+ def __init__(self, n_exp=4, hidden=8, intermediate=6):
+ super().__init__()
+ self.num_experts = n_exp
+ self.hidden_dim = hidden
+ self.intermediate_dim = intermediate
+ self.gate_up_proj = nn.Parameter(torch.randn(n_exp, 2 * intermediate, hidden))
+ self.down_proj = nn.Parameter(torch.randn(n_exp, hidden, intermediate))
+ self.act_fn = F.silu
+
+
+class TestPackedExpertLoRA(unittest.TestCase):
+ def test_base_frozen_and_loss_drops(self):
+ torch.manual_seed(4)
+ experts = _FakePackedExperts()
+ frozen_gu = experts.gate_up_proj.detach().clone()
+ wrap = LoRAPackedExperts(experts, r=2, alpha=4, device=torch.device("cpu"), dtype=torch.float32)
+ n_tok = 5
+ hidden = torch.randn(n_tok, 8)
+ top_k_index = torch.tensor([[0, 1], [1, 2], [0, 3], [2, 3], [1, 0]])
+ top_k_weights = torch.full((n_tok, 2), 0.5)
+ target = torch.randn(n_tok, 8)
+ opt = torch.optim.Adam(lora_parameters(wrap), lr=0.05)
+ before = F.mse_loss(wrap(hidden, top_k_index, top_k_weights), target).item()
+ for _ in range(40):
+ opt.zero_grad()
+ F.mse_loss(wrap(hidden, top_k_index, top_k_weights), target).backward()
+ opt.step()
+ after = F.mse_loss(wrap(hidden, top_k_index, top_k_weights), target).item()
+ self.assertTrue(math.isfinite(after))
+ self.assertLess(after, before)
+ self.assertTrue(torch.equal(wrap.gate_up_proj, frozen_gu))
+ self.assertFalse(wrap.gate_up_proj.requires_grad)
+ self.assertTrue(wrap.lora_A_gate_up.requires_grad)
+
+ def test_inject_by_class_name(self):
+ class Qwen4ExpTextExperts(_FakePackedExperts):
+ pass
+
+ class MoE(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.experts = Qwen4ExpTextExperts()
+
+ moe = MoE()
+ n = inject_packed_expert_lora(moe, r=2, alpha=2, device=torch.device("cpu"), dtype=torch.float32)
+ self.assertEqual(n, 1)
+ self.assertIsInstance(moe.experts, LoRAPackedExperts)
+
+
+if __name__ == "__main__":
+ unittest.main()