layerpool 0.1.1__tar.gz → 0.1.3__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.
- {layerpool-0.1.1 → layerpool-0.1.3}/PKG-INFO +37 -1
- {layerpool-0.1.1 → layerpool-0.1.3}/README.md +36 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/__init__.py +1 -1
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/api.py +2 -1
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/blocks.py +16 -1
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/cli.py +12 -7
- layerpool-0.1.3/src/layerpool/data.py +162 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/job.py +0 -23
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/trainers.py +5 -36
- {layerpool-0.1.1 → layerpool-0.1.3}/.gitignore +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/LICENSE +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/pyproject.toml +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/__main__.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/backends/__init__.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/backends/common.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/backends/mlx_backend.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/codec.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/control.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/driver.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/export.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/fetch.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/hf.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/losses.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/net.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/planner.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/pool.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/selfcheck.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/telemetry.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/tunnel.py +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/ui/app.js +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/ui/index.html +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/ui/style.css +0 -0
- {layerpool-0.1.1 → layerpool-0.1.3}/src/layerpool/worker.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: layerpool
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.3
|
|
4
4
|
Summary: Train one model on all of your devices: layers split across GPUs, Apple Silicon and CPUs, with your own training code.
|
|
5
5
|
Project-URL: Homepage, https://github.com/abdallah-swe/layerpool
|
|
6
6
|
Project-URL: Repository, https://github.com/abdallah-swe/layerpool
|
|
@@ -56,6 +56,10 @@ One model, split by layers across all your machines. Their memory is pooled, and
|
|
|
56
56
|
|
|
57
57
|
</div>
|
|
58
58
|
|
|
59
|
+
<p align="center">
|
|
60
|
+
<img src="https://raw.githubusercontent.com/abdallah-swe/layerpool/main/docs/demo.webp" width="75%" alt="A model too big to train on any single machine is split by its layers across a gaming PC, a desktop, a laptop and a cloud GPU, and they train it together. When the laptop drops out, the others take over its layers.">
|
|
61
|
+
</p>
|
|
62
|
+
|
|
59
63
|
<div align="center">
|
|
60
64
|
|
|
61
65
|
| 💻 Laptop | 🖥️ Desktop | 🎮 Gaming PC | ☁️ Cloud GPU | | ⚡ Your pool |
|
|
@@ -216,6 +220,23 @@ layerpool train --model Qwen/Qwen3-8B --data data.jsonl --method sft --epochs 1
|
|
|
216
220
|
```
|
|
217
221
|
|
|
218
222
|
`--method` also takes `cpt`, `dpo`, `ipo`, `simpo` and `orpo`. In Python the same loop is `run.train("data.jsonl", method="sft")`.
|
|
223
|
+
|
|
224
|
+
`--data` is a `.jsonl`, `.json`, `.txt` or `.md` file, or the name of a dataset on Hugging Face (with `pip install "layerpool[hf]"`):
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
layerpool train --model Qwen/Qwen3-8B --data yahma/alpaca-cleaned --split "train[:5000]" --out my-adapter
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
`--split` picks its split (`train` by default) and `--subset` its configuration, when it has several. Rows are read as they are:
|
|
231
|
+
|
|
232
|
+
| Format | Fields |
|
|
233
|
+
| --- | --- |
|
|
234
|
+
| Chat | `messages` |
|
|
235
|
+
| ShareGPT | `conversations` |
|
|
236
|
+
| Alpaca | `instruction`, `output`, and `input` when there is one |
|
|
237
|
+
| Prompt and completion | `prompt` and `completion`, or `question` and `answer` |
|
|
238
|
+
| Plain text | `text` |
|
|
239
|
+
| Preference (`dpo`, `ipo`, `simpo`, `orpo`) | `prompt`, `chosen` and `rejected`, or whole conversations in `chosen` and `rejected` |
|
|
219
240
|
</details>
|
|
220
241
|
|
|
221
242
|
## What you can train
|
|
@@ -324,6 +345,21 @@ dashboard or with `layerpool approve CODE`.
|
|
|
324
345
|
|
|
325
346
|
</details>
|
|
326
347
|
|
|
348
|
+
## Compared to other tools
|
|
349
|
+
|
|
350
|
+
| | layerpool | [FSDP](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) / [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) | [Petals](https://github.com/bigscience-workshop/petals) | [exo](https://github.com/exo-explore/exo) |
|
|
351
|
+
| :--- | :---: | :---: | :---: | :---: |
|
|
352
|
+
| Trains the model's own layers | ✅ | ✅ | ❌ | ❌ |
|
|
353
|
+
| LoRA, QLoRA and full fine-tuning | ✅ | ✅ | ❌ | ❌ |
|
|
354
|
+
| Training from scratch | ✅ | ✅ | ❌ | ❌ |
|
|
355
|
+
| Works with the Hugging Face Trainer | ✅ | ✅ | – | ❌ |
|
|
356
|
+
| NVIDIA, Apple Silicon and CPU in one model | ✅ | ❌ | partly | ❌ |
|
|
357
|
+
| Over the internet, no port forwarding | ✅ | ❌ | ✅ | ❌ |
|
|
358
|
+
| Stronger devices get more layers | ✅ | ❌ | ✅ | ✅ |
|
|
359
|
+
| Goes on when a device drops out | ✅ | ❌ | ✅ | – |
|
|
360
|
+
|
|
361
|
+
<sub>From each project's documentation, November 2026.</sub>
|
|
362
|
+
|
|
327
363
|
## FAQ
|
|
328
364
|
|
|
329
365
|
<details>
|
|
@@ -15,6 +15,10 @@ One model, split by layers across all your machines. Their memory is pooled, and
|
|
|
15
15
|
|
|
16
16
|
</div>
|
|
17
17
|
|
|
18
|
+
<p align="center">
|
|
19
|
+
<img src="https://raw.githubusercontent.com/abdallah-swe/layerpool/main/docs/demo.webp" width="75%" alt="A model too big to train on any single machine is split by its layers across a gaming PC, a desktop, a laptop and a cloud GPU, and they train it together. When the laptop drops out, the others take over its layers.">
|
|
20
|
+
</p>
|
|
21
|
+
|
|
18
22
|
<div align="center">
|
|
19
23
|
|
|
20
24
|
| 💻 Laptop | 🖥️ Desktop | 🎮 Gaming PC | ☁️ Cloud GPU | | ⚡ Your pool |
|
|
@@ -175,6 +179,23 @@ layerpool train --model Qwen/Qwen3-8B --data data.jsonl --method sft --epochs 1
|
|
|
175
179
|
```
|
|
176
180
|
|
|
177
181
|
`--method` also takes `cpt`, `dpo`, `ipo`, `simpo` and `orpo`. In Python the same loop is `run.train("data.jsonl", method="sft")`.
|
|
182
|
+
|
|
183
|
+
`--data` is a `.jsonl`, `.json`, `.txt` or `.md` file, or the name of a dataset on Hugging Face (with `pip install "layerpool[hf]"`):
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
layerpool train --model Qwen/Qwen3-8B --data yahma/alpaca-cleaned --split "train[:5000]" --out my-adapter
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`--split` picks its split (`train` by default) and `--subset` its configuration, when it has several. Rows are read as they are:
|
|
190
|
+
|
|
191
|
+
| Format | Fields |
|
|
192
|
+
| --- | --- |
|
|
193
|
+
| Chat | `messages` |
|
|
194
|
+
| ShareGPT | `conversations` |
|
|
195
|
+
| Alpaca | `instruction`, `output`, and `input` when there is one |
|
|
196
|
+
| Prompt and completion | `prompt` and `completion`, or `question` and `answer` |
|
|
197
|
+
| Plain text | `text` |
|
|
198
|
+
| Preference (`dpo`, `ipo`, `simpo`, `orpo`) | `prompt`, `chosen` and `rejected`, or whole conversations in `chosen` and `rejected` |
|
|
178
199
|
</details>
|
|
179
200
|
|
|
180
201
|
## What you can train
|
|
@@ -283,6 +304,21 @@ dashboard or with `layerpool approve CODE`.
|
|
|
283
304
|
|
|
284
305
|
</details>
|
|
285
306
|
|
|
307
|
+
## Compared to other tools
|
|
308
|
+
|
|
309
|
+
| | layerpool | [FSDP](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) / [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) | [Petals](https://github.com/bigscience-workshop/petals) | [exo](https://github.com/exo-explore/exo) |
|
|
310
|
+
| :--- | :---: | :---: | :---: | :---: |
|
|
311
|
+
| Trains the model's own layers | ✅ | ✅ | ❌ | ❌ |
|
|
312
|
+
| LoRA, QLoRA and full fine-tuning | ✅ | ✅ | ❌ | ❌ |
|
|
313
|
+
| Training from scratch | ✅ | ✅ | ❌ | ❌ |
|
|
314
|
+
| Works with the Hugging Face Trainer | ✅ | ✅ | – | ❌ |
|
|
315
|
+
| NVIDIA, Apple Silicon and CPU in one model | ✅ | ❌ | partly | ❌ |
|
|
316
|
+
| Over the internet, no port forwarding | ✅ | ❌ | ✅ | ❌ |
|
|
317
|
+
| Stronger devices get more layers | ✅ | ❌ | ✅ | ✅ |
|
|
318
|
+
| Goes on when a device drops out | ✅ | ❌ | ✅ | – |
|
|
319
|
+
|
|
320
|
+
<sub>From each project's documentation, November 2026.</sub>
|
|
321
|
+
|
|
286
322
|
## FAQ
|
|
287
323
|
|
|
288
324
|
<details>
|
|
@@ -313,7 +313,8 @@ class Run:
|
|
|
313
313
|
def train(self, data, method: str = "sft", steps: int | None = None, epochs: float = 1.0, batch_size: int = 8, seq: int | None = None,
|
|
314
314
|
max_grad_norm: float | None = 1.0, beta: float | None = None, on_step=None, seed: int = 0, **kw) -> list[dict]:
|
|
315
315
|
"""Built-in loops. method: "sft" (chat or text rows, learns assistant replies), "cpt" (raw text, every token),
|
|
316
|
-
"dpo" / "ipo" / "simpo" / "orpo" (rows with prompt, chosen, rejected).
|
|
316
|
+
"dpo" / "ipo" / "simpo" / "orpo" (rows with prompt, chosen, rejected). data: rows, a dataset, a file, or the name of a
|
|
317
|
+
dataset on Hugging Face (with split= and subset=)."""
|
|
317
318
|
return trainers.train(self, data, method=method, steps=steps, epochs=epochs, batch_size=batch_size, seq=seq, max_grad_norm=max_grad_norm,
|
|
318
319
|
beta=beta, on_step=on_step, seed=seed, **kw)
|
|
319
320
|
|
|
@@ -276,7 +276,7 @@ def _prune_ranges(repo: str, keep: str):
|
|
|
276
276
|
with open(os.path.join(keep, "layerpool_part.json"), "w", encoding="utf-8") as f:
|
|
277
277
|
json.dump(marker, f)
|
|
278
278
|
now = time.time()
|
|
279
|
-
for name in os.listdir(RANGE_CACHE):
|
|
279
|
+
for name in os.listdir(RANGE_CACHE) if os.path.isdir(RANGE_CACHE) else ():
|
|
280
280
|
folder = os.path.join(RANGE_CACHE, name)
|
|
281
281
|
if folder == keep:
|
|
282
282
|
continue
|
|
@@ -394,6 +394,8 @@ def load_blocks(repo: str, lay: dict, first: int, last: int, device, dtype, quan
|
|
|
394
394
|
prefix = lay["stack"] + "."
|
|
395
395
|
missing = {k for k in info.get("missing_keys", []) if k.startswith(prefix)}
|
|
396
396
|
blocks = list(model.get_submodule(lay["stack"]))
|
|
397
|
+
if quantized:
|
|
398
|
+
_compute_in(blocks, dtype)
|
|
397
399
|
if not quantized and in_place:
|
|
398
400
|
saved = None if random_init else os.path.join(out, "model.safetensors")
|
|
399
401
|
blocks = _as_in_full_model(blocks, config, lay, first, device, missing if not random_init else set(), repo, saved, dtype)
|
|
@@ -406,6 +408,19 @@ def load_blocks(repo: str, lay: dict, first: int, last: int, device, dtype, quan
|
|
|
406
408
|
return blocks
|
|
407
409
|
|
|
408
410
|
|
|
411
|
+
def _compute_in(blocks, dtype):
|
|
412
|
+
"""A 4-bit checkpoint names the 16-bit type it was made to compute in, mostly bfloat16, and its 16-bit weights load in that
|
|
413
|
+
type. GPUs without bfloat16 in hardware (a T4) emulate it, several times slower, so the blocks compute in the device's own."""
|
|
414
|
+
import torch
|
|
415
|
+
for block in blocks:
|
|
416
|
+
for mod in block.modules():
|
|
417
|
+
if type(mod).__name__ == "Linear4bit":
|
|
418
|
+
mod.compute_dtype, mod.compute_type_is_set = dtype, True
|
|
419
|
+
for value in [*block.parameters(), *block.buffers()]:
|
|
420
|
+
if value.dtype in (torch.float16, torch.bfloat16) and value.dtype != dtype:
|
|
421
|
+
value.data = value.data.to(dtype)
|
|
422
|
+
|
|
423
|
+
|
|
409
424
|
def _as_in_full_model(loaded: list, config, lay: dict, first: int, device, missing: set, repo: str, saved: str | None = None,
|
|
410
425
|
dtype=None) -> list:
|
|
411
426
|
"""The blocks as the full model builds them, holding the loaded weights. A model built with fewer blocks numbers them from 0
|
|
@@ -17,12 +17,13 @@ import psutil
|
|
|
17
17
|
from . import __version__, worker as worker_module
|
|
18
18
|
from .api import connect, start
|
|
19
19
|
from .control import ControlServer, RemoteError, find_local
|
|
20
|
+
from .data import is_hub_name, load
|
|
20
21
|
from .pool import Pool, PoolError
|
|
21
22
|
|
|
22
23
|
REFERENCE_FILE = "reference_logprobs.npy"
|
|
23
|
-
TRAIN_KEYS = ("model", "mlx_model", "data", "method", "mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio",
|
|
24
|
-
"epochs", "batch_size", "seq", "micro", "micro_batch_size", "codec", "ckpt_every", "max_grad_norm", "beta", "out",
|
|
25
|
-
"save_every", "resume", "target_modules")
|
|
24
|
+
TRAIN_KEYS = ("model", "mlx_model", "data", "split", "subset", "method", "mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio",
|
|
25
|
+
"weight_decay", "steps", "epochs", "batch_size", "seq", "micro", "micro_batch_size", "codec", "ckpt_every", "max_grad_norm", "beta", "out",
|
|
26
|
+
"random_init", "train_on", "name", "save_every", "resume", "target_modules")
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
def plain_error(e: BaseException) -> str:
|
|
@@ -120,7 +121,10 @@ def train(argv):
|
|
|
120
121
|
p.add_argument("config", nargs="?", help="YAML or JSON file with any of the options below")
|
|
121
122
|
p.add_argument("--model")
|
|
122
123
|
p.add_argument("--mlx-model")
|
|
123
|
-
p.add_argument("--data", help=".jsonl/.json/.txt
|
|
124
|
+
p.add_argument("--data", help="a .jsonl/.json/.txt file or a Hugging Face dataset (user/name): chat rows (messages, ShareGPT), Alpaca "
|
|
125
|
+
"or prompt/completion rows, text rows, or preference rows (prompt, chosen, rejected)")
|
|
126
|
+
p.add_argument("--split", help="which split of a Hugging Face dataset, such as train[:1000] (default: train)")
|
|
127
|
+
p.add_argument("--subset", help="which configuration of a Hugging Face dataset that has several")
|
|
124
128
|
p.add_argument("--method", choices=["sft", "cpt", "dpo", "ipo", "simpo", "orpo"])
|
|
125
129
|
p.add_argument("--mode", choices=["lora", "full"])
|
|
126
130
|
p.add_argument("--random-init", action="store_true", default=None, help="train from scratch (with --mode full)")
|
|
@@ -168,14 +172,15 @@ def train(argv):
|
|
|
168
172
|
cfg.update({k: v for k, v in vars(args).items() if k in TRAIN_KEYS and v is not None})
|
|
169
173
|
if not cfg.get("model") or not cfg.get("data"):
|
|
170
174
|
sys.exit("layerpool train: --model and --data are required (or put them in the config file)")
|
|
171
|
-
if isinstance(cfg["data"], str) and not os.path.exists(cfg["data"]):
|
|
175
|
+
if isinstance(cfg["data"], str) and not os.path.exists(cfg["data"]) and not is_hub_name(cfg["data"]):
|
|
172
176
|
sys.exit(f"layerpool train: the data file {cfg['data']} does not exist")
|
|
173
177
|
run_training(cfg, local=args.local)
|
|
174
178
|
|
|
175
179
|
|
|
176
180
|
def run_training(cfg: dict, local: bool = False):
|
|
177
|
-
client = start(control=False) if local else _client()
|
|
178
181
|
method = cfg.get("method", "sft")
|
|
182
|
+
rows = load(cfg["data"], method, cfg.get("split") or "train", cfg.get("subset"))
|
|
183
|
+
client = start(control=False) if local else _client()
|
|
179
184
|
run_kwargs = {k: cfg[k] for k in ("mlx_model", "mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio", "weight_decay", "micro", "codec",
|
|
180
185
|
"micro_batch_size", "ckpt_every", "random_init", "seq", "target_modules") if cfg.get(k) is not None}
|
|
181
186
|
batch = cfg.get("batch_size", 8)
|
|
@@ -216,7 +221,7 @@ def run_training(cfg: dict, local: bool = False):
|
|
|
216
221
|
np.save(os.path.join(path, REFERENCE_FILE), run.reference)
|
|
217
222
|
print(f"layerpool: checkpoint {path} (resume with --resume {path})", flush=True)
|
|
218
223
|
try:
|
|
219
|
-
run.train(
|
|
224
|
+
run.train(rows, method=method, steps=cfg.get("steps"), epochs=cfg.get("epochs", 1.0), batch_size=batch, seq=cfg.get("seq"),
|
|
220
225
|
max_grad_norm=cfg.get("max_grad_norm", 1.0), beta=cfg.get("beta"), assistant_only=cfg.get("train_on", "assistant") == "assistant",
|
|
221
226
|
on_step=on_step, start_step=start_step, reference=reference)
|
|
222
227
|
path = run.save(out)
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
PREFERENCE = ("dpo", "ipo", "simpo", "orpo")
|
|
7
|
+
FILES = (".jsonl", ".json", ".txt", ".md")
|
|
8
|
+
PAIRS = (("instruction", "output"), ("instruction", "response"), ("prompt", "completion"), ("prompt", "response"), ("question", "answer"),
|
|
9
|
+
("query", "response"))
|
|
10
|
+
PROMPTS = ("prompt", "question", "instruction")
|
|
11
|
+
ROLES = {"system": "system", "human": "user", "user": "user", "gpt": "assistant", "assistant": "assistant", "chatgpt": "assistant",
|
|
12
|
+
"model": "assistant", "tool": "tool", "observation": "tool"}
|
|
13
|
+
KNOWN = ("'messages', 'text', 'conversations' (ShareGPT), 'instruction' and 'output' (Alpaca), 'prompt' and 'completion', or 'question' and "
|
|
14
|
+
"'answer'")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class EmptyRow(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def is_hub_name(data: str) -> bool:
|
|
22
|
+
return not os.path.exists(data) and not data.lower().endswith(FILES) and re.fullmatch(r"\w[\w.-]*/\w[\w.-]*", data) is not None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load(data, method: str = "sft", split: str = "train", subset: str | None = None) -> list:
|
|
26
|
+
"""Rows ready to train on: strings and lists of messages, or for a preference method dicts of chosen and rejected messages."""
|
|
27
|
+
if method not in ("sft", "cpt", *PREFERENCE):
|
|
28
|
+
raise ValueError(f"method must be one of sft, cpt, {', '.join(PREFERENCE)}")
|
|
29
|
+
name = data if isinstance(data, str) else "the data"
|
|
30
|
+
if isinstance(data, str):
|
|
31
|
+
rows = _read(data, split, subset)
|
|
32
|
+
elif isinstance(data, dict):
|
|
33
|
+
raise ValueError(f"the data is a dict with {', '.join(map(repr, list(data)[:5]))}: pass a list of rows, or one split of a dataset")
|
|
34
|
+
else:
|
|
35
|
+
rows = data.to_list() if hasattr(data, "to_list") else list(data)
|
|
36
|
+
convert, out, empty = _preference if method in PREFERENCE else _example, [], 0
|
|
37
|
+
for i, row in enumerate(rows):
|
|
38
|
+
try:
|
|
39
|
+
out.append(convert(row))
|
|
40
|
+
except EmptyRow:
|
|
41
|
+
empty += 1
|
|
42
|
+
except ValueError as e:
|
|
43
|
+
raise ValueError(f"row {i + 1} of {name}: {e}") from None
|
|
44
|
+
if empty and not out:
|
|
45
|
+
raise ValueError(f"every row of {name} has an empty question or reply")
|
|
46
|
+
if empty:
|
|
47
|
+
warnings.warn(f"layerpool: left out {empty} of the {len(out) + empty} rows of {name}: their question or reply is empty", stacklevel=2)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _read(data: str, split: str, subset: str | None) -> list:
|
|
52
|
+
if is_hub_name(data):
|
|
53
|
+
try:
|
|
54
|
+
from datasets import load_dataset
|
|
55
|
+
except ImportError:
|
|
56
|
+
raise RuntimeError(f"reading {data} from Hugging Face needs the datasets package: pip install \"layerpool[hf]\"") from None
|
|
57
|
+
try:
|
|
58
|
+
return load_dataset(data, subset, split=split).to_list()
|
|
59
|
+
except ValueError as e:
|
|
60
|
+
if subset is None and "config name is missing" in str(e).lower():
|
|
61
|
+
from datasets import get_dataset_config_names
|
|
62
|
+
raise ValueError(f"{data} has several configurations, pick one with subset (--subset): "
|
|
63
|
+
+ ", ".join(get_dataset_config_names(data))) from None
|
|
64
|
+
raise
|
|
65
|
+
if not data.lower().endswith(FILES):
|
|
66
|
+
raise ValueError(f"{data}: give the data as .jsonl or .json rows, as a .txt or .md file of plain text, or as the name of a dataset "
|
|
67
|
+
"on Hugging Face (user/name)")
|
|
68
|
+
if split != "train" or subset:
|
|
69
|
+
raise ValueError(f"{data} is a file: split and subset are for datasets on Hugging Face")
|
|
70
|
+
with open(data, encoding="utf-8") as f:
|
|
71
|
+
if data.lower().endswith(".jsonl"):
|
|
72
|
+
return [json.loads(line) for line in f if line.strip()]
|
|
73
|
+
if not data.lower().endswith(".json"):
|
|
74
|
+
return [f.read()]
|
|
75
|
+
rows = json.load(f)
|
|
76
|
+
if not isinstance(rows, list):
|
|
77
|
+
raise ValueError(f"{data}: a .json file must hold a list of rows")
|
|
78
|
+
return rows
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _example(row):
|
|
82
|
+
if isinstance(row, str):
|
|
83
|
+
return row
|
|
84
|
+
if isinstance(row, list):
|
|
85
|
+
return _chat(row)
|
|
86
|
+
if not isinstance(row, dict):
|
|
87
|
+
raise ValueError(f"expected a string or an object, got {type(row).__name__}")
|
|
88
|
+
if row.get("messages"):
|
|
89
|
+
return _chat(row["messages"])
|
|
90
|
+
if isinstance(row.get("text"), str):
|
|
91
|
+
return row["text"]
|
|
92
|
+
if row.get("conversations"):
|
|
93
|
+
return _headed(row, _chat(row["conversations"]))
|
|
94
|
+
for ask, reply in PAIRS:
|
|
95
|
+
if _given(row.get(ask)) and _given(row.get(reply)):
|
|
96
|
+
return _headed(row, _turns(_asked(row, ask), "user") + _turns(row[reply], "assistant"))
|
|
97
|
+
if row.get("messages") == [] or row.get("conversations") == [] or \
|
|
98
|
+
any(ask in row and reply in row and _blank(row[ask], row[reply]) for ask, reply in PAIRS):
|
|
99
|
+
raise EmptyRow
|
|
100
|
+
if "chosen" in row and "rejected" in row:
|
|
101
|
+
raise ValueError("this is a preference row (chosen and rejected): train on it with method dpo, ipo, simpo or orpo")
|
|
102
|
+
raise ValueError(f"it has {', '.join(map(repr, row)) or 'no fields'}; a row needs {KNOWN}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _preference(row) -> dict:
|
|
106
|
+
if isinstance(row, dict) and "chosen" in row and "rejected" in row and _blank(row["chosen"], row["rejected"]):
|
|
107
|
+
raise EmptyRow
|
|
108
|
+
if not isinstance(row, dict) or not _given(row.get("chosen")) or not _given(row.get("rejected")):
|
|
109
|
+
raise ValueError("a preference row needs 'prompt', 'chosen' and 'rejected'")
|
|
110
|
+
asked = next((k for k in PROMPTS if _given(row.get(k))), None)
|
|
111
|
+
prompt = _turns(_asked(row, asked), "user") if asked else _chat(row.get("conversations") or [])
|
|
112
|
+
out = {}
|
|
113
|
+
for side in ("chosen", "rejected"):
|
|
114
|
+
reply = _turns(row[side], "assistant")
|
|
115
|
+
whole = reply[0]["role"] != "assistant"
|
|
116
|
+
if not whole and not any(m["role"] == "user" for m in prompt):
|
|
117
|
+
raise ValueError(f"there is no prompt: give it as 'prompt', or as the first messages of '{side}'")
|
|
118
|
+
out[side] = _headed(row, reply if whole else prompt + reply)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _given(value) -> bool:
|
|
123
|
+
return isinstance(value, (str, list, dict)) and bool(value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _blank(*values) -> bool:
|
|
127
|
+
return any(not v for v in values) and all(v is None or isinstance(v, (str, list, dict)) for v in values)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _asked(row: dict, key: str):
|
|
131
|
+
extra = (row.get("input") or row.get("context")) if key == "instruction" else None
|
|
132
|
+
return f"{row[key]}\n\n{extra}" if extra and isinstance(extra, str) and isinstance(row[key], str) else row[key]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _headed(row: dict, chat: list[dict]) -> list[dict]:
|
|
136
|
+
text = row.get("system")
|
|
137
|
+
if not text or not isinstance(text, str) or chat[0]["role"] == "system":
|
|
138
|
+
return chat
|
|
139
|
+
return [{"role": "system", "content": text}] + chat
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _turns(value, role: str) -> list[dict]:
|
|
143
|
+
if isinstance(value, str):
|
|
144
|
+
return [{"role": role, "content": value}]
|
|
145
|
+
return _chat([value] if isinstance(value, dict) else value)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _chat(turns: list) -> list[dict]:
|
|
149
|
+
out = []
|
|
150
|
+
for turn in turns:
|
|
151
|
+
if not isinstance(turn, dict):
|
|
152
|
+
raise ValueError(f"a conversation holds messages, not {type(turn).__name__}")
|
|
153
|
+
if "role" in turn:
|
|
154
|
+
out.append(turn)
|
|
155
|
+
continue
|
|
156
|
+
if "from" not in turn or "value" not in turn:
|
|
157
|
+
raise ValueError("a message needs 'role' and 'content', or 'from' and 'value'")
|
|
158
|
+
role = ROLES.get(str(turn["from"]).lower())
|
|
159
|
+
if role is None:
|
|
160
|
+
raise ValueError(f"unknown speaker {turn['from']!r} (known: {', '.join(ROLES)})")
|
|
161
|
+
out.append({"role": role, "content": turn["value"]})
|
|
162
|
+
return out
|
|
@@ -180,29 +180,6 @@ def build_job(model: str, mlx_model: str | None = None, mode: str = "lora", rank
|
|
|
180
180
|
return job
|
|
181
181
|
|
|
182
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
183
|
def _render(tokenizer, messages: list[dict], prompt: bool = False) -> str:
|
|
207
184
|
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=prompt)
|
|
208
185
|
|
|
@@ -1,37 +1,14 @@
|
|
|
1
|
-
import json
|
|
2
1
|
import random
|
|
3
2
|
|
|
4
3
|
import numpy as np
|
|
5
4
|
|
|
6
|
-
from .
|
|
7
|
-
|
|
8
|
-
PREFERENCE = ("dpo", "ipo", "simpo", "orpo")
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
def _load(data):
|
|
12
|
-
if isinstance(data, str):
|
|
13
|
-
if data.endswith((".jsonl", ".json")) and _is_preference_file(data):
|
|
14
|
-
with open(data, encoding="utf-8") as f:
|
|
15
|
-
return [json.loads(line) for line in f if line.strip()] if data.endswith(".jsonl") else json.load(f)
|
|
16
|
-
return load_rows(data)
|
|
17
|
-
if hasattr(data, "to_list"):
|
|
18
|
-
return data.to_list()
|
|
19
|
-
return list(data)
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _is_preference_file(path: str) -> bool:
|
|
23
|
-
with open(path, encoding="utf-8") as f:
|
|
24
|
-
first = f.readline() if path.endswith(".jsonl") else f.read(4096)
|
|
25
|
-
return '"chosen"' in first and '"rejected"' in first
|
|
5
|
+
from .data import PREFERENCE, load
|
|
6
|
+
from .job import encode_row
|
|
26
7
|
|
|
27
8
|
|
|
28
9
|
def _pack(rows: list, tokenizer, seq: int, assistant_only: bool) -> tuple[np.ndarray, np.ndarray]:
|
|
29
10
|
stream, targets = [], []
|
|
30
11
|
for row in rows:
|
|
31
|
-
if isinstance(row, dict) and "messages" in row:
|
|
32
|
-
row = row["messages"]
|
|
33
|
-
elif isinstance(row, dict) and "text" in row:
|
|
34
|
-
row = row["text"]
|
|
35
12
|
ids, labels = encode_row(tokenizer, row, assistant_only)
|
|
36
13
|
stream.extend(ids)
|
|
37
14
|
targets.extend(labels)
|
|
@@ -41,16 +18,10 @@ def _pack(rows: list, tokenizer, seq: int, assistant_only: bool) -> tuple[np.nda
|
|
|
41
18
|
return np.array(stream[:count * seq]).reshape(count, seq), np.array(targets[:count * seq]).reshape(count, seq)
|
|
42
19
|
|
|
43
20
|
|
|
44
|
-
def _messages(prompt, reply) -> list[dict]:
|
|
45
|
-
head = prompt if isinstance(prompt, list) else [{"role": "user", "content": prompt}]
|
|
46
|
-
tail = reply if isinstance(reply, list) else [{"role": "assistant", "content": reply}]
|
|
47
|
-
return head + tail
|
|
48
|
-
|
|
49
|
-
|
|
50
21
|
def _pair(tokenizer, row: dict, seq: int) -> tuple:
|
|
51
22
|
out = []
|
|
52
23
|
for side in ("chosen", "rejected"):
|
|
53
|
-
ids, labels = encode_row(tokenizer,
|
|
24
|
+
ids, labels = encode_row(tokenizer, row[side])
|
|
54
25
|
out.append((ids[:seq], labels[:seq]))
|
|
55
26
|
return out
|
|
56
27
|
|
|
@@ -63,7 +34,7 @@ def _tell_length(run, total: int):
|
|
|
63
34
|
|
|
64
35
|
|
|
65
36
|
def train(run, data, method="sft", steps=None, epochs=1.0, batch_size=8, seq=None, max_grad_norm=1.0, beta=None, on_step=None, seed=0,
|
|
66
|
-
assistant_only=True, gamma=0.5, lam=0.1, start_step=0, reference=None, **kw):
|
|
37
|
+
assistant_only=True, gamma=0.5, lam=0.1, start_step=0, reference=None, split="train", subset=None, **kw):
|
|
67
38
|
from . import losses
|
|
68
39
|
if kw:
|
|
69
40
|
raise TypeError(f"train() got unknown settings: {', '.join(sorted(kw))}")
|
|
@@ -73,7 +44,7 @@ def train(run, data, method="sft", steps=None, epochs=1.0, batch_size=8, seq=Non
|
|
|
73
44
|
if tok is None:
|
|
74
45
|
raise ValueError("this run has no tokenizer; pass tokenized batches to forward_backward instead")
|
|
75
46
|
seq = seq or run.job.get("seq", 512)
|
|
76
|
-
rows =
|
|
47
|
+
rows = load(data, method, split, subset)
|
|
77
48
|
rng = random.Random(seed)
|
|
78
49
|
history = []
|
|
79
50
|
if method in ("sft", "cpt"):
|
|
@@ -95,8 +66,6 @@ def train(run, data, method="sft", steps=None, epochs=1.0, batch_size=8, seq=Non
|
|
|
95
66
|
if on_step:
|
|
96
67
|
on_step(record)
|
|
97
68
|
return history
|
|
98
|
-
if method not in PREFERENCE:
|
|
99
|
-
raise ValueError(f"method must be one of sft, cpt, {', '.join(PREFERENCE)}")
|
|
100
69
|
import torch
|
|
101
70
|
pairs = [_pair(tok, row, seq) for row in rows]
|
|
102
71
|
pad = run.job.get("pad_id", 0)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|