Skip to content

AirLLM 2.8T LLM inference with single 4GB GPU

docs: train from a JSONL file via --data

Yu Lib6f3d8a99b2f
diff --git a/README.md b/README.md
index e52a7e6..cf4f300 100644
--- a/README.md
+++ b/README.md
@@ -304,6 +304,50 @@ AirLLM can fine-tune huge models on a small GPU. Frozen base weights stream from
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).
+### 1. Prepare a dataset
+
+One JSON object per line (`.jsonl`). The usual field is `text` — next-token prediction over the whole string:
+
+```json
+{"text": "Your first training document. Can be a few sentences or a few paragraphs."}
+{"text": "Your second training document."}
+```
+
+Instruction pairs work too. Loss is applied on the completion only:
+
+```json
+{"prompt": "What is AirLLM?", "completion": "A library that runs and trains huge models on small VRAM."}
+{"instruction": "Translate to English", "input": "bonjour", "output": "hello"}
+```
+
+A `.txt` file is also fine: one example per blank-line-separated block. A two-line starter file lives at `air_llm/examples/sft_example.jsonl`.
+
+### 2. Run training
+
+From the repo root, point `--data` at your file:
+
+```bash
+python air_llm/examples/train_qwen38_flash_next_lora.py \
+ --data my_data.jsonl \
+ --seq-len 512 \
+ --epochs 1 \
+ --save-adapter qwen38-flash-next-lora.pt
+```
+
+For the 27B dense model:
+
+```bash
+python air_llm/examples/train_qwen38_lora.py \
+ --data my_data.jsonl \
+ --seq-len 512 \
+ --epochs 1 \
+ --save-adapter qwen38-27b-lora.pt
+```
+
+`--steps N` stops after N examples (useful for a smoke test). Omit `--data` and the script overfits a built-in snippet.
+
+### Python API
+
```python
from airllm import AirLLMLoRAQwen4Exp
@@ -332,20 +376,7 @@ 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)
-```
-
-Or run the example scripts from the repo root:
-
-```bash
-python air_llm/examples/train_qwen38_flash_next_lora.py --seq-len 512 --steps 1 --verbose
-python air_llm/examples/train_qwen38_lora.py --seq-len 512 --steps 1 --verbose
-```
+`AirLLMLoRA` is the same API for `Qwen/Qwen3.8-27B`.
## Acknowledgement
diff --git a/air_llm/airllm/lora_data.py b/air_llm/airllm/lora_data.py
new file mode 100644
index 0000000..ebafa72
--- /dev/null
+++ b/air_llm/airllm/lora_data.py
@@ -0,0 +1,151 @@
+"""Load a tiny SFT file for streamed LoRA (JSONL / JSON / TXT)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+
+def record_from_obj(obj) -> dict:
+ """Turn one JSON object (or a raw string) into ``{text, mask_prefix}``."""
+ if isinstance(obj, str):
+ text = obj.strip()
+ if not text:
+ raise ValueError("empty string example")
+ return {"text": text, "mask_prefix": None}
+ if not isinstance(obj, dict):
+ raise ValueError(f"expected a JSON object or string, got {type(obj).__name__}")
+
+ if obj.get("text"):
+ return {"text": str(obj["text"]), "mask_prefix": None}
+
+ prompt = obj.get("prompt") or obj.get("instruction") or ""
+ extra = obj.get("input") or ""
+ completion = obj.get("completion") or obj.get("output") or obj.get("response") or ""
+ if prompt or completion:
+ prefix_parts = [p for p in (str(prompt).strip(), str(extra).strip()) if p]
+ prefix = "\n".join(prefix_parts)
+ completion = str(completion)
+ if prefix and completion:
+ sep = "" if prefix.endswith(("\n", " ")) else "\n"
+ text = f"{prefix}{sep}{completion}"
+ else:
+ text = prefix or completion
+ if not text.strip():
+ raise ValueError("prompt/completion example is empty")
+ return {"text": text, "mask_prefix": prefix or None}
+
+ messages = obj.get("messages")
+ if isinstance(messages, list) and messages:
+ lines = []
+ last_assistant = None
+ for msg in messages:
+ role = (msg.get("role") or "user").strip()
+ content = (msg.get("content") or "").strip()
+ if not content:
+ continue
+ lines.append(f"{role}: {content}")
+ if role == "assistant":
+ last_assistant = content
+ if not lines:
+ raise ValueError("messages example is empty")
+ text = "\n".join(lines)
+ prefix = None
+ if last_assistant and text.endswith(last_assistant):
+ prefix = text[: -len(last_assistant)]
+ return {"text": text, "mask_prefix": prefix}
+
+ raise ValueError(
+ "each example needs `text`, or `prompt`/`completion`, "
+ "or `instruction`/`output`, or `messages`"
+ )
+
+
+def _load_json_blob(raw: str):
+ data = json.loads(raw)
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict):
+ for key in ("data", "examples", "rows"):
+ if isinstance(data.get(key), list):
+ return data[key]
+ return [data]
+ raise ValueError("JSON file must be an object, a list, or {\"data\": [...]}")
+
+
+def load_records(path) -> list:
+ """Load training examples from ``.jsonl``, ``.json``, or ``.txt``.
+
+ TXT is one example per blank-line-separated block (the whole file if there
+ are no blank lines).
+ """
+ p = Path(path)
+ if not p.is_file():
+ raise FileNotFoundError(p)
+ suffix = p.suffix.lower()
+ text = p.read_text(encoding="utf-8")
+ records = []
+ if suffix == ".txt":
+ blocks = [b.strip() for b in text.split("\n\n") if b.strip()]
+ for block in blocks:
+ records.append({"text": block, "mask_prefix": None})
+ elif suffix == ".json":
+ for i, obj in enumerate(_load_json_blob(text)):
+ try:
+ records.append(record_from_obj(obj))
+ except ValueError as e:
+ raise ValueError(f"{p}:{i}: {e}") from e
+ else:
+ # .jsonl and anything else: one JSON object per non-empty line
+ for i, line in enumerate(text.splitlines(), start=1):
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ try:
+ records.append(record_from_obj(json.loads(line)))
+ except ValueError as e:
+ raise ValueError(f"{p}:{i}: {e}") from e
+ except json.JSONDecodeError as e:
+ raise ValueError(f"{p}:{i}: invalid JSON ({e.msg})") from e
+ if not records:
+ raise ValueError(f"no examples in {p}")
+ return records
+
+
+def encode_record(tokenizer, record, seq_len, device):
+ """Tokenize one example. Prompt tokens are labeled ``-100`` when masked."""
+ encoded = tokenizer(
+ record["text"],
+ return_tensors="pt",
+ truncation=True,
+ max_length=seq_len,
+ )
+ input_ids = encoded["input_ids"].to(device)
+ attention_mask = encoded.get("attention_mask")
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(device)
+ labels = input_ids.clone()
+ prefix = record.get("mask_prefix")
+ if prefix:
+ pref = tokenizer(
+ prefix,
+ add_special_tokens=True,
+ truncation=True,
+ max_length=seq_len,
+ )
+ plen = len(pref["input_ids"])
+ plen = min(plen, max(input_ids.shape[1] - 1, 0))
+ if plen:
+ labels[:, :plen] = -100
+ return input_ids, attention_mask, labels
+
+
+def iter_train_items(records, epochs, steps=None):
+ """Yield ``(step, epoch, record)`` over ``epochs`` passes, optional step cap."""
+ step = 0
+ for epoch in range(epochs):
+ for rec in records:
+ if steps is not None and step >= steps:
+ return
+ yield step, epoch, rec
+ step += 1
diff --git a/air_llm/examples/sft_example.jsonl b/air_llm/examples/sft_example.jsonl
new file mode 100644
index 0000000..3f190c7
--- /dev/null
+++ b/air_llm/examples/sft_example.jsonl
@@ -0,0 +1,2 @@
+{"text": "AirLLM streams frozen decoder weights from disk one layer at a time so LoRA can train on a small GPU."}
+{"prompt": "What is AirLLM?", "completion": "A library that runs and trains huge language models on small VRAM by streaming one layer at a time."}
diff --git a/air_llm/examples/train_qwen38_flash_next_lora.py b/air_llm/examples/train_qwen38_flash_next_lora.py
index eb254cd..b8cf119 100644
--- a/air_llm/examples/train_qwen38_flash_next_lora.py
+++ b/air_llm/examples/train_qwen38_flash_next_lora.py
@@ -1,4 +1,4 @@
-"""Smoke-test streamed LoRA on Qwen3.8-Flash-Next (125B MoE + 51B PLE).
+"""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
@@ -8,7 +8,7 @@ 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
+ python air_llm/examples/train_qwen38_flash_next_lora.py --data my_data.jsonl --save-adapter out.pt
"""
import argparse
@@ -23,14 +23,30 @@ if _AIRLLM not in sys.path:
sys.path.insert(0, os.path.abspath(_AIRLLM))
from airllm.airllm_lora import AirLLMLoRAQwen4Exp
+from airllm.lora_data import encode_record, iter_train_items, load_records
+
+_FALLBACK = (
+ "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
def parse_args():
- p = argparse.ArgumentParser(description="AirLLM streamed LoRA smoke test (Qwen3.8-Flash-Next)")
+ p = argparse.ArgumentParser(description="AirLLM streamed LoRA (Qwen3.8-Flash-Next)")
+ p.add_argument("--data", default=None,
+ help="JSONL/JSON/TXT dataset (see README Training). Omit to overfit a built-in snippet.")
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("--epochs", type=int, default=1)
+ p.add_argument("--steps", type=int, default=None,
+ help="stop after N steps (default: all examples × epochs; 1 if --data is omitted)")
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)
@@ -51,9 +67,16 @@ def parse_args():
def main():
args = parse_args()
if not torch.cuda.is_available():
- print("CUDA is required for this smoke test.")
+ print("CUDA is required for this trainer.")
sys.exit(1)
+ if args.data:
+ records = load_records(args.data)
+ epochs, steps = args.epochs, args.steps
+ else:
+ records = [{"text": _FALLBACK, "mask_prefix": None}]
+ epochs, steps = (args.steps or 1), None
+
max_seq_len = args.max_seq_len or args.seq_len
trainer = AirLLMLoRAQwen4Exp(
args.model,
@@ -71,24 +94,7 @@ def main():
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)
+ print(f"examples={len(records)} epochs={epochs} seq_len={args.seq_len}", flush=True)
csv_f = None
if args.log_csv:
@@ -98,22 +104,30 @@ def main():
torch.cuda.reset_peak_memory_stats(trainer.device)
t0 = time.time()
- for step in range(args.steps):
+ n = 0
+ for step, epoch, rec in iter_train_items(records, epochs, steps):
+ input_ids, attention_mask, labels = encode_record(
+ tok, rec, args.seq_len, trainer.device)
loss = trainer.train_step(
- input_ids, attention_mask=attention_mask, verbose=args.verbose)
+ input_ids, labels=labels, 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"step {step} epoch {epoch} 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()
+ n += 1
if csv_f is not None:
csv_f.close()
+ if n == 0:
+ print("no training steps ran")
+ sys.exit(1)
+
if args.save_adapter:
trainer.save_adapter(args.save_adapter)
print(f"saved adapter to {args.save_adapter}")
diff --git a/air_llm/examples/train_qwen38_lora.py b/air_llm/examples/train_qwen38_lora.py
index 1da570f..cf17973 100644
--- a/air_llm/examples/train_qwen38_lora.py
+++ b/air_llm/examples/train_qwen38_lora.py
@@ -1,12 +1,11 @@
-"""Smoke-test streamed LoRA on Qwen3.8-27B and print peak VRAM.
+"""Streamed LoRA on Qwen3.8-27B.
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``.
+8GB target. This is not Hugging Face Trainer / bitsandbytes QLoRA.
Example::
- python examples/train_qwen38_lora.py --model Qwen/Qwen3.8-27B --seq-len 512 --steps 1
+ python air_llm/examples/train_qwen38_lora.py --data my_data.jsonl --save-adapter out.pt
"""
import argparse
@@ -20,14 +19,21 @@ if _AIRLLM not in sys.path:
sys.path.insert(0, os.path.abspath(_AIRLLM))
from airllm.airllm_lora import AirLLMLoRA
+from airllm.lora_data import encode_record, iter_train_items, load_records
+
+_FALLBACK = "AirLLM trains LoRA with one decoder layer on the GPU at a time. " * 256
def parse_args():
- p = argparse.ArgumentParser(description="AirLLM streamed LoRA smoke test (Qwen3.8-27B)")
+ p = argparse.ArgumentParser(description="AirLLM streamed LoRA (Qwen3.8-27B)")
+ p.add_argument("--data", default=None,
+ help="JSONL/JSON/TXT dataset (see README Training). Omit to overfit a built-in snippet.")
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("--epochs", type=int, default=1)
+ p.add_argument("--steps", type=int, default=None,
+ help="stop after N steps (default: all examples × epochs; 1 if --data is omitted)")
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)
@@ -42,9 +48,16 @@ def parse_args():
def main():
args = parse_args()
if not torch.cuda.is_available():
- print("CUDA is required for this smoke test.")
+ print("CUDA is required for this trainer.")
sys.exit(1)
+ if args.data:
+ records = load_records(args.data)
+ epochs, steps = args.epochs, args.steps
+ else:
+ records = [{"text": _FALLBACK, "mask_prefix": None}]
+ epochs, steps = (args.steps or 1), None
+
max_seq_len = args.max_seq_len or args.seq_len
trainer = AirLLMLoRA(
args.model,
@@ -60,20 +73,26 @@ def main():
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)
+ print(f"examples={len(records)} epochs={epochs} seq_len={args.seq_len}", flush=True)
torch.cuda.reset_peak_memory_stats(trainer.device)
- for step in range(args.steps):
+ n = 0
+ for step, epoch, rec in iter_train_items(records, epochs, steps):
+ input_ids, attention_mask, labels = encode_record(
+ tok, rec, args.seq_len, trainer.device)
loss = trainer.train_step(
- input_ids, attention_mask=attention_mask, verbose=args.verbose)
+ input_ids, labels=labels, 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)
+ print(
+ f"step {step} epoch {epoch} loss={loss:.4f} peak_vram={peak:.2f}GB "
+ f"seq={input_ids.shape[1]}",
+ flush=True,
+ )
+ n += 1
+
+ if n == 0:
+ print("no training steps ran")
+ sys.exit(1)
if args.save_adapter:
trainer.save_adapter(args.save_adapter)
diff --git a/air_llm/tests/test_lora_data.py b/air_llm/tests/test_lora_data.py
new file mode 100644
index 0000000..6414e60
--- /dev/null
+++ b/air_llm/tests/test_lora_data.py
@@ -0,0 +1,88 @@
+"""Dataset loading for streamed LoRA — no GPU or torch required."""
+
+import json
+import sys
+import tempfile
+import types
+import unittest
+from pathlib import Path
+
+_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.lora_data import iter_train_items, load_records, record_from_obj
+
+
+class TestRecordFromObj(unittest.TestCase):
+ def test_text(self):
+ rec = record_from_obj({"text": "hello world"})
+ self.assertEqual(rec["text"], "hello world")
+ self.assertIsNone(rec["mask_prefix"])
+
+ def test_prompt_completion(self):
+ rec = record_from_obj({"prompt": "Q?", "completion": "A."})
+ self.assertEqual(rec["text"], "Q?\nA.")
+ self.assertEqual(rec["mask_prefix"], "Q?")
+
+ def test_alpaca(self):
+ rec = record_from_obj({
+ "instruction": "Translate",
+ "input": "hola",
+ "output": "hello",
+ })
+ self.assertEqual(rec["text"], "Translate\nhola\nhello")
+ self.assertEqual(rec["mask_prefix"], "Translate\nhola")
+
+ def test_messages(self):
+ rec = record_from_obj({
+ "messages": [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello"},
+ ]
+ })
+ self.assertIn("user: Hi", rec["text"])
+ self.assertTrue(rec["text"].endswith("Hello"))
+ self.assertTrue(rec["mask_prefix"].endswith("assistant: "))
+
+
+class TestLoadRecords(unittest.TestCase):
+ def test_jsonl_and_txt(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ jsonl = Path(tmp) / "a.jsonl"
+ jsonl.write_text(
+ json.dumps({"text": "one"}) + "\n"
+ + json.dumps({"prompt": "Q", "completion": "A"}) + "\n",
+ encoding="utf-8",
+ )
+ recs = load_records(jsonl)
+ self.assertEqual(len(recs), 2)
+ self.assertEqual(recs[0]["text"], "one")
+
+ txt = Path(tmp) / "b.txt"
+ txt.write_text("first block\n\nsecond block\n", encoding="utf-8")
+ recs = load_records(txt)
+ self.assertEqual([r["text"] for r in recs], ["first block", "second block"])
+
+ def test_json_list(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "a.json"
+ path.write_text(json.dumps([{"text": "x"}, "y"]), encoding="utf-8")
+ recs = load_records(path)
+ self.assertEqual([r["text"] for r in recs], ["x", "y"])
+
+
+class TestIterTrainItems(unittest.TestCase):
+ def test_epochs_and_step_cap(self):
+ recs = [{"text": "a"}, {"text": "b"}]
+ items = list(iter_train_items(recs, epochs=2))
+ self.assertEqual(len(items), 4)
+ capped = list(iter_train_items(recs, epochs=9, steps=3))
+ self.assertEqual([s for s, _, _ in capped], [0, 1, 2])
+
+
+if __name__ == "__main__":
+ unittest.main()