bantamtrain 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/PKG-INFO +27 -4
  2. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/README.md +22 -3
  3. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/__init__.py +2 -2
  4. bantamtrain-0.2.0/bantamtrain/finetune.py +452 -0
  5. bantamtrain-0.2.0/bantamtrain/lora.py +130 -0
  6. bantamtrain-0.2.0/bantamtrain/losses.py +35 -0
  7. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/memory.py +47 -0
  8. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/models/gpt.py +11 -2
  9. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/optim.py +32 -6
  10. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/qweights.py +55 -10
  11. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain.egg-info/PKG-INFO +27 -4
  12. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain.egg-info/SOURCES.txt +3 -0
  13. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain.egg-info/requires.txt +5 -0
  14. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/pyproject.toml +2 -1
  15. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/LICENSE +0 -0
  16. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/data/__init__.py +0 -0
  17. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/data/dedup.py +0 -0
  18. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/data/gridpack.py +0 -0
  19. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/data/tokpack.py +0 -0
  20. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/device.py +0 -0
  21. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/lowmem.py +0 -0
  22. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/models/__init__.py +0 -0
  23. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/models/vit_weather.py +0 -0
  24. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/weightpack.py +0 -0
  25. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain/zoom.py +0 -0
  26. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain.egg-info/dependency_links.txt +0 -0
  27. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/bantamtrain.egg-info/top_level.txt +0 -0
  28. {bantamtrain-0.1.0 → bantamtrain-0.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bantamtrain
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Bantam: train small language models and weather models faster and cheaper on limited compute - Zoom Training, Muon, 8-bit/bf16 low-memory training, int8/int4 weights, compressed token and weather-grid stores
5
5
  Author: Nathan
6
6
  License-Expression: MIT
@@ -22,6 +22,10 @@ Provides-Extra: data
22
22
  Requires-Dist: tokenizers; extra == "data"
23
23
  Requires-Dist: pyarrow; extra == "data"
24
24
  Requires-Dist: huggingface_hub; extra == "data"
25
+ Provides-Extra: finetune
26
+ Requires-Dist: transformers>=4.40; extra == "finetune"
27
+ Requires-Dist: datasets; extra == "finetune"
28
+ Requires-Dist: sentencepiece; extra == "finetune"
25
29
  Provides-Extra: weather
26
30
  Requires-Dist: xarray; extra == "weather"
27
31
  Requires-Dist: zarr; extra == "weather"
@@ -59,6 +63,9 @@ pip install bantamtrain
59
63
  | `bantamtrain.device` | runtime: flush-to-zero on CPU, AMP, TF32, compile, batch finder, duty-cycle limiter | the FTZ fix made affected CPU matmuls up to 23x faster |
60
64
  | `bantamtrain.memory` | memory / time scoreboard for single-GPU training | `python -m bantamtrain.memory` |
61
65
  | `bantamtrain.models` | `ZoomGPT` (decoder LM) and `ZoomViT` (weather grid forecaster) with every option above | |
66
+ | `bantamtrain.lora` | LoRA / QLoRA adapters on `nn.Linear` or int8 / NF4 / int4 `QLinear` bases; merge, adapter-only state dicts | |
67
+ | `bantamtrain.losses` | chunked cross-entropy: never materializes the tokens x vocab logits | |
68
+ | `bantamtrain.finetune` | `python -m bantamtrain.finetune`: SFT of any HuggingFace causal LM (chat templates, response-only loss, best-fit packing), Muon + 8-bit state, torchrun DDP | SmolLM2-135M QLoRA on Dolly: held-out loss 3.39 -> 3.18 in 40 CPU steps |
62
69
 
63
70
  ## Quick start
64
71
 
@@ -89,6 +96,22 @@ weightpack.save("model.zwpk", model.state_dict(), bits=8) # int8 checkpoint f
89
96
  qweights.quantize_model(model, bits=4) # int4 weights in RAM, float compute
90
97
  ```
91
98
 
99
+ Fine-tune a HuggingFace model (LoRA on an int8 / NF4 base, Muon, 8-bit state):
100
+
101
+ ```bash
102
+ pip install bantamtrain[finetune]
103
+ python -m bantamtrain.finetune --model HuggingFaceTB/SmolLM2-135M \
104
+ --dataset databricks/databricks-dolly-15k --max_examples 2000 \
105
+ --lora 16 --quant 8 --optim muon --state_bits 8 --epochs 1 --out runs/dolly
106
+ torchrun --nproc_per_node 4 -m bantamtrain.finetune ... # multi-GPU
107
+ python -m bantamtrain.memory --finetune --params 7e9 --gpu_gb 24 # will it fit?
108
+ ```
109
+
110
+ Measured on SmolLM2-135M before training (100 held-out Dolly examples): int8
111
+ base costs +0.003 loss (558 -> 200 MB), NF4 linears with int8 embeddings
112
+ +0.18 (140 MB). Use int8 for small bases; NF4 for 7B+ where the literature
113
+ finds it near-lossless.
114
+
92
115
  Size a run on one GPU:
93
116
 
94
117
  ```bash
@@ -97,9 +120,9 @@ python -m bantamtrain.memory --params 5e9 --gpu_gb 96 --tokens 1e11
97
120
 
98
121
  ## Honest notes
99
122
 
100
- - Muon, 8-bit optimizer state, stochastic-rounding bf16 and blockwise weight
101
- quantization are published techniques re-implemented here; Zoom Training and
102
- the storage formats are this project's own.
123
+ - Muon, 8-bit optimizer state, stochastic-rounding bf16, LoRA/QLoRA/NF4 and
124
+ blockwise weight quantization are published techniques re-implemented here;
125
+ Zoom Training and the storage formats are this project's own.
103
126
  - All quality numbers above were measured on a 5.8M-parameter model; gains at
104
127
  larger scale are expected to be smaller for the optimizer and are untested for
105
128
  Zoom. Nothing has been run on a GPU yet.
@@ -26,6 +26,9 @@ pip install bantamtrain
26
26
  | `bantamtrain.device` | runtime: flush-to-zero on CPU, AMP, TF32, compile, batch finder, duty-cycle limiter | the FTZ fix made affected CPU matmuls up to 23x faster |
27
27
  | `bantamtrain.memory` | memory / time scoreboard for single-GPU training | `python -m bantamtrain.memory` |
28
28
  | `bantamtrain.models` | `ZoomGPT` (decoder LM) and `ZoomViT` (weather grid forecaster) with every option above | |
29
+ | `bantamtrain.lora` | LoRA / QLoRA adapters on `nn.Linear` or int8 / NF4 / int4 `QLinear` bases; merge, adapter-only state dicts | |
30
+ | `bantamtrain.losses` | chunked cross-entropy: never materializes the tokens x vocab logits | |
31
+ | `bantamtrain.finetune` | `python -m bantamtrain.finetune`: SFT of any HuggingFace causal LM (chat templates, response-only loss, best-fit packing), Muon + 8-bit state, torchrun DDP | SmolLM2-135M QLoRA on Dolly: held-out loss 3.39 -> 3.18 in 40 CPU steps |
29
32
 
30
33
  ## Quick start
31
34
 
@@ -56,6 +59,22 @@ weightpack.save("model.zwpk", model.state_dict(), bits=8) # int8 checkpoint f
56
59
  qweights.quantize_model(model, bits=4) # int4 weights in RAM, float compute
57
60
  ```
58
61
 
62
+ Fine-tune a HuggingFace model (LoRA on an int8 / NF4 base, Muon, 8-bit state):
63
+
64
+ ```bash
65
+ pip install bantamtrain[finetune]
66
+ python -m bantamtrain.finetune --model HuggingFaceTB/SmolLM2-135M \
67
+ --dataset databricks/databricks-dolly-15k --max_examples 2000 \
68
+ --lora 16 --quant 8 --optim muon --state_bits 8 --epochs 1 --out runs/dolly
69
+ torchrun --nproc_per_node 4 -m bantamtrain.finetune ... # multi-GPU
70
+ python -m bantamtrain.memory --finetune --params 7e9 --gpu_gb 24 # will it fit?
71
+ ```
72
+
73
+ Measured on SmolLM2-135M before training (100 held-out Dolly examples): int8
74
+ base costs +0.003 loss (558 -> 200 MB), NF4 linears with int8 embeddings
75
+ +0.18 (140 MB). Use int8 for small bases; NF4 for 7B+ where the literature
76
+ finds it near-lossless.
77
+
59
78
  Size a run on one GPU:
60
79
 
61
80
  ```bash
@@ -64,9 +83,9 @@ python -m bantamtrain.memory --params 5e9 --gpu_gb 96 --tokens 1e11
64
83
 
65
84
  ## Honest notes
66
85
 
67
- - Muon, 8-bit optimizer state, stochastic-rounding bf16 and blockwise weight
68
- quantization are published techniques re-implemented here; Zoom Training and
69
- the storage formats are this project's own.
86
+ - Muon, 8-bit optimizer state, stochastic-rounding bf16, LoRA/QLoRA/NF4 and
87
+ blockwise weight quantization are published techniques re-implemented here;
88
+ Zoom Training and the storage formats are this project's own.
70
89
  - All quality numbers above were measured on a 5.8M-parameter model; gains at
71
90
  larger scale are expected to be smaller for the optimizer and are untested for
72
91
  Zoom. Nothing has been run on a GPU yet.
@@ -1,4 +1,4 @@
1
- """bantamtrain (Bantam): train small LLMs and weather models faster on limited compute.
1
+ """bantamtrain: train small LLMs and weather models faster on limited compute.
2
2
 
3
3
  Components
4
4
  zoom - Zoom Training (coarse-to-fine resolution annealing), schedules
@@ -9,4 +9,4 @@ Components
9
9
  """
10
10
  from .zoom import SlotMerge, SlotUnmerge, ZoomSchedule, lr_at # noqa: F401
11
11
 
12
- __version__ = "0.1.0"
12
+ __version__ = "0.2.0"
@@ -0,0 +1,452 @@
1
+ """Fine-tune any HuggingFace causal LM with the Bantam stack.
2
+
3
+ python -m bantamtrain.finetune --model HuggingFaceTB/SmolLM2-135M \
4
+ --dataset databricks/databricks-dolly-15k --max_examples 2000 \
5
+ --lora 16 --quant 4 --optim muon --state_bits 8 --epochs 1 --out runs/dolly
6
+
7
+ What it gives you
8
+ * LoRA / QLoRA: frozen base (optionally int8/int4 blockwise, bantamtrain.qweights)
9
+ + trainable low-rank adapters; or full fine-tuning (--lora 0).
10
+ * Muon (hidden matrices) + 8-bit optimizer state + bf16 weights with
11
+ stochastic rounding; chunked cross-entropy so a 32k-128k vocabulary never
12
+ materializes the full logits; activation checkpointing; grad accumulation.
13
+ * SFT data from a HuggingFace dataset or a local JSONL: prompt/response
14
+ columns, Dolly-style instruction/context/response, or chat `messages`.
15
+ Uses the tokenizer's chat template when it has one; the loss is computed
16
+ on response tokens only; examples are packed into fixed windows.
17
+ * Multi-GPU with torchrun (DistributedDataParallel), resumable JSON logs,
18
+ adapter-only checkpoints (MBs) and an optional merged save_pretrained().
19
+ """
20
+ import torch
21
+
22
+ torch.set_flush_denormal(True)
23
+
24
+ import argparse # noqa: E402
25
+ import json # noqa: E402
26
+ import math # noqa: E402
27
+ import os # noqa: E402
28
+ import random # noqa: E402
29
+ import time # noqa: E402
30
+
31
+ from .device import DutyCycleLimiter, describe, setup_runtime # noqa: E402
32
+ from .lora import apply_lora, lora_state_dict, merge_lora, unwrap_lora # noqa: E402
33
+ from .losses import chunked_cross_entropy # noqa: E402
34
+ from .lowmem import state_bytes # noqa: E402
35
+ from .optim import build_optimizer # noqa: E402
36
+ from .qweights import model_bytes, quantize_model # noqa: E402
37
+ from .zoom import lr_at # noqa: E402
38
+
39
+ DEFAULT_TARGETS = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
40
+ "c_attn", "c_proj", "c_fc", "query_key_value", "dense", "dense_h_to_4h",
41
+ "dense_4h_to_h", "qkv", "proj", "fc", "fc_out", "wq", "wk", "wv", "wo",
42
+ "w1", "w2", "w3")
43
+
44
+
45
+ # ----------------------------------------------------------------------------- data
46
+ def load_examples(args):
47
+ """Return a list of dicts with either {'prompt','response'} or {'messages'}."""
48
+ rows = []
49
+ if args.jsonl:
50
+ with open(args.jsonl) as f:
51
+ rows = [json.loads(l) for l in f if l.strip()]
52
+ else:
53
+ from datasets import load_dataset
54
+ ds = load_dataset(args.dataset, args.config or None, split=args.split)
55
+ rows = [dict(r) for r in ds]
56
+ if args.max_examples:
57
+ random.Random(args.seed).shuffle(rows)
58
+ rows = rows[:args.max_examples]
59
+ out = []
60
+ for r in rows:
61
+ if args.messages_col in r and r[args.messages_col]:
62
+ out.append({"messages": r[args.messages_col]})
63
+ continue
64
+ resp = r.get(args.response_col) or r.get("output") or r.get("completion")
65
+ prompt = r.get(args.prompt_col) or r.get("instruction") or r.get("question")
66
+ if not resp or not prompt:
67
+ continue
68
+ ctx = r.get("context") or r.get("input")
69
+ if ctx:
70
+ prompt = f"{prompt}\n\n{ctx}"
71
+ out.append({"prompt": prompt, "response": resp})
72
+ return out
73
+
74
+
75
+ CHATML = ("{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\n' + "
76
+ "message['content'] + '<|im_end|>' + '\n' }}{% endfor %}"
77
+ "{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}")
78
+
79
+
80
+ def resolve_template(tok):
81
+ """Base checkpoints have no chat template: install ChatML when the vocab has its
82
+ tokens (SmolLM2, Qwen2.5 bases) and align eos with the end-of-turn token."""
83
+ if getattr(tok, "chat_template", None):
84
+ return "model"
85
+ if "<|im_end|>" in tok.get_vocab():
86
+ tok.chat_template = CHATML
87
+ tok.eos_token = "<|im_end|>"
88
+ return "chatml-installed"
89
+ return "plain"
90
+
91
+
92
+ def to_messages(ex):
93
+ if "messages" in ex:
94
+ return ex["messages"]
95
+ return [{"role": "user", "content": ex["prompt"]},
96
+ {"role": "assistant", "content": ex["response"]}]
97
+
98
+
99
+ def render(tok, ex):
100
+ """-> (prompt_text, full_text) using the chat template when available."""
101
+ has_tpl = getattr(tok, "chat_template", None) is not None
102
+ if "messages" in ex:
103
+ msgs = ex["messages"]
104
+ if has_tpl:
105
+ prompt = tok.apply_chat_template(msgs[:-1], tokenize=False, add_generation_prompt=True)
106
+ full = tok.apply_chat_template(msgs, tokenize=False)
107
+ else:
108
+ prompt = "".join(f"{m['role']}: {m['content']}\n" for m in msgs[:-1]) + "assistant: "
109
+ full = prompt + msgs[-1]["content"] + (tok.eos_token or "")
110
+ return prompt, full
111
+ if has_tpl:
112
+ msgs = [{"role": "user", "content": ex["prompt"]}]
113
+ prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
114
+ full = tok.apply_chat_template(msgs + [{"role": "assistant", "content": ex["response"]}],
115
+ tokenize=False)
116
+ else:
117
+ prompt = f"### Instruction:\n{ex['prompt']}\n\n### Response:\n"
118
+ full = prompt + ex["response"] + (tok.eos_token or "")
119
+ return prompt, full
120
+
121
+
122
+ def _assistant_mask(tok, msgs):
123
+ """Use the template's {% generation %} blocks when it has them; else None."""
124
+ try:
125
+ enc = tok.apply_chat_template(msgs, tokenize=True, return_dict=True,
126
+ return_assistant_tokens_mask=True,
127
+ add_generation_prompt=False)
128
+ except Exception:
129
+ return None
130
+ mask = enc.get("assistant_masks")
131
+ if not mask or sum(mask) == 0:
132
+ return None
133
+ return enc["input_ids"], mask
134
+
135
+
136
+ def tokenize_examples(tok, examples, seq, prompt_loss_weight=0.0):
137
+ """-> list of (ids, labels, weights): labels = -100 on prompt tokens unless
138
+ prompt_loss_weight > 0, in which case prompt tokens get that weight and
139
+ response tokens weight 1. Multi-turn chats get every assistant turn supervised
140
+ when the template marks generation spans; otherwise the final turn only."""
141
+ items = []
142
+ for ex in examples:
143
+ msgs = to_messages(ex)
144
+ am = _assistant_mask(tok, msgs) if getattr(tok, "chat_template", None) else None
145
+ if am is not None:
146
+ f_ids, mask = am
147
+ f_ids, mask = f_ids[:seq], mask[:seq]
148
+ sup = [bool(m) for m in mask]
149
+ else:
150
+ prompt, full = render(tok, ex)
151
+ p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
152
+ f_ids = tok(full, add_special_tokens=False)["input_ids"]
153
+ p_len = len(p_ids) if f_ids[:len(p_ids)] == p_ids else min(len(p_ids), len(f_ids) - 1)
154
+ f_ids = f_ids[:seq]
155
+ sup = [i >= p_len for i in range(len(f_ids))]
156
+ if not any(sup):
157
+ continue
158
+ labels = [t if s_ or prompt_loss_weight > 0 else -100 for t, s_ in zip(f_ids, sup)]
159
+ weights = [1.0 if s_ else prompt_loss_weight for s_ in sup]
160
+ items.append((f_ids, labels, weights))
161
+ return items
162
+
163
+
164
+ def _pad(x, y, w, n, pad_id):
165
+ k = n - len(x)
166
+ return x + [pad_id] * k, y + [-100] * k, w + [0.0] * k
167
+
168
+
169
+ def pack(items, seq, pad_id, mode="bfd"):
170
+ """Group tokenized examples into windows of seq+1 tokens.
171
+
172
+ mode="bfd": best-fit-decreasing bin packing, examples never split (TRL default)
173
+ mode="wrapped": concatenate everything and cut every seq tokens (may split examples)
174
+ mode="none": one example per window, padded
175
+ Each window is (ids, labels, weights) of length seq+1 (inputs = [:-1], targets = [1:]).
176
+ """
177
+ n = seq + 1
178
+ items = [t for t in items if len(t[0]) >= 2]
179
+ if mode != "wrapped": # one example per bin: truncate to fit
180
+ items = [(i[:n], l[:n], w[:n]) for i, l, w in items]
181
+ if mode == "wrapped":
182
+ ids, labels, ws = [], [], []
183
+ for i, l, w in items:
184
+ ids += i
185
+ labels += l
186
+ ws += w
187
+ out = []
188
+ for s in range(0, len(ids) - 1, seq):
189
+ x, y, w = ids[s:s + n], labels[s:s + n], ws[s:s + n]
190
+ out.append(_pad(x, y, w, n, pad_id))
191
+ return out
192
+ if mode == "none":
193
+ return [_pad(i, l, w, n, pad_id) for i, l, w in items]
194
+ bins = [] # best-fit decreasing
195
+ for i, l, w in sorted(items, key=lambda t: -len(t[0])):
196
+ best, best_left = None, None
197
+ for b in bins:
198
+ left = n - b["len"]
199
+ if len(i) <= left and (best_left is None or left < best_left):
200
+ best, best_left = b, left
201
+ if best is None:
202
+ best = {"len": 0, "x": [], "y": [], "w": []}
203
+ bins.append(best)
204
+ best["x"] += i
205
+ best["y"] += l
206
+ best["w"] += w
207
+ best["len"] += len(i)
208
+ return [_pad(b["x"], b["y"], b["w"], n, pad_id) for b in bins]
209
+
210
+
211
+ # ----------------------------------------------------------------------------- model
212
+ def lm_loss(model, x, y, ce_chunk, w=None):
213
+ """Mean CE over supervised tokens (optionally weighted); chunked head when the
214
+ model exposes base + output embeddings."""
215
+ if w is not None and bool((w != 1.0).logical_and(y != -100).any()):
216
+ logits = model(input_ids=x).logits.float()
217
+ per = torch.nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]),
218
+ y.reshape(-1), ignore_index=-100, reduction="none")
219
+ wf = w.reshape(-1).float()
220
+ return (per * wf).sum() / wf[y.reshape(-1) != -100].sum().clamp_min(1)
221
+ base = getattr(model, "model", None) or getattr(model, "base_model", None)
222
+ head = model.get_output_embeddings() if hasattr(model, "get_output_embeddings") else None
223
+ if ce_chunk and base is not None and head is not None and hasattr(head, "weight"):
224
+ h = base(input_ids=x).last_hidden_state
225
+ bias = getattr(head, "bias", None)
226
+ return chunked_cross_entropy(h, head.weight, y, ce_chunk, bias=bias)
227
+ logits = model(input_ids=x).logits.float()
228
+ return torch.nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]), y.reshape(-1),
229
+ ignore_index=-100)
230
+
231
+
232
+ @torch.no_grad()
233
+ def evaluate(model, windows, rt, batch, ce_chunk):
234
+ model.eval()
235
+ tot, n = 0.0, 0
236
+ for i in range(0, len(windows), batch):
237
+ xs = torch.tensor([w[0] for w in windows[i:i + batch]], device=rt.device)
238
+ ys = torch.tensor([w[1] for w in windows[i:i + batch]], device=rt.device)
239
+ with rt.autocast():
240
+ loss = lm_loss(model, xs[:, :-1], ys[:, 1:], ce_chunk) # eval: response tokens only
241
+ nv = int((ys[:, 1:] != -100).sum())
242
+ tot += loss.float().item() * nv
243
+ n += nv
244
+ model.train()
245
+ return tot / max(n, 1)
246
+
247
+
248
+ def main(argv=None):
249
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
250
+ ap.add_argument("--model", required=True, help="HF model id or local path")
251
+ ap.add_argument("--dataset", default="", help="HF dataset id")
252
+ ap.add_argument("--config", default="")
253
+ ap.add_argument("--split", default="train")
254
+ ap.add_argument("--jsonl", default="", help="local JSONL instead of --dataset")
255
+ ap.add_argument("--prompt_col", default="prompt")
256
+ ap.add_argument("--response_col", default="response")
257
+ ap.add_argument("--messages_col", default="messages")
258
+ ap.add_argument("--max_examples", type=int, default=0)
259
+ ap.add_argument("--eval_frac", type=float, default=0.05)
260
+ ap.add_argument("--seq", type=int, default=512)
261
+ ap.add_argument("--pack", default="bfd", choices=["bfd", "wrapped", "none"])
262
+ ap.add_argument("--prompt_loss_weight", type=float, default=0.0,
263
+ help="0 = loss on response tokens only (default); 1 = train on everything")
264
+ ap.add_argument("--epochs", type=float, default=1.0)
265
+ ap.add_argument("--max_steps", type=int, default=0)
266
+ ap.add_argument("--batch", type=int, default=4)
267
+ ap.add_argument("--accum", type=int, default=1)
268
+ ap.add_argument("--lr", type=float, default=2e-4)
269
+ ap.add_argument("--warmup", type=float, default=0.03)
270
+ ap.add_argument("--sched", default="wsd", choices=["cosine", "wsd"])
271
+ ap.add_argument("--wd", type=float, default=0.0)
272
+ ap.add_argument("--optim", default="adamw", choices=["adamw", "muon"])
273
+ ap.add_argument("--muon_lora", type=int, default=0, help="also put LoRA matrices on Muon")
274
+ ap.add_argument("--ns", default="quintic", choices=["quintic", "polar"])
275
+ ap.add_argument("--state_bits", type=int, default=8, choices=[32, 8])
276
+ ap.add_argument("--param_dtype", default="auto", choices=["auto", "fp32", "bf16"])
277
+ ap.add_argument("--lora", type=int, default=16, help="LoRA rank (0 = full fine-tuning)")
278
+ ap.add_argument("--lora_alpha", type=float, default=32)
279
+ ap.add_argument("--lora_dropout", type=float, default=0.05)
280
+ ap.add_argument("--lora_targets", default="", help="comma list; default: all projections")
281
+ ap.add_argument("--rslora", type=int, default=-1, help="-1: auto (on when r >= 64)")
282
+ ap.add_argument("--quant", default="0", choices=["0", "8", "4", "nf4"],
283
+ help="quantize the frozen base: 8, 4 (linear int4) or nf4 (QLoRA codebook)")
284
+ ap.add_argument("--embed_quant", default="8", choices=["same", "8", "none"],
285
+ help="embeddings / output head: int8 (default), same as --quant, or float")
286
+ ap.add_argument("--eval_only", type=int, default=0, help="evaluate the held-out loss and exit")
287
+ ap.add_argument("--grad_ckpt", type=int, default=0)
288
+ ap.add_argument("--ce_chunk", type=int, default=2048)
289
+ ap.add_argument("--eval_every", type=int, default=50)
290
+ ap.add_argument("--device", default="auto")
291
+ ap.add_argument("--precision", default="auto")
292
+ ap.add_argument("--threads", type=int, default=4)
293
+ ap.add_argument("--duty", type=float, default=1.0)
294
+ ap.add_argument("--seed", type=int, default=0)
295
+ ap.add_argument("--out", required=True)
296
+ ap.add_argument("--save_merged", type=int, default=0, help="also save_pretrained() the merged model")
297
+ args = ap.parse_args(argv)
298
+
299
+ # ---- distributed (torchrun) ----
300
+ world = int(os.environ.get("WORLD_SIZE", "1"))
301
+ rank = int(os.environ.get("RANK", "0"))
302
+ if world > 1:
303
+ import torch.distributed as dist
304
+ dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo")
305
+ if torch.cuda.is_available():
306
+ torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", "0")))
307
+ is_main = rank == 0
308
+ rt = setup_runtime(args.device, args.precision, False, args.threads, args.seed + rank)
309
+ if rt.device.type == "cpu":
310
+ rt.amp_dtype = None
311
+ os.makedirs(args.out, exist_ok=True)
312
+
313
+ from transformers import AutoModelForCausalLM, AutoTokenizer
314
+ tok = AutoTokenizer.from_pretrained(args.model)
315
+ template = resolve_template(tok)
316
+ if tok.pad_token_id is None:
317
+ tok.pad_token = tok.eos_token
318
+ pdt = args.param_dtype
319
+ if pdt == "auto":
320
+ pdt = "bf16" if (rt.device.type == "cuda" or args.lora == 0) else "fp32"
321
+ model = AutoModelForCausalLM.from_pretrained(
322
+ args.model, dtype=torch.bfloat16 if pdt == "bf16" else torch.float32)
323
+ base_bytes_fp = model_bytes(model)
324
+ report = {}
325
+ quant = {"0": 0, "8": 8, "4": 4, "nf4": "nf4"}[str(args.quant)]
326
+ if quant:
327
+ eq = {"same": "same", "8": 8, "none": None}[args.embed_quant]
328
+ report["quant"] = quantize_model(model, quant, min_numel=1 << 16, embed_bits=eq)
329
+ if args.lora:
330
+ targets = tuple(t for t in args.lora_targets.split(",") if t) or DEFAULT_TARGETS
331
+ rslora = (args.lora >= 64) if args.rslora < 0 else bool(args.rslora)
332
+ report["lora"] = apply_lora(model, args.lora, args.lora_alpha, args.lora_dropout,
333
+ targets, rslora=rslora)
334
+ assert report["lora"]["wrapped"] > 0, "no LoRA targets matched; use --lora_targets"
335
+ else:
336
+ for p in model.parameters():
337
+ p.requires_grad_(True)
338
+ if args.grad_ckpt and hasattr(model, "gradient_checkpointing_enable"):
339
+ model.gradient_checkpointing_enable()
340
+ if hasattr(model, "enable_input_require_grads"):
341
+ model.enable_input_require_grads()
342
+ model.to(rt.device)
343
+ model.train()
344
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
345
+ opt = build_optimizer(model, args.optim, args.lr, args.wd, state_bits=args.state_bits,
346
+ ns=args.ns, muon_lora=bool(args.muon_lora))
347
+ fwd_model = model
348
+ if world > 1:
349
+ from torch.nn.parallel import DistributedDataParallel as DDP
350
+ fwd_model = DDP(model, device_ids=[rt.device.index] if rt.device.type == "cuda" else None,
351
+ gradient_as_bucket_view=True)
352
+
353
+ # ---- data ----
354
+ examples = load_examples(args)
355
+ items = tokenize_examples(tok, examples, args.seq, args.prompt_loss_weight)
356
+ random.Random(args.seed).shuffle(items)
357
+ n_eval = max(1, int(len(items) * args.eval_frac))
358
+ eval_w = pack(items[:n_eval], args.seq, tok.pad_token_id, args.pack)
359
+ train_w = pack(items[n_eval:], args.seq, tok.pad_token_id, args.pack)
360
+ n_sup = sum(1 for w in train_w for t in w[1][1:] if t != -100)
361
+ pad_frac = sum(w[0].count(tok.pad_token_id) for w in train_w) / max(1, len(train_w) * (args.seq + 1))
362
+ train_w = train_w[rank::world]
363
+ steps_per_epoch = max(1, len(train_w) // (args.batch * args.accum))
364
+ total_steps = args.max_steps or max(1, int(steps_per_epoch * args.epochs))
365
+ limiter = DutyCycleLimiter(args.duty, rt.device)
366
+
367
+ n_quant = sum(m.q.numel() * (2 if getattr(m, "bits", 8) in (4, "nf4") else 1)
368
+ for m in model.modules() if hasattr(m, "q") and hasattr(m, "s"))
369
+ log = {"args": vars(args), "report": report, "trainable_params": trainable,
370
+ "total_params": sum(p.numel() for p in model.parameters()) + n_quant,
371
+ "quantized_base_params": n_quant,
372
+ "model_bytes_before_quant": base_bytes_fp, "model_bytes": model_bytes(model),
373
+ "optimizer_state_bytes": state_bytes(opt), "train_windows": len(train_w) * world,
374
+ "eval_windows": len(eval_w), "examples": len(items), "steps": total_steps,
375
+ "chat_template": template, "supervised_tokens": n_sup, "padding_fraction": pad_frac,
376
+ "world_size": world, "runtime": describe(rt), "evals": [], "train": []}
377
+ if is_main:
378
+ print(f"[finetune] {args.model} trainable={trainable/1e6:.2f}M "
379
+ f"model={log['model_bytes']/1e6:.0f}MB state={log['optimizer_state_bytes']/1e6:.0f}MB "
380
+ f"windows={len(train_w)*world} steps={total_steps} {describe(rt)}", flush=True)
381
+ ev = evaluate(model, eval_w, rt, args.batch, args.ce_chunk)
382
+ log["evals"].append({"step": 0, "eval_loss": ev})
383
+ print(f" step 0 eval={ev:.4f}", flush=True)
384
+ if args.eval_only:
385
+ log["final_eval_loss"] = ev
386
+ with open(os.path.join(args.out, "log.json"), "w") as f:
387
+ json.dump(log, f, indent=1)
388
+ return
389
+
390
+ rng = random.Random(args.seed + rank)
391
+ order = list(range(len(train_w)))
392
+ rng.shuffle(order)
393
+ pos, t_train = 0, 0.0
394
+ for step in range(1, total_steps + 1):
395
+ for g in opt.param_groups:
396
+ g["lr"] = lr_at(step / total_steps, args.lr, warmup=args.warmup, sched=args.sched)
397
+ t0 = time.perf_counter()
398
+ opt.zero_grad(set_to_none=True)
399
+ loss_acc = 0.0
400
+ for a in range(args.accum):
401
+ if pos + args.batch > len(order):
402
+ rng.shuffle(order)
403
+ pos = 0
404
+ idx = order[pos:pos + args.batch]
405
+ pos += args.batch
406
+ xs = torch.tensor([train_w[i][0] for i in idx], device=rt.device)
407
+ ys = torch.tensor([train_w[i][1] for i in idx], device=rt.device)
408
+ ws = torch.tensor([train_w[i][2] for i in idx], device=rt.device)
409
+ with rt.autocast():
410
+ loss = lm_loss(fwd_model, xs[:, :-1], ys[:, 1:], args.ce_chunk, ws[:, 1:]) / args.accum
411
+ rt.backward(loss, opt, [p for p in model.parameters() if p.requires_grad], step=False)
412
+ loss_acc += loss.float().item()
413
+ rt.step(opt, [p for p in model.parameters() if p.requires_grad])
414
+ dt = time.perf_counter() - t0
415
+ t_train += dt
416
+ limiter(dt)
417
+ if is_main and (step % 10 == 0 or step == 1):
418
+ log["train"].append({"step": step, "loss": loss_acc, "time": t_train})
419
+ print(f" step {step}/{total_steps} loss={loss_acc:.4f} {dt:.1f}s", flush=True)
420
+ if is_main and args.eval_every and (step % args.eval_every == 0 or step == total_steps):
421
+ ev = evaluate(model, eval_w, rt, args.batch, args.ce_chunk)
422
+ log["evals"].append({"step": step, "eval_loss": ev, "time": t_train})
423
+ print(f" step {step} eval={ev:.4f}", flush=True)
424
+ with open(os.path.join(args.out, "log.json"), "w") as f:
425
+ json.dump(log, f, indent=1)
426
+
427
+ if is_main:
428
+ log["train_time"] = t_train
429
+ log["optimizer_state_bytes"] = state_bytes(opt) # allocated lazily at step 1
430
+ log["final_eval_loss"] = log["evals"][-1]["eval_loss"]
431
+ if args.lora:
432
+ torch.save(lora_state_dict(model), os.path.join(args.out, "adapter.pt"))
433
+ log["adapter_bytes"] = os.path.getsize(os.path.join(args.out, "adapter.pt"))
434
+ else:
435
+ model.save_pretrained(os.path.join(args.out, "model"))
436
+ if args.save_merged and args.lora and not quant:
437
+ merge_lora(model)
438
+ unwrap_lora(model)
439
+ model.save_pretrained(os.path.join(args.out, "merged"))
440
+ tok.save_pretrained(os.path.join(args.out, "merged"))
441
+ with open(os.path.join(args.out, "log.json"), "w") as f:
442
+ json.dump(log, f, indent=1)
443
+ print(f"[finetune] done: eval {log['evals'][0]['eval_loss']:.4f} -> "
444
+ f"{log['final_eval_loss']:.4f} in {t_train:.0f}s", flush=True)
445
+ if world > 1:
446
+ import torch.distributed as dist
447
+ dist.barrier()
448
+ dist.destroy_process_group()
449
+
450
+
451
+ if __name__ == "__main__":
452
+ main()
@@ -0,0 +1,130 @@
1
+ """LoRA / QLoRA adapters for any PyTorch model.
2
+
3
+ from bantamtrain.lora import apply_lora, lora_state_dict, merge_lora
4
+ apply_lora(model, r=16, alpha=32, targets=("q_proj", "k_proj", "v_proj", "o_proj",
5
+ "gate_proj", "up_proj", "down_proj"))
6
+ ...train (only adapter weights have requires_grad)...
7
+ torch.save(lora_state_dict(model), "adapter.pt") # a few MB
8
+ merge_lora(model) # fold W += B A * scale into the base
9
+
10
+ Each targeted nn.Linear (or an int8/int4 QLinear from bantamtrain.qweights, which
11
+ gives QLoRA: frozen quantized base + trainable adapters) becomes
12
+
13
+ y = base(x) + (dropout(x) @ A^T @ B^T) * scale, scale = alpha / r (or alpha/sqrt(r))
14
+
15
+ A ~ Kaiming-uniform, B = 0, so the model starts exactly at the base model.
16
+ Trainable parameters per layer: r * (d_in + d_out).
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from .qweights import QLinear
25
+
26
+
27
+ class LoRALinear(nn.Module):
28
+ def __init__(self, base, r=8, alpha=16, dropout=0.0, rslora=False):
29
+ super().__init__()
30
+ assert isinstance(base, (nn.Linear, QLinear))
31
+ self.base = base
32
+ for p in self.base.parameters():
33
+ p.requires_grad_(False)
34
+ self.r, self.alpha = r, alpha
35
+ self.scale = alpha / (math.sqrt(r) if rslora else r)
36
+ d_in, d_out = base.in_features, base.out_features
37
+ self.lora_A = nn.Parameter(torch.empty(r, d_in))
38
+ self.lora_B = nn.Parameter(torch.zeros(d_out, r))
39
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
40
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
41
+ self.merged = False
42
+
43
+ @property
44
+ def in_features(self):
45
+ return self.base.in_features
46
+
47
+ @property
48
+ def out_features(self):
49
+ return self.base.out_features
50
+
51
+ def forward(self, x):
52
+ y = self.base(x)
53
+ if self.merged:
54
+ return y
55
+ a = self.lora_A.to(x.dtype)
56
+ b = self.lora_B.to(x.dtype)
57
+ return y + F.linear(F.linear(self.dropout(x), a), b) * self.scale
58
+
59
+ @torch.no_grad()
60
+ def merge(self):
61
+ """Fold the adapter into the base weight (float base only) and disable it."""
62
+ if self.merged:
63
+ return
64
+ delta = (self.lora_B.float() @ self.lora_A.float()) * self.scale
65
+ if isinstance(self.base, QLinear):
66
+ raise RuntimeError("merge into a quantized base: dequantize the base first")
67
+ self.base.weight.add_(delta.to(self.base.weight.dtype))
68
+ self.merged = True
69
+
70
+
71
+ def _match(name, targets):
72
+ leaf = name.split(".")[-1]
73
+ return any(t == leaf or t == name or name.endswith("." + t) for t in targets)
74
+
75
+
76
+ def apply_lora(model, r=8, alpha=16, dropout=0.0, targets=("q_proj", "k_proj", "v_proj", "o_proj"),
77
+ rslora=False, min_numel=0, freeze_rest=True):
78
+ """Wrap every targeted Linear/QLinear in LoRALinear; freeze everything else.
79
+
80
+ Returns a report {wrapped, trainable_params, total_params}.
81
+ """
82
+ if freeze_rest:
83
+ for p in model.parameters():
84
+ p.requires_grad_(False)
85
+ wrapped = 0
86
+ for name, mod in list(model.named_modules()):
87
+ for cname, child in list(mod.named_children()):
88
+ full = f"{name}.{cname}" if name else cname
89
+ if isinstance(child, (nn.Linear, QLinear)) and _match(full, targets) \
90
+ and child.in_features * child.out_features >= min_numel:
91
+ setattr(mod, cname, LoRALinear(child, r, alpha, dropout, rslora))
92
+ wrapped += 1
93
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
94
+ total = sum(p.numel() for p in model.parameters())
95
+ return {"wrapped": wrapped, "r": r, "alpha": alpha, "trainable_params": trainable,
96
+ "total_params": total, "trainable_frac": trainable / max(total, 1)}
97
+
98
+
99
+ def lora_parameters(model):
100
+ return [p for n, p in model.named_parameters() if "lora_A" in n or "lora_B" in n]
101
+
102
+
103
+ def lora_state_dict(model):
104
+ return {k: v.detach().cpu() for k, v in model.state_dict().items()
105
+ if "lora_A" in k or "lora_B" in k}
106
+
107
+
108
+ def load_lora_state_dict(model, sd):
109
+ missing, unexpected = model.load_state_dict(sd, strict=False)
110
+ bad = [k for k in missing if "lora_" in k]
111
+ assert not bad and not unexpected, (bad, unexpected)
112
+
113
+
114
+ def merge_lora(model):
115
+ """Merge every adapter into its base weight; returns the number merged."""
116
+ n = 0
117
+ for m in model.modules():
118
+ if isinstance(m, LoRALinear):
119
+ m.merge()
120
+ n += 1
121
+ return n
122
+
123
+
124
+ def unwrap_lora(model):
125
+ """Replace each (merged) LoRALinear by its base module."""
126
+ for name, mod in list(model.named_modules()):
127
+ for cname, child in list(mod.named_children()):
128
+ if isinstance(child, LoRALinear):
129
+ setattr(mod, cname, child.base)
130
+ return model
@@ -0,0 +1,35 @@
1
+ """Chunked cross-entropy: never materializes the full (tokens x vocab) logits.
2
+
3
+ loss = chunked_cross_entropy(hidden, head_weight, targets, chunk=2048)
4
+
5
+ The logits of each chunk of `chunk` positions are computed, reduced to a loss
6
+ and discarded; torch.utils.checkpoint recomputes them in the backward pass.
7
+ Peak memory for the loss goes from tokens*vocab*4 bytes to chunk*vocab*4, which
8
+ for a 128k vocabulary at 16k tokens per step is 8 GB -> 1 GB. Matches
9
+ F.cross_entropy exactly up to floating-point summation order.
10
+ """
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch.utils.checkpoint import checkpoint
14
+
15
+
16
+ def _chunk_loss(h, weight, bias, targets, softcap, ignore_index):
17
+ logits = F.linear(h, weight, bias).float()
18
+ if softcap > 0:
19
+ logits = softcap * torch.tanh(logits / softcap)
20
+ return F.cross_entropy(logits, targets, ignore_index=ignore_index, reduction="sum")
21
+
22
+
23
+ def chunked_cross_entropy(h, weight, targets, chunk=2048, bias=None, softcap=0.0,
24
+ ignore_index=-100):
25
+ """h: (..., d) hidden states; weight: (vocab, d); targets: (...) long. Mean over
26
+ non-ignored targets."""
27
+ h = h.reshape(-1, h.shape[-1])
28
+ targets = targets.reshape(-1)
29
+ n_valid = (targets != ignore_index).sum().clamp_min(1)
30
+ total = h.new_zeros((), dtype=torch.float32)
31
+ for i in range(0, h.shape[0], chunk):
32
+ total = total + checkpoint(_chunk_loss, h[i:i + chunk], weight, bias,
33
+ targets[i:i + chunk], softcap, ignore_index,
34
+ use_reentrant=False)
35
+ return total / n_valid
@@ -102,6 +102,43 @@ def scoreboard(params=5e9, d=0, vocab=32000, seq=2048, gpu_gb=96.0, peak_tflops=
102
102
  return {"layers": L, "params": N, "d": d, "rows": rows}
103
103
 
104
104
 
105
+ def finetune_table(N, d, L, seq, micro, gpu_gb, lora_r=16, overhead_gb=2.0, act_factor=1.0):
106
+ """Memory for fine-tuning an N-param base model on one GPU: full FT vs LoRA vs QLoRA.
107
+
108
+ LoRA params ~ 2 * r * (sum over the 7 projections of (d_in + d_out)) per layer
109
+ ~ r * L * (4*2d + 3*(d + 2.7d)) for a Llama block; adapters keep fp32 state.
110
+ """
111
+ lora_params = lora_r * L * (4 * 2 * d + 3 * (d + 2.7 * d))
112
+ act = 34 * d * L * seq * micro * act_factor
113
+ act_ckpt = (2 * d * L + 34 * d) * seq * micro * act_factor
114
+ rows = []
115
+ for name, wbytes, grads, state, trainable in [
116
+ ("full fine-tune: fp32 master + AdamW (standard)", 4 + 2, 4 * N, 8 * N, N),
117
+ ("full fine-tune: bf16 weights(SR) + 8-bit Muon", 2, 2 * N, 1.1 * N, N),
118
+ (f"LoRA r={lora_r}: bf16 base frozen + fp32 adapters/AdamW", 2, 4 * lora_params,
119
+ 8 * lora_params, lora_params),
120
+ (f"QLoRA r={lora_r}: int4 base (bantamtrain.qweights) + adapters", 0.53, 4 * lora_params,
121
+ 8 * lora_params, lora_params),
122
+ ]:
123
+ static = wbytes * N + grads + state + 4 * lora_params * (1 if "LoRA" in name else 0)
124
+ for ck, a in (("no", act), ("yes", act_ckpt)):
125
+ total = static + a + overhead_gb * GB
126
+ rows.append({"config": name, "ckpt": ck, "trainable": trainable,
127
+ "static_gb": static / GB, "act_gb": a / GB, "total_gb": total / GB,
128
+ "fits": total <= gpu_gb * GB})
129
+ return rows
130
+
131
+
132
+ def fmt_finetune(rows, N, gpu_gb):
133
+ hdr = f"fine-tuning a {N/1e9:.1f}B base model on one {gpu_gb:.0f} GB GPU"
134
+ out = [hdr, f"{'configuration':60s} {'act.ckpt':>8s} {'trainable':>10s} {'static':>7s} {'act':>6s} {'total':>6s} fit"]
135
+ out.append("-" * len(out[1]))
136
+ for r in rows:
137
+ out.append(f"{r['config']:60s} {r['ckpt']:>8s} {r['trainable']/1e6:9.1f}M {r['static_gb']:6.1f}G "
138
+ f"{r['act_gb']:5.1f}G {r['total_gb']:5.1f}G {'yes' if r['fits'] else 'NO'}")
139
+ return "\n".join(out)
140
+
141
+
105
142
  def storage_table(N, tokens, bits_per_token=5.97):
106
143
  """Disk/RAM sizes for weights, resumable checkpoints and the token corpus."""
107
144
  return [
@@ -157,7 +194,17 @@ def main():
157
194
  ap.add_argument("--act_factor", type=float, default=1.0,
158
195
  help="activation memory vs the 34*T*d formula (1.6 for HF Llama code)")
159
196
  ap.add_argument("--markdown", action="store_true")
197
+ ap.add_argument("--finetune", action="store_true",
198
+ help="print the fine-tuning memory table (full / LoRA / QLoRA) instead")
199
+ ap.add_argument("--micro", type=int, default=4, help="micro-batch for the fine-tune table")
200
+ ap.add_argument("--lora_r", type=int, default=16)
160
201
  a = ap.parse_args()
202
+ if a.finetune:
203
+ d = a.d or default_width(a.params)
204
+ L, N = model_dims(a.params, d, a.vocab)
205
+ print(fmt_finetune(finetune_table(N, d, L, a.seq, a.micro, a.gpu_gb, a.lora_r,
206
+ act_factor=a.act_factor), N, a.gpu_gb))
207
+ return
161
208
  sb = scoreboard(a.params, a.d, a.vocab, a.seq, a.gpu_gb, a.peak_tflops, a.mfu, a.tokens,
162
209
  a.fp8_speedup, a.muon_flops, a.power_tput, act_factor=a.act_factor)
163
210
  print(fmt(sb, a.tokens, a.markdown))
@@ -10,6 +10,7 @@ import torch.nn as nn
10
10
  import torch.nn.functional as F
11
11
  from torch.utils.checkpoint import checkpoint
12
12
 
13
+ from ..losses import chunked_cross_entropy
13
14
  from ..zoom import SlotMerge, SlotUnmerge
14
15
 
15
16
 
@@ -78,13 +79,14 @@ class ZoomGPT(nn.Module):
78
79
  def __init__(self, vocab, d=256, n_layer=6, n_head=4, zoom_ks=(),
79
80
  gated=True, out_mode="slot", rope_pos="token", qk_norm=False,
80
81
  merge_mode=None, grad_ckpt=False, mlp="gelu", softcap=0.0,
81
- zero_init_proj=False):
82
+ zero_init_proj=False, ce_chunk=0):
82
83
  super().__init__()
83
84
  assert out_mode in ("slot", "bag")
84
85
  assert rope_pos in ("token", "patch")
85
86
  self.d, self.n_layer, self.vocab = d, n_layer, vocab
86
87
  self.out_mode, self.rope_pos, self.grad_ckpt = out_mode, rope_pos, grad_ckpt
87
88
  self.softcap = softcap
89
+ self.ce_chunk = ce_chunk
88
90
  self.head_dim = d // n_head
89
91
  self.emb = nn.Embedding(vocab, d)
90
92
  self.blocks = nn.ModuleList(Block(d, n_head, qk_norm=qk_norm, mlp=mlp)
@@ -146,10 +148,17 @@ class ZoomGPT(nn.Module):
146
148
  B, T = idx.shape
147
149
  h = self.hidden(idx, k) # (B, T/k, d)
148
150
  if k == 1:
151
+ if self.ce_chunk:
152
+ return chunked_cross_entropy(h, self.emb.weight, targets, self.ce_chunk,
153
+ softcap=self.softcap)
149
154
  return F.cross_entropy(self.logits(h).view(-1, self.vocab), targets.reshape(-1))
150
155
  tgt = targets.view(B, T // k, k)
151
156
  if self.out_mode == "slot":
152
- z = self.logits(self.unmerge[str(k)](h)) # (B, T/k, k, V)
157
+ hs = self.unmerge[str(k)](h) # (B, T/k, k, d)
158
+ if self.ce_chunk:
159
+ return chunked_cross_entropy(hs, self.emb.weight, tgt, self.ce_chunk,
160
+ softcap=self.softcap)
161
+ z = self.logits(hs) # (B, T/k, k, V)
153
162
  return F.cross_entropy(z.reshape(-1, self.vocab), tgt.reshape(-1))
154
163
  logp = F.log_softmax(self.logits(h), dim=-1) # (B, T/k, V), one dist per group
155
164
  return -logp.gather(-1, tgt).mean()
@@ -18,6 +18,7 @@ Low-memory options (see bantamtrain.lowmem):
18
18
  import math
19
19
 
20
20
  import torch
21
+ import torch.nn as nn
21
22
  from torch.optim import Optimizer
22
23
 
23
24
  from .lowmem import QState, write_param
@@ -180,20 +181,44 @@ class CombinedOptimizer:
180
181
  o.load_state_dict(s)
181
182
 
182
183
 
184
+ def default_muon_params(model, include_lora=False):
185
+ """Muon candidates for an arbitrary model: trainable 2-D weights of nn.Linear
186
+ layers that are not embeddings or the output head (and not LoRA adapters
187
+ unless include_lora). Works for HuggingFace causal LMs."""
188
+ skip = {id(m.weight) for m in model.modules() if isinstance(m, nn.Embedding)}
189
+ get_out = getattr(model, "get_output_embeddings", None)
190
+ if callable(get_out):
191
+ out = get_out()
192
+ if out is not None and hasattr(out, "weight"):
193
+ skip.add(id(out.weight))
194
+ params = []
195
+ for name, m in model.named_modules():
196
+ if isinstance(m, nn.Linear) and m.weight.requires_grad and m.weight.dim() == 2 \
197
+ and id(m.weight) not in skip and "lora_" not in name \
198
+ and not name.split(".")[-1] in ("lm_head", "head", "output", "score"):
199
+ params.append(m.weight)
200
+ elif include_lora and type(m).__name__ == "LoRALinear":
201
+ params += [m.lora_A, m.lora_B]
202
+ return params
203
+
204
+
183
205
  def build_optimizer(model, name, lr, weight_decay, betas=(0.9, 0.95), fused=None,
184
- state_bits=32, ns="quintic"):
206
+ state_bits=32, ns="quintic", muon_lora=False):
185
207
  """name: 'adamw' or 'muon'.
186
208
 
187
- Muon takes the 2-D weights the model lists in `model.muon_params()`
188
- (hidden matrices inside the blocks). Embeddings, output head, norms, gates
189
- and biases stay on AdamW, as recommended for Muon.
209
+ Muon takes the 2-D weights the model lists in `model.muon_params()`, or,
210
+ for any other model (e.g. a HuggingFace LM), the hidden nn.Linear weights
211
+ found by `default_muon_params`. Embeddings, output head, norms, gates,
212
+ biases and (by default) LoRA adapters stay on AdamW.
190
213
 
191
214
  state_bits=8, or bf16 parameters, switch AdamW to AdamWLowMem (8-bit
192
215
  moments / stochastic-rounding writes); otherwise torch's fused AdamW is used.
193
216
  """
194
217
  muon_ids = set()
195
218
  if name == "muon":
196
- muon_ids = {id(p) for p in model.muon_params()}
219
+ cands = model.muon_params() if hasattr(model, "muon_params") \
220
+ else default_muon_params(model, include_lora=muon_lora)
221
+ muon_ids = {id(p) for p in cands if p.requires_grad}
197
222
  muon_p, decay, no_decay = [], [], []
198
223
  for n, p in model.named_parameters():
199
224
  if not p.requires_grad:
@@ -206,7 +231,8 @@ def build_optimizer(model, name, lr, weight_decay, betas=(0.9, 0.95), fused=None
206
231
  no_decay.append(p)
207
232
  groups = [{"params": decay, "weight_decay": weight_decay},
208
233
  {"params": no_decay, "weight_decay": 0.0}]
209
- bf16_params = next(model.parameters()).dtype == torch.bfloat16
234
+ trainable = [p for p in model.parameters() if p.requires_grad]
235
+ bf16_params = any(p.dtype == torch.bfloat16 for p in trainable)
210
236
  if state_bits == 8 or bf16_params:
211
237
  adamw = AdamWLowMem(groups, lr=lr, betas=betas, eps=1e-8, state_bits=state_bits)
212
238
  else:
@@ -5,10 +5,14 @@
5
5
  print(report) # bytes before / after
6
6
 
7
7
  Each weight matrix is split into blocks of `block` consecutive input columns;
8
- every block stores one fp16 scale (absmax / qmax) and int codes:
8
+ every block stores one fp16 scale (absmax) and codes:
9
9
 
10
- bits=8: int8 in [-127, 127] ~1.03 B/param (block 128)
11
- bits=4: int4 in [-7, 7], two codes per byte ~0.53 B/param (block 64)
10
+ bits=8: int8 in [-127, 127] ~1.03 B/param (block 128)
11
+ bits=4: linear int4 in [-7, 7], two codes per byte ~0.53 B/param (block 64)
12
+ "nf4": 4-bit NormalFloat (QLoRA, Dettmers 2023): 16 codebook values at the
13
+ quantiles of N(0,1), two codes per byte ~0.53 B/param (block 64)
14
+ NF4 is the right choice for pretrained weights (roughly Gaussian per block);
15
+ linear int4 wastes codes on the rarely used extremes.
12
16
 
13
17
  The forward pass dequantizes the block-scaled codes to the activation dtype
14
18
  and runs a normal matmul, so the model's output is that of a model whose
@@ -21,7 +25,13 @@ import torch
21
25
  import torch.nn as nn
22
26
  import torch.nn.functional as F
23
27
 
24
- QMAX = {8: 127, 4: 7}
28
+ QMAX = {8: 127, 4: 7, "nf4": 7}
29
+ # NF4 codebook (bitsandbytes create_normal_map): 16 quantiles of N(0,1), 0 exactly representable
30
+ NF4 = torch.tensor([-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453,
31
+ -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0,
32
+ 0.07958029955625534, 0.16093020141124725, 0.24611230194568634,
33
+ 0.33791524171829224, 0.44070982933044434, 0.5626170039176941,
34
+ 0.7229568362236023, 1.0])
25
35
 
26
36
 
27
37
  def quantize_rows(w, bits, block):
@@ -32,6 +42,12 @@ def quantize_rows(w, bits, block):
32
42
  if pad:
33
43
  w = F.pad(w, (0, pad))
34
44
  b = w.view(R, -1, block)
45
+ if bits == "nf4":
46
+ s = b.abs().amax(dim=2).clamp_min(1e-12) # scale to [-1, 1]
47
+ n = b / s[..., None]
48
+ u = (n[..., None] - NF4.to(n.device)).abs().argmin(dim=-1).to(torch.uint8).view(R, -1)
49
+ q = (u[:, 0::2] | (u[:, 1::2] << 4)).contiguous()
50
+ return q, s.to(torch.float16), pad
35
51
  s = (b.abs().amax(dim=2) / QMAX[bits]).clamp_min(1e-12)
36
52
  q = torch.round(b / s[..., None]).clamp_(-QMAX[bits], QMAX[bits]).to(torch.int8)
37
53
  if bits == 4:
@@ -42,6 +58,13 @@ def quantize_rows(w, bits, block):
42
58
 
43
59
  def dequantize_rows(q, s, pad, bits, block, dtype=torch.float32):
44
60
  R = q.shape[0]
61
+ if bits == "nf4":
62
+ lo = (q & 0x0F).long()
63
+ hi = (q >> 4).long()
64
+ idx = torch.stack([lo, hi], dim=-1).view(R, -1)
65
+ w = NF4.to(q.device)[idx].to(dtype).view(R, -1, block) * s.to(dtype)[..., None]
66
+ w = w.view(R, -1)
67
+ return w[:, :w.shape[1] - pad] if pad else w
45
68
  if bits == 4:
46
69
  lo = (q & 0x0F).to(torch.int8) - 8
47
70
  hi = (q >> 4).to(torch.int8) - 8
@@ -75,6 +98,10 @@ class QLinear(nn.Module):
75
98
  n = self.q.numel() * self.q.element_size() + self.s.numel() * 2
76
99
  return n + (0 if self.bias is None else self.bias.numel() * 4)
77
100
 
101
+ @property
102
+ def code_bits(self):
103
+ return 4 if self.bits in (4, "nf4") else 8
104
+
78
105
 
79
106
  class QEmbedding(nn.Module):
80
107
  """Quantized embedding table; `.weight` dequantizes (for a tied output head)."""
@@ -111,19 +138,37 @@ def model_bytes(model):
111
138
 
112
139
 
113
140
  @torch.no_grad()
114
- def quantize_model(model, bits=8, block=None, min_numel=4096):
115
- """Replace every nn.Linear / nn.Embedding with >= min_numel weights, in place."""
116
- assert bits in (8, 4)
141
+ def quantize_model(model, bits=8, block=None, min_numel=4096, embed_bits="same",
142
+ skip_names=()):
143
+ """Replace every nn.Linear / nn.Embedding with >= min_numel weights, in place.
144
+ bits: 8, 4 (linear int4) or "nf4" for the linear layers.
145
+ embed_bits: "same", 8, 4, "nf4" or None (keep embeddings and a tied/untied
146
+ output head in float, as QLoRA does). skip_names: module-name suffixes to leave alone."""
147
+ assert bits in (8, 4, "nf4")
117
148
  block = block or (128 if bits == 8 else 64)
149
+ eb = bits if embed_bits == "same" else embed_bits
150
+ eblock = 128 if eb == 8 else 64
151
+ head_ids = set()
152
+ get_out = getattr(model, "get_output_embeddings", None)
153
+ if callable(get_out) and get_out() is not None:
154
+ head_ids.add(id(get_out()))
118
155
  before = model_bytes(model)
119
156
  n_q = 0
120
157
  for name, mod in list(model.named_modules()):
121
158
  for cname, child in list(mod.named_children()):
122
- if isinstance(child, nn.Linear) and child.weight.numel() >= min_numel:
159
+ full = f"{name}.{cname}" if name else cname
160
+ if any(full.endswith(sn) for sn in skip_names):
161
+ continue
162
+ is_head = id(child) in head_ids
163
+ if isinstance(child, nn.Linear) and child.weight.numel() >= min_numel and not is_head:
123
164
  setattr(mod, cname, QLinear(child, bits, block))
124
165
  n_q += 1
125
- elif isinstance(child, nn.Embedding) and child.weight.numel() >= min_numel:
126
- setattr(mod, cname, QEmbedding(child, bits, block))
166
+ elif isinstance(child, (nn.Embedding, nn.Linear)) and child.weight.numel() >= min_numel \
167
+ and (isinstance(child, nn.Embedding) or is_head) and eb is not None:
168
+ if isinstance(child, nn.Embedding):
169
+ setattr(mod, cname, QEmbedding(child, eb, eblock))
170
+ else:
171
+ setattr(mod, cname, QLinear(child, eb, eblock))
127
172
  n_q += 1
128
173
  after = model_bytes(model)
129
174
  return {"bits": bits, "block": block, "modules_quantized": n_q,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bantamtrain
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Bantam: train small language models and weather models faster and cheaper on limited compute - Zoom Training, Muon, 8-bit/bf16 low-memory training, int8/int4 weights, compressed token and weather-grid stores
5
5
  Author: Nathan
6
6
  License-Expression: MIT
@@ -22,6 +22,10 @@ Provides-Extra: data
22
22
  Requires-Dist: tokenizers; extra == "data"
23
23
  Requires-Dist: pyarrow; extra == "data"
24
24
  Requires-Dist: huggingface_hub; extra == "data"
25
+ Provides-Extra: finetune
26
+ Requires-Dist: transformers>=4.40; extra == "finetune"
27
+ Requires-Dist: datasets; extra == "finetune"
28
+ Requires-Dist: sentencepiece; extra == "finetune"
25
29
  Provides-Extra: weather
26
30
  Requires-Dist: xarray; extra == "weather"
27
31
  Requires-Dist: zarr; extra == "weather"
@@ -59,6 +63,9 @@ pip install bantamtrain
59
63
  | `bantamtrain.device` | runtime: flush-to-zero on CPU, AMP, TF32, compile, batch finder, duty-cycle limiter | the FTZ fix made affected CPU matmuls up to 23x faster |
60
64
  | `bantamtrain.memory` | memory / time scoreboard for single-GPU training | `python -m bantamtrain.memory` |
61
65
  | `bantamtrain.models` | `ZoomGPT` (decoder LM) and `ZoomViT` (weather grid forecaster) with every option above | |
66
+ | `bantamtrain.lora` | LoRA / QLoRA adapters on `nn.Linear` or int8 / NF4 / int4 `QLinear` bases; merge, adapter-only state dicts | |
67
+ | `bantamtrain.losses` | chunked cross-entropy: never materializes the tokens x vocab logits | |
68
+ | `bantamtrain.finetune` | `python -m bantamtrain.finetune`: SFT of any HuggingFace causal LM (chat templates, response-only loss, best-fit packing), Muon + 8-bit state, torchrun DDP | SmolLM2-135M QLoRA on Dolly: held-out loss 3.39 -> 3.18 in 40 CPU steps |
62
69
 
63
70
  ## Quick start
64
71
 
@@ -89,6 +96,22 @@ weightpack.save("model.zwpk", model.state_dict(), bits=8) # int8 checkpoint f
89
96
  qweights.quantize_model(model, bits=4) # int4 weights in RAM, float compute
90
97
  ```
91
98
 
99
+ Fine-tune a HuggingFace model (LoRA on an int8 / NF4 base, Muon, 8-bit state):
100
+
101
+ ```bash
102
+ pip install bantamtrain[finetune]
103
+ python -m bantamtrain.finetune --model HuggingFaceTB/SmolLM2-135M \
104
+ --dataset databricks/databricks-dolly-15k --max_examples 2000 \
105
+ --lora 16 --quant 8 --optim muon --state_bits 8 --epochs 1 --out runs/dolly
106
+ torchrun --nproc_per_node 4 -m bantamtrain.finetune ... # multi-GPU
107
+ python -m bantamtrain.memory --finetune --params 7e9 --gpu_gb 24 # will it fit?
108
+ ```
109
+
110
+ Measured on SmolLM2-135M before training (100 held-out Dolly examples): int8
111
+ base costs +0.003 loss (558 -> 200 MB), NF4 linears with int8 embeddings
112
+ +0.18 (140 MB). Use int8 for small bases; NF4 for 7B+ where the literature
113
+ finds it near-lossless.
114
+
92
115
  Size a run on one GPU:
93
116
 
94
117
  ```bash
@@ -97,9 +120,9 @@ python -m bantamtrain.memory --params 5e9 --gpu_gb 96 --tokens 1e11
97
120
 
98
121
  ## Honest notes
99
122
 
100
- - Muon, 8-bit optimizer state, stochastic-rounding bf16 and blockwise weight
101
- quantization are published techniques re-implemented here; Zoom Training and
102
- the storage formats are this project's own.
123
+ - Muon, 8-bit optimizer state, stochastic-rounding bf16, LoRA/QLoRA/NF4 and
124
+ blockwise weight quantization are published techniques re-implemented here;
125
+ Zoom Training and the storage formats are this project's own.
103
126
  - All quality numbers above were measured on a 5.8M-parameter model; gains at
104
127
  larger scale are expected to be smaller for the optimizer and are untested for
105
128
  Zoom. Nothing has been run on a GPU yet.
@@ -3,6 +3,9 @@ README.md
3
3
  pyproject.toml
4
4
  bantamtrain/__init__.py
5
5
  bantamtrain/device.py
6
+ bantamtrain/finetune.py
7
+ bantamtrain/lora.py
8
+ bantamtrain/losses.py
6
9
  bantamtrain/lowmem.py
7
10
  bantamtrain/memory.py
8
11
  bantamtrain/optim.py
@@ -7,6 +7,11 @@ tokenizers
7
7
  pyarrow
8
8
  huggingface_hub
9
9
 
10
+ [finetune]
11
+ transformers>=4.40
12
+ datasets
13
+ sentencepiece
14
+
10
15
  [test]
11
16
  pytest
12
17
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "bantamtrain"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "Bantam: train small language models and weather models faster and cheaper on limited compute - Zoom Training, Muon, 8-bit/bf16 low-memory training, int8/int4 weights, compressed token and weather-grid stores"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -24,6 +24,7 @@ dependencies = ["torch>=2.2", "numpy>=1.24", "zstandard>=0.21"]
24
24
 
25
25
  [project.optional-dependencies]
26
26
  data = ["tokenizers", "pyarrow", "huggingface_hub"]
27
+ finetune = ["transformers>=4.40", "datasets", "sentencepiece"]
27
28
  weather = ["xarray", "zarr", "fsspec", "aiohttp"]
28
29
  test = ["pytest"]
29
30
 
File without changes
File without changes