layerpool 0.1.0__tar.gz → 0.1.2__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 (33) hide show
  1. {layerpool-0.1.0 → layerpool-0.1.2}/PKG-INFO +38 -2
  2. {layerpool-0.1.0 → layerpool-0.1.2}/README.md +37 -1
  3. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/__init__.py +1 -1
  4. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/api.py +2 -1
  5. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/cli.py +12 -7
  6. layerpool-0.1.2/src/layerpool/data.py +162 -0
  7. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/job.py +0 -23
  8. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/net.py +17 -3
  9. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/trainers.py +5 -36
  10. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/tunnel.py +13 -0
  11. {layerpool-0.1.0 → layerpool-0.1.2}/.gitignore +0 -0
  12. {layerpool-0.1.0 → layerpool-0.1.2}/LICENSE +0 -0
  13. {layerpool-0.1.0 → layerpool-0.1.2}/pyproject.toml +0 -0
  14. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/__main__.py +0 -0
  15. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/backends/__init__.py +0 -0
  16. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/backends/common.py +0 -0
  17. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/backends/mlx_backend.py +0 -0
  18. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/blocks.py +0 -0
  19. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/codec.py +0 -0
  20. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/control.py +0 -0
  21. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/driver.py +0 -0
  22. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/export.py +0 -0
  23. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/fetch.py +0 -0
  24. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/hf.py +0 -0
  25. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/losses.py +0 -0
  26. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/planner.py +0 -0
  27. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/pool.py +0 -0
  28. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/selfcheck.py +0 -0
  29. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/telemetry.py +0 -0
  30. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/ui/app.js +0 -0
  31. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/ui/index.html +0 -0
  32. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/ui/style.css +0 -0
  33. {layerpool-0.1.0 → layerpool-0.1.2}/src/layerpool/worker.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: layerpool
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
@@ -52,10 +52,14 @@ Description-Content-Type: text/markdown
52
52
 
53
53
  One model, split by layers across all your machines. Their memory is pooled, and they train it as one.
54
54
 
55
- [![PyPI](https://img.shields.io/pypi/v/layerpool.svg)](https://pypi.org/project/layerpool/) [![Python](https://img.shields.io/pypi/pyversions/layerpool.svg)](https://pypi.org/project/layerpool/) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/abdallah-swe/layerpool/blob/main/LICENSE)
55
+ [![PyPI](https://img.shields.io/pypi/v/layerpool.svg?v=1)](https://pypi.org/project/layerpool/) [![Python](https://img.shields.io/pypi/pyversions/layerpool.svg?v=1)](https://pypi.org/project/layerpool/) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/abdallah-swe/layerpool/blob/main/LICENSE)
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>
@@ -11,10 +11,14 @@
11
11
 
12
12
  One model, split by layers across all your machines. Their memory is pooled, and they train it as one.
13
13
 
14
- [![PyPI](https://img.shields.io/pypi/v/layerpool.svg)](https://pypi.org/project/layerpool/) [![Python](https://img.shields.io/pypi/pyversions/layerpool.svg)](https://pypi.org/project/layerpool/) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/abdallah-swe/layerpool/blob/main/LICENSE)
14
+ [![PyPI](https://img.shields.io/pypi/v/layerpool.svg?v=1)](https://pypi.org/project/layerpool/) [![Python](https://img.shields.io/pypi/pyversions/layerpool.svg?v=1)](https://pypi.org/project/layerpool/) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/abdallah-swe/layerpool/blob/main/LICENSE)
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>
@@ -1,6 +1,6 @@
1
1
  import importlib
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.1.2"
4
4
 
5
5
 
6
6
  def __getattr__(name):
@@ -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
 
@@ -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", "weight_decay", "steps",
24
- "epochs", "batch_size", "seq", "micro", "micro_batch_size", "codec", "ckpt_every", "max_grad_norm", "beta", "out", "random_init", "train_on", "name",
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: chat rows ('messages'), text rows ('text'), or preference rows ('prompt', 'chosen', 'rejected')")
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(cfg["data"], method=method, steps=cfg.get("steps"), epochs=cfg.get("epochs", 1.0), batch_size=batch, seq=cfg.get("seq"),
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
 
@@ -318,6 +318,7 @@ def lan_ip() -> str:
318
318
  s.close()
319
319
 
320
320
 
321
+ QUICK_TUNNELS = ".trycloudflare.com"
321
322
  _resolved: dict[str, tuple[str, float]] = {}
322
323
 
323
324
 
@@ -336,9 +337,22 @@ def _ask_public_dns(host: str) -> str | None:
336
337
  return None
337
338
 
338
339
 
340
+ def _front_door(host: str) -> str | None:
341
+ """A quick tunnel is served by the same Cloudflare addresses as its parent domain, which find the tunnel by the host name sent
342
+ with TLS, so a tunnel answers there before its own name has spread through DNS."""
343
+ if not host.endswith(QUICK_TUNNELS):
344
+ return None
345
+ parent = QUICK_TUNNELS.lstrip(".")
346
+ try:
347
+ return socket.getaddrinfo(parent, None, socket.AF_INET)[0][4][0]
348
+ except socket.gaierror:
349
+ return _ask_public_dns(parent)
350
+
351
+
339
352
  def resolve(host: str) -> str:
340
- """The address to connect to. A fresh tunnel name is often cached as missing by the local resolver for many
341
- minutes, so when the system cannot find a name, ask public DNS over HTTPS instead."""
353
+ """The address to connect to. A fresh tunnel name is often cached as missing by the local resolver for many minutes, so when
354
+ the system cannot find a name, ask public DNS over HTTPS instead. Public DNS can hold the same miss for about a minute: a quick
355
+ tunnel is then reached through its parent domain."""
342
356
  try:
343
357
  socket.getaddrinfo(host, None)
344
358
  return host
@@ -346,7 +360,7 @@ def resolve(host: str) -> str:
346
360
  cached = _resolved.get(host)
347
361
  if cached and cached[1] > time.time():
348
362
  return cached[0]
349
- ip = _ask_public_dns(host)
363
+ ip = _ask_public_dns(host) or _front_door(host)
350
364
  if ip is None:
351
365
  raise
352
366
  _resolved[host] = (ip, time.time() + 300)
@@ -1,37 +1,14 @@
1
- import json
2
1
  import random
3
2
 
4
3
  import numpy as np
5
4
 
6
- from .job import encode_row, load_rows
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, _messages(row["prompt"], row[side]))
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 = _load(data)
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)
@@ -24,6 +24,7 @@ SHA256 = {
24
24
  "cloudflared-linux-arm64": "3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775",
25
25
  "cloudflared-windows-amd64.exe": "2493dbc168923bb3e59e5e7716f71deced92992eea9acd6e9d74f84ac7751343",
26
26
  }
27
+ SETTLE_S = 3.0
27
28
  CACHE = os.path.join(os.path.expanduser("~"), ".cache", "layerpool")
28
29
 
29
30
 
@@ -117,6 +118,8 @@ class Tunnel:
117
118
  threading.Thread(target=self._read, daemon=True).start()
118
119
  try:
119
120
  self.url = self._wait_url(timeout)
121
+ self._wait_registered(20)
122
+ time.sleep(SETTLE_S)
120
123
  self._wait_reachable(timeout)
121
124
  log(f"tunnel ready at {self.url} after {time.time() - started:.0f}s")
122
125
  return
@@ -144,6 +147,16 @@ class Tunnel:
144
147
  self.close()
145
148
  raise RuntimeError("cloudflared did not give a tunnel address:\n" + "".join(self.lines[-20:]))
146
149
 
150
+ def _wait_registered(self, timeout: float):
151
+ """The address is printed before the tunnel is connected. Asking for it that early makes Cloudflare and DNS servers remember
152
+ for up to a minute that it does not exist, so wait until cloudflared says it is connected (or, if it never says so, for
153
+ `timeout` seconds). Cloudflare's servers learn of it a moment later still: SETTLE_S."""
154
+ deadline = time.time() + timeout
155
+ while time.time() < deadline and self.proc.poll() is None:
156
+ if any("Registered tunnel connection" in line for line in list(self.lines)):
157
+ return
158
+ time.sleep(0.1)
159
+
147
160
  def _wait_reachable(self, timeout: float):
148
161
  deadline = time.time() + timeout
149
162
  while time.time() < deadline:
File without changes
File without changes
File without changes
File without changes