layerpool 0.1.0__py3-none-any.whl

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.
layerpool/job.py ADDED
@@ -0,0 +1,242 @@
1
+ import glob
2
+ import json
3
+ import os
4
+ import struct
5
+
6
+
7
+ from .blocks import block_keys, layout, linear_size, load_config as hf_config, lora_targets, skeleton, targeted
8
+
9
+
10
+
11
+ def tensor_bytes(repo: str) -> dict[str, int]:
12
+ out = {}
13
+ if os.path.isdir(repo):
14
+ for path in glob.glob(os.path.join(repo, "*.safetensors")):
15
+ with open(path, "rb") as f:
16
+ header = json.loads(f.read(struct.unpack("<Q", f.read(8))[0]))
17
+ out.update({k: v["data_offsets"][1] - v["data_offsets"][0] for k, v in header.items() if k != "__metadata__"})
18
+ return out
19
+ from huggingface_hub import get_safetensors_metadata
20
+ for meta in get_safetensors_metadata(repo).files_metadata.values():
21
+ out.update({k: v.data_offsets[1] - v.data_offsets[0] for k, v in meta.tensors.items()})
22
+ return out
23
+
24
+
25
+ def load_config(repo: str) -> dict:
26
+ if os.path.isdir(repo):
27
+ path = os.path.join(repo, "config.json")
28
+ else:
29
+ from huggingface_hub import hf_hub_download
30
+ path = hf_hub_download(repo, "config.json")
31
+ with open(path, encoding="utf-8") as f:
32
+ return json.load(f)
33
+
34
+
35
+ def _block_shape(config, lay: dict) -> tuple[int, int]:
36
+ """(weights, LoRA in+out sum per unit of rank) of one block, from the model skeleton."""
37
+ block = skeleton(config, lay["auto"]).get_submodule(lay["stack"])[0]
38
+ params = sum(p.numel() for p in block.parameters())
39
+ lora = 0
40
+ for name in lora_targets(block):
41
+ mod = block.get_submodule(name)
42
+ lora += sum(linear_size(mod))
43
+ return params, lora
44
+
45
+
46
+ def estimate(repo: str, lay: dict, rank: int, seq: int, batch: int, micro: int, mode: str = "lora", config=None, stack: str | None = None) -> dict:
47
+ """Memory of one block on a device: its weights (as stored), the trainable part with its AdamW state, and the saved inputs of
48
+ every micro-batch in flight."""
49
+ config = config or hf_config(repo)
50
+ text = config.get_text_config()
51
+ hidden = getattr(text, "hidden_size", None) or getattr(config, "d_model", 1024)
52
+ inner = getattr(text, "intermediate_size", None) or 4 * hidden
53
+ params, lora = _block_shape(config, lay)
54
+ saved_inputs = micro * batch * seq * hidden * 2
55
+ if mode == "full":
56
+ per_block = params * 16
57
+ else:
58
+ try:
59
+ sizes = tensor_bytes(repo)
60
+ index = block_keys(sizes, stack or lay["stack"], lay["n"])
61
+ per = [0] * lay["n"]
62
+ for key, i in index.items():
63
+ per[i] += sizes[key]
64
+ stored = max(per)
65
+ except Exception:
66
+ stored = params * 2
67
+ per_block = stored + lora * rank * 4 * 4
68
+ peak = batch * seq * (3 * inner + 6 * hidden) * 2 + batch * seq * seq * 2
69
+ return {"layers": lay["n"], "layer_gb": round((per_block + saved_inputs) / 1e9, 4), "overhead_gb": round(0.8 + peak / 1e9, 3)}
70
+
71
+
72
+
73
+
74
+ QUANTIZERS = ("unsloth",)
75
+
76
+
77
+ def guess_mlx_repo(repo: str) -> str | None:
78
+ """The mlx-community 4-bit copy of a bitsandbytes repo that only quantizes a published model (unsloth's). Any other repo
79
+ may be a fine-tune with the base model's name, so its MLX weights must be given as mlx_model=."""
80
+ org, _, name = repo.rpartition("/")
81
+ if org.lower() not in QUANTIZERS:
82
+ return None
83
+ for suffix in ("-unsloth-bnb-4bit", "-bnb-4bit", "-4bit", "-bnb"):
84
+ if name.endswith(suffix):
85
+ name = name[: -len(suffix)]
86
+ break
87
+ candidate = f"mlx-community/{name}-4bit"
88
+ try:
89
+ from huggingface_hub import model_info
90
+ model_info(candidate)
91
+ return candidate
92
+ except Exception:
93
+ return None
94
+
95
+
96
+ RUN_EXTRAS = ("name", "checkpointing", "peer_replicas", "rebalance", "rebalance_cost_s", "streams", "target_modules")
97
+
98
+
99
+ def build_job(model: str, mlx_model: str | None = None, mode: str = "lora", rank: int = 16, alpha: float | None = None, lr: float = 1e-4,
100
+ schedule: str = "cosine", warmup: int = 0, min_lr_ratio: float = 0.1, weight_decay: float = 0.0, micro: int = 8,
101
+ micro_batch_size: int | None = None, codec: str = "fp16", ckpt_every: int = 4, random_init: bool = False, expected_steps: int | None = None,
102
+ seq: int = 512, auto: str = "AutoModelForCausalLM", **extra) -> dict:
103
+ if mode not in ("lora", "full"):
104
+ raise ValueError("mode must be 'lora' or 'full'")
105
+ raw = load_config(model)
106
+ if "quantization" in raw:
107
+ raise ValueError(f"{model} is an MLX-only model; pass the Hugging Face model as model= and this one as mlx_model=")
108
+ quant = raw.get("quantization_config") or {}
109
+ if quant and not (quant.get("quant_method") == "bitsandbytes" and quant.get("load_in_4bit")):
110
+ raise ValueError(f"{model} is quantized with {quant.get('quant_method', 'an unknown method')}; layerpool trains the 16-bit model "
111
+ "or a bitsandbytes 4-bit one (QLoRA)")
112
+ kind = "q4" if quant else "plain"
113
+ if kind == "q4" and mode == "full":
114
+ raise ValueError(f"{model} is a 4-bit model; full fine-tuning needs the 16-bit version (LoRA works on 4-bit)")
115
+ if random_init and mode != "full":
116
+ raise ValueError("training from scratch (random_init=True) needs mode='full'")
117
+ config = hf_config(model)
118
+ lay = layout(config, auto)
119
+ text = config.get_text_config()
120
+ model_type = str(getattr(text, "model_type", raw.get("model_type", "")))
121
+ causal = auto == "AutoModelForCausalLM"
122
+ mlx_ok = causal
123
+ guessed = None
124
+ if kind == "q4" and mlx_model is None and mlx_ok:
125
+ mlx_model = guessed = guess_mlx_repo(model)
126
+ pad = getattr(text, "pad_token_id", None)
127
+ if pad is None:
128
+ eos = getattr(text, "eos_token_id", None)
129
+ pad = eos[0] if isinstance(eos, list) else (eos or 0)
130
+ vocab = getattr(text, "vocab_size", None)
131
+ if vocab and not 0 <= int(pad) < vocab:
132
+ pad = 0
133
+ sizes = {"torch": estimate(model, lay, rank, seq, micro_batch_size or 1, micro, mode, config)}
134
+ if mlx_model and mlx_ok:
135
+ try:
136
+ sizes["mlx"] = estimate(mlx_model, lay, rank, seq, micro_batch_size or 1, micro, mode, config)
137
+ except Exception:
138
+ pass
139
+ job = {"repo": model, "mlx_repo": mlx_model if mlx_ok else None, "kind": kind, "mode": mode, "random_init": random_init, "rank": rank,
140
+ "scale": (alpha or 2 * rank) / rank, "lr": lr, "schedule": schedule, "warmup": warmup, "min_lr_ratio": min_lr_ratio,
141
+ "weight_decay": weight_decay, "micro": micro, "micro_batch_size": micro_batch_size, "codec": codec, "ckpt_every": ckpt_every,
142
+ "loss_scale": 1024.0, "loss_scale_max": 1024.0, "checkpointing": True, "peer_replicas": "auto", "rebalance": True, "rebalance_cost_s": 60, "streams": 3, "pad_id": int(pad),
143
+ "expected_steps": expected_steps, "seq": seq, "sizes": sizes, "auto": auto, "layout": lay, "mlx_ok": mlx_ok,
144
+ "model_type": model_type, "linear_attention": "linear_attention" in (getattr(text, "layer_types", None) or []),
145
+ **sizes["torch"]}
146
+ if guessed:
147
+ job["mlx_guessed"] = guessed
148
+ unknown = sorted(set(extra) - set(RUN_EXTRAS))
149
+ if unknown:
150
+ raise TypeError(f"unknown setting{'s' if len(unknown) > 1 else ''} for a run: {', '.join(unknown)} (the settings besides "
151
+ f"the named ones are {', '.join(RUN_EXTRAS)})")
152
+ job.update(extra)
153
+ targets = job.get("target_modules")
154
+ if targets in ("all-linear", None):
155
+ job["target_modules"] = None
156
+ elif isinstance(targets, str):
157
+ job["target_modules"] = [targets]
158
+ elif not (isinstance(targets, (list, tuple)) and targets and all(isinstance(t, str) and t for t in targets)):
159
+ raise ValueError(f"target_modules must be layer names such as [\"q_proj\", \"v_proj\"], or \"all-linear\", not {targets!r}")
160
+ else:
161
+ job["target_modules"] = list(targets)
162
+ if mode == "lora":
163
+ block = skeleton(config, lay["auto"]).get_submodule(lay["stack"])[0]
164
+ names = lora_targets(block)
165
+ if not any(targeted(n, job["target_modules"]) for n in names):
166
+ raise ValueError(f"target_modules {job['target_modules']} names none of the linear layers in a block of {model}: "
167
+ f"{', '.join(names)}")
168
+ for key in ("checkpointing", "rebalance"):
169
+ if not isinstance(job[key], bool):
170
+ raise ValueError(f"{key} must be True or False, not {job[key]!r}")
171
+ choices = {"codec": ("int8", "fp16", "fp32"), "peer_replicas": ("auto", "always", "never"), "schedule": ("constant", "linear", "cosine")}
172
+ for key, allowed in choices.items():
173
+ if job[key] not in allowed:
174
+ raise ValueError(f"{key} must be one of {', '.join(allowed)}, not {job[key]!r}")
175
+ for key in ("micro", "ckpt_every", "streams", "seq", "rank"):
176
+ if not isinstance(job[key], int) or job[key] < 1:
177
+ raise ValueError(f"{key} must be a whole number of at least 1, not {job[key]!r}")
178
+ if job["micro_batch_size"] is not None and (not isinstance(job["micro_batch_size"], int) or job["micro_batch_size"] < 1):
179
+ raise ValueError(f"micro_batch_size must be a whole number of at least 1, not {job['micro_batch_size']!r}")
180
+ return job
181
+
182
+
183
+ def load_rows(path: str) -> list:
184
+ if path.endswith((".jsonl", ".json")):
185
+ with open(path, encoding="utf-8") as f:
186
+ rows = [json.loads(line) for line in f if line.strip()] if path.endswith(".jsonl") else json.load(f)
187
+ if not isinstance(rows, list):
188
+ raise ValueError(f"{path}: a .json file must hold a list of rows (strings, or objects with 'text' or 'messages')")
189
+ out = []
190
+ for row in rows:
191
+ if isinstance(row, str):
192
+ out.append(row)
193
+ elif "messages" in row:
194
+ out.append(row["messages"])
195
+ elif "text" in row:
196
+ out.append(row["text"])
197
+ else:
198
+ raise ValueError(f"{path}: every row needs a 'text' or 'messages' field")
199
+ return out
200
+ if not path.endswith((".txt", ".md")):
201
+ raise ValueError(f"{path}: give the data as .jsonl or .json rows, or as a .txt or .md file of plain text")
202
+ with open(path, encoding="utf-8") as f:
203
+ return [f.read()]
204
+
205
+
206
+ def _render(tokenizer, messages: list[dict], prompt: bool = False) -> str:
207
+ return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=prompt)
208
+
209
+
210
+ def assistant_spans(tokenizer, messages: list[dict]) -> tuple[str, list[tuple[int, int]]]:
211
+ full = _render(tokenizer, messages)
212
+ spans, cursor = [], 0
213
+ for i, message in enumerate(messages):
214
+ if message["role"] != "assistant":
215
+ continue
216
+ before, upto = _render(tokenizer, messages[:i], prompt=True), _render(tokenizer, messages[:i + 1])
217
+ if upto.startswith(before) and full.startswith(upto):
218
+ spans.append((len(before), len(upto)))
219
+ cursor = len(upto)
220
+ else:
221
+ at = full.find(message["content"], cursor)
222
+ if at < 0:
223
+ raise ValueError("could not locate an assistant reply in the chat template output")
224
+ spans.append((at, at + len(message["content"])))
225
+ cursor = at + len(message["content"])
226
+ return full, spans
227
+
228
+
229
+ def encode_row(tokenizer, row, assistant_only: bool = True) -> tuple[list[int], list[int]]:
230
+ eos = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 0
231
+ if isinstance(row, str):
232
+ ids = list(tokenizer(row)["input_ids"])
233
+ if not ids or ids[-1] != eos:
234
+ ids.append(eos)
235
+ return ids, list(ids)
236
+ text, spans = assistant_spans(tokenizer, row)
237
+ enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
238
+ ids = list(enc["input_ids"])
239
+ if not assistant_only:
240
+ return ids, list(ids)
241
+ labels = [t if any(a <= start < b for a, b in spans) else -100 for t, (start, _) in zip(ids, enc["offset_mapping"])]
242
+ return ids, labels
layerpool/losses.py ADDED
@@ -0,0 +1,108 @@
1
+ """Losses written on per-token log-probabilities, so every one of them runs through the pipeline unchanged.
2
+
3
+ Each function takes torch tensors and returns a scalar torch loss. `logprobs` has shape (rows, tokens - 1): the log-probability of
4
+ every next token. `mask` marks the tokens that count (the completion), and `sequence_logprob` turns the two into one number per row."""
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch.utils.checkpoint import checkpoint
9
+
10
+ PIECE_BYTES = 1 << 28
11
+
12
+
13
+ def _piece_rows(vocab: int) -> int:
14
+ return max(1, PIECE_BYTES // (4 * vocab))
15
+
16
+
17
+ def _piece_logprobs(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
18
+ x = logits.float()
19
+ return x.gather(-1, targets[:, None]).squeeze(-1) - torch.logsumexp(x, -1)
20
+
21
+
22
+ def token_logprobs(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
23
+ """log p(target) for every position, shape targets.shape, without a float32 copy of the whole logits tensor: the rows go
24
+ through in pieces of about PIECE_BYTES, and in training each piece is recomputed in the backward pass instead of kept."""
25
+ vocab = logits.shape[-1]
26
+ flat, t = logits.reshape(-1, vocab), targets.reshape(-1).to(logits.device)
27
+ rows = _piece_rows(vocab)
28
+ if flat.shape[0] <= rows:
29
+ return _piece_logprobs(flat, t).view(targets.shape)
30
+ keep = torch.is_grad_enabled() and flat.requires_grad
31
+ parts = [checkpoint(_piece_logprobs, x, y, use_reentrant=False) if keep else _piece_logprobs(x, y)
32
+ for x, y in zip(flat.split(rows), t.split(rows))]
33
+ return torch.cat(parts).view(targets.shape)
34
+
35
+
36
+ def token_stats(logits: torch.Tensor, targets: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
37
+ """log p(target), the entropy of each next-token distribution, and whether the target was the most likely token, piece by
38
+ piece (no gradients)."""
39
+ vocab = logits.shape[-1]
40
+ flat, t = logits.reshape(-1, vocab), targets.reshape(-1).to(logits.device)
41
+ lp, entropy, top1 = [], [], []
42
+ with torch.no_grad():
43
+ for x, y in zip(flat.split(_piece_rows(vocab)), t.split(_piece_rows(vocab))):
44
+ logp = torch.log_softmax(x.float(), -1)
45
+ lp.append(logp.gather(-1, y[:, None]).squeeze(-1))
46
+ entropy.append(-(logp.exp() * logp).sum(-1))
47
+ top1.append((logp.argmax(-1) == y).float())
48
+ return tuple(torch.cat(v).view(targets.shape) for v in (lp, entropy, top1))
49
+
50
+
51
+ def lean_causal_loss(original):
52
+ """transformers' causal LM loss computed with token_logprobs when the logits are large, so a model with a big vocabulary does
53
+ not hold float32 copies of all of them (the loss and its gradients are the same); small logits go to `original`."""
54
+ def loss(logits, labels, vocab_size, num_items_in_batch=None, ignore_index=-100, shift_labels=None, **kwargs):
55
+ if logits.numel() <= 2 * _piece_rows(vocab_size) * vocab_size:
56
+ return original(logits, labels, vocab_size, num_items_in_batch=num_items_in_batch, ignore_index=ignore_index,
57
+ shift_labels=shift_labels, **kwargs)
58
+ if shift_labels is None:
59
+ shift_labels = F.pad(labels, (0, 1), value=ignore_index)[..., 1:]
60
+ t = shift_labels.reshape(-1).to(logits.device)
61
+ counted = t != ignore_index
62
+ lp = token_logprobs(logits.reshape(-1, vocab_size), t.masked_fill(~counted, 0))
63
+ total = -(lp * counted).sum()
64
+ if num_items_in_batch is None:
65
+ return total / counted.sum()
66
+ if torch.is_tensor(num_items_in_batch):
67
+ num_items_in_batch = num_items_in_batch.to(total.device)
68
+ return total / num_items_in_batch
69
+ return loss
70
+
71
+
72
+ def sequence_logprob(logprobs: torch.Tensor, mask: torch.Tensor, average: bool = False) -> torch.Tensor:
73
+ total = (logprobs * mask).sum(-1)
74
+ return total / mask.sum(-1).clamp(min=1) if average else total
75
+
76
+
77
+ def cross_entropy(logprobs: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
78
+ return -(logprobs * mask).sum() / mask.sum().clamp(min=1)
79
+
80
+
81
+ def dpo(policy_chosen: torch.Tensor, policy_rejected: torch.Tensor, ref_chosen: torch.Tensor, ref_rejected: torch.Tensor, beta: float = 0.1,
82
+ label_smoothing: float = 0.0) -> torch.Tensor:
83
+ margin = beta * ((policy_chosen - ref_chosen) - (policy_rejected - ref_rejected))
84
+ return (-F.logsigmoid(margin) * (1 - label_smoothing) - F.logsigmoid(-margin) * label_smoothing).mean()
85
+
86
+
87
+ def ipo(policy_chosen: torch.Tensor, policy_rejected: torch.Tensor, ref_chosen: torch.Tensor, ref_rejected: torch.Tensor, beta: float = 0.1) -> torch.Tensor:
88
+ margin = (policy_chosen - ref_chosen) - (policy_rejected - ref_rejected)
89
+ return ((margin - 1 / (2 * beta)) ** 2).mean()
90
+
91
+
92
+ def simpo(policy_chosen_avg: torch.Tensor, policy_rejected_avg: torch.Tensor, beta: float = 2.0, gamma: float = 0.5) -> torch.Tensor:
93
+ return -F.logsigmoid(beta * (policy_chosen_avg - policy_rejected_avg) - gamma).mean()
94
+
95
+
96
+ def orpo(chosen_avg: torch.Tensor, rejected_avg: torch.Tensor, chosen_nll: torch.Tensor, lam: float = 0.1) -> torch.Tensor:
97
+ log_odds = (chosen_avg - rejected_avg) - (torch.log1p(-torch.exp(chosen_avg).clamp(max=1 - 1e-6)) - torch.log1p(-torch.exp(rejected_avg).clamp(max=1 - 1e-6)))
98
+ return chosen_nll.mean() - lam * F.logsigmoid(log_odds).mean()
99
+
100
+
101
+ def policy_gradient(logprobs: torch.Tensor, mask: torch.Tensor, advantages: torch.Tensor, old_logprobs: torch.Tensor | None = None,
102
+ clip: float = 0.2) -> torch.Tensor:
103
+ if old_logprobs is None:
104
+ return -((logprobs * mask).sum(-1) * advantages).mean()
105
+ ratio = torch.exp(logprobs - old_logprobs)
106
+ adv = advantages[:, None]
107
+ per_token = -torch.minimum(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv)
108
+ return (per_token * mask).sum() / mask.sum().clamp(min=1)