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/trainers.py ADDED
@@ -0,0 +1,168 @@
1
+ import json
2
+ import random
3
+
4
+ import numpy as np
5
+
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
26
+
27
+
28
+ def _pack(rows: list, tokenizer, seq: int, assistant_only: bool) -> tuple[np.ndarray, np.ndarray]:
29
+ stream, targets = [], []
30
+ 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
+ ids, labels = encode_row(tokenizer, row, assistant_only)
36
+ stream.extend(ids)
37
+ targets.extend(labels)
38
+ count = len(stream) // seq
39
+ if count == 0:
40
+ raise ValueError(f"the data has {len(stream)} tokens, fewer than one sequence of {seq}")
41
+ return np.array(stream[:count * seq]).reshape(count, seq), np.array(targets[:count * seq]).reshape(count, seq)
42
+
43
+
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
+ def _pair(tokenizer, row: dict, seq: int) -> tuple:
51
+ out = []
52
+ for side in ("chosen", "rejected"):
53
+ ids, labels = encode_row(tokenizer, _messages(row["prompt"], row[side]))
54
+ out.append((ids[:seq], labels[:seq]))
55
+ return out
56
+
57
+
58
+ def _tell_length(run, total: int):
59
+ try:
60
+ run.pool.set_run(expected_steps=total)
61
+ except Exception:
62
+ pass
63
+
64
+
65
+ 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):
67
+ from . import losses
68
+ if kw:
69
+ raise TypeError(f"train() got unknown settings: {', '.join(sorted(kw))}")
70
+ if beta is None:
71
+ beta = 2.0 if method == "simpo" else 0.1
72
+ tok = run.tokenizer
73
+ if tok is None:
74
+ raise ValueError("this run has no tokenizer; pass tokenized batches to forward_backward instead")
75
+ seq = seq or run.job.get("seq", 512)
76
+ rows = _load(data)
77
+ rng = random.Random(seed)
78
+ history = []
79
+ if method in ("sft", "cpt"):
80
+ ids, labels = _pack(rows, tok, seq, assistant_only and method == "sft")
81
+ per_epoch = max(1, len(ids) // batch_size)
82
+ total = steps or max(1, int(per_epoch * epochs))
83
+ _tell_length(run, total)
84
+ order = list(range(len(ids)))
85
+ for step in range(total):
86
+ if step % per_epoch == 0:
87
+ rng.shuffle(order)
88
+ if step < start_step:
89
+ continue
90
+ pick = [order[(step * batch_size + i) % len(order)] for i in range(batch_size)]
91
+ out = run.forward_backward(ids[pick], labels[pick])
92
+ record = run.optim_step(lr=run.schedule(step, total), max_grad_norm=max_grad_norm, loss=out.loss)
93
+ record.update(at=step, total=total)
94
+ history.append(record)
95
+ if on_step:
96
+ on_step(record)
97
+ return history
98
+ if method not in PREFERENCE:
99
+ raise ValueError(f"method must be one of sft, cpt, {', '.join(PREFERENCE)}")
100
+ import torch
101
+ pairs = [_pair(tok, row, seq) for row in rows]
102
+ pad = run.job.get("pad_id", 0)
103
+
104
+ def batch(index):
105
+ chosen = [pairs[i][0] for i in index]
106
+ rejected = [pairs[i][1] for i in index]
107
+ both = chosen + rejected
108
+ length = max(len(ids) for ids, _ in both)
109
+ ids = np.full((len(both), length), pad, np.int64)
110
+ lab = np.full((len(both), length), -100, np.int64)
111
+ for r, (i, l) in enumerate(both):
112
+ ids[r, :len(i)], lab[r, :len(l)] = i, l
113
+ return ids, lab
114
+
115
+ if method in ("dpo", "ipo") and reference is not None:
116
+ reference = np.asarray(reference, np.float64)
117
+ if reference.shape != (len(pairs), 2):
118
+ raise ValueError(f"the saved reference log-probabilities are for {len(reference)} pairs, the data has {len(pairs)}")
119
+ elif method in ("dpo", "ipo"):
120
+ reference = np.zeros((len(pairs), 2), np.float64)
121
+ for start in range(0, len(pairs), batch_size):
122
+ index = list(range(start, min(len(pairs), start + batch_size)))
123
+ ids, lab = batch(index)
124
+ lp = run.forward(ids, lab, adapter=run.job.get("mode", "lora") == "full")
125
+ mask = (lab[:, 1:] != -100)
126
+ seqlp = (lp * mask).sum(-1)
127
+ n = len(index)
128
+ reference[index, 0], reference[index, 1] = seqlp[:n], seqlp[n:]
129
+ run.reference = reference
130
+ per_epoch = max(1, len(pairs) // batch_size)
131
+ total = steps or max(1, int(per_epoch * epochs))
132
+ _tell_length(run, total)
133
+ order = list(range(len(pairs)))
134
+ for step in range(total):
135
+ if step % per_epoch == 0:
136
+ rng.shuffle(order)
137
+ if step < start_step:
138
+ continue
139
+ index = [order[(step * batch_size + i) % len(order)] for i in range(batch_size)]
140
+ ids, lab = batch(index)
141
+ n = len(index)
142
+ ref = None if reference is None else torch.tensor(reference[index])
143
+ stats = {}
144
+
145
+ def loss_fn(lp, mask, _):
146
+ total_c = losses.sequence_logprob(lp[:n], mask[:n], average=method in ("simpo", "orpo"))
147
+ total_r = losses.sequence_logprob(lp[n:], mask[n:], average=method in ("simpo", "orpo"))
148
+ if method == "dpo":
149
+ value = losses.dpo(total_c, total_r, ref[:, 0], ref[:, 1], beta)
150
+ stats["reward_margin"] = float(beta * ((total_c.detach() - ref[:, 0]) - (total_r.detach() - ref[:, 1])).mean())
151
+ elif method == "ipo":
152
+ value = losses.ipo(total_c, total_r, ref[:, 0], ref[:, 1], beta)
153
+ elif method == "simpo":
154
+ value = losses.simpo(total_c, total_r, beta, gamma)
155
+ else:
156
+ value = losses.orpo(total_c, total_r, -total_c, lam)
157
+ stats["accuracy"] = float((total_c.detach() > total_r.detach()).float().mean()) if method in ("simpo", "orpo") else \
158
+ float(((total_c.detach() - ref[:, 0]) > (total_r.detach() - ref[:, 1])).float().mean())
159
+ return value
160
+ out = run.forward_backward(ids, lab, loss=loss_fn)
161
+ record = run.optim_step(lr=run.schedule(step, total), max_grad_norm=max_grad_norm, loss=out.loss)
162
+ record.update(stats)
163
+ record.update(at=step, total=total)
164
+ run.log(**stats, loss=out.loss)
165
+ history.append(record)
166
+ if on_step:
167
+ on_step(record)
168
+ return history
layerpool/tunnel.py ADDED
@@ -0,0 +1,165 @@
1
+ import hashlib
2
+ import os
3
+ import platform
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import tarfile
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ import urllib.request
12
+
13
+ from .codec import replace_file
14
+ from .net import ping
15
+
16
+ VERSION = "2026.10.7"
17
+ RELEASES = f"https://github.com/cloudflare/cloudflared/releases/download/{VERSION}/"
18
+ SHA256 = {
19
+ "cloudflared-darwin-amd64.tgz": "02f3edfd87684dd5b705607688e4eb4b323f6e777b81e7b3a85af556aa356848",
20
+ "cloudflared-darwin-arm64.tgz": "3586ccf397e98e5f437e60e7c307ca6ac463e110580503af8bb8e6f9ebf831bd",
21
+ "cloudflared-linux-386": "4823d2f038395617e04e4070601ab45c0c43f31f15ee7586be299e19ef49d46e",
22
+ "cloudflared-linux-amd64": "1f99fb518b83dec2ba8d870a7cc991d82a77e6196295a3d2754ba17ab9f91872",
23
+ "cloudflared-linux-arm": "74f690f6707182839b63e0465726c7776dd63f0a174390b911d5d71f35cab94e",
24
+ "cloudflared-linux-arm64": "3df43aedc9ff291d1735b5cb576cb97e0b157488796db2e32b28aecabb445775",
25
+ "cloudflared-windows-amd64.exe": "2493dbc168923bb3e59e5e7716f71deced92992eea9acd6e9d74f84ac7751343",
26
+ }
27
+ CACHE = os.path.join(os.path.expanduser("~"), ".cache", "layerpool")
28
+
29
+
30
+ def _bind_prctl():
31
+ """prctl, looked up once here: a child process after fork must only call it, not import or load anything."""
32
+ if platform.system() != "Linux":
33
+ return None
34
+ try:
35
+ import ctypes
36
+ return ctypes.CDLL(None, use_errno=True).prctl
37
+ except (OSError, AttributeError):
38
+ return None
39
+
40
+
41
+ _PRCTL = _bind_prctl()
42
+ _TERM = 15
43
+
44
+
45
+ def _die_with_parent():
46
+ _PRCTL(1, _TERM)
47
+
48
+
49
+ def child_options() -> dict:
50
+ """Popen options that end a helper process (cloudflared, systemd-inhibit) when layerpool is killed, on Linux; elsewhere
51
+ layerpool ends them when it exits."""
52
+ return {"preexec_fn": _die_with_parent} if _PRCTL is not None else {}
53
+
54
+
55
+ def _asset() -> str:
56
+ system, machine = platform.system().lower(), platform.machine().lower()
57
+ arch = "arm64" if machine in ("arm64", "aarch64") else "arm" if machine.startswith("arm") else "386" if machine in ("i386", "i686", "x86") else "amd64"
58
+ if system == "darwin":
59
+ return f"cloudflared-darwin-{arch}.tgz"
60
+ if system == "windows":
61
+ return "cloudflared-windows-amd64.exe"
62
+ return f"cloudflared-linux-{arch}"
63
+
64
+
65
+ def cloudflared() -> str:
66
+ found = shutil.which("cloudflared")
67
+ if found:
68
+ return found
69
+ name = f"cloudflared-{VERSION}" + (".exe" if platform.system() == "Windows" else "")
70
+ path = os.path.join(CACHE, name)
71
+ if os.path.exists(path):
72
+ return path
73
+ os.makedirs(CACHE, exist_ok=True)
74
+ asset = _asset()
75
+ with tempfile.TemporaryDirectory() as tmp:
76
+ download = os.path.join(tmp, asset)
77
+ with urllib.request.urlopen(RELEASES + asset, timeout=120) as r, open(download, "wb") as f:
78
+ shutil.copyfileobj(r, f)
79
+ with open(download, "rb") as f:
80
+ got = hashlib.sha256(f.read()).hexdigest()
81
+ if got != SHA256.get(asset):
82
+ raise RuntimeError(f"the downloaded {asset} does not match cloudflared {VERSION} (sha256 {got}); install cloudflared yourself "
83
+ "and put it on PATH")
84
+ if asset.endswith(".tgz"):
85
+ with tarfile.open(download) as archive:
86
+ member = next(m for m in archive.getmembers() if os.path.basename(m.name) == "cloudflared" and m.isfile())
87
+ with archive.extractfile(member) as src, open(download + ".bin", "wb") as dst:
88
+ shutil.copyfileobj(src, dst)
89
+ download += ".bin"
90
+ os.chmod(download, 0o755)
91
+ staged = f"{path}.{os.getpid()}.tmp"
92
+ shutil.copyfile(download, staged)
93
+ os.chmod(staged, 0o755)
94
+ try:
95
+ replace_file(staged, path)
96
+ except OSError:
97
+ os.remove(staged)
98
+ if not os.path.exists(path):
99
+ raise
100
+ return path
101
+
102
+
103
+ class Tunnel:
104
+ def __init__(self, port: int, timeout: float = 60.0, attempts: int = 3, log=None):
105
+ self.port = port
106
+ self.lines: list[str] = []
107
+ self.proc = None
108
+ log = log or (lambda *a: None)
109
+ binary = cloudflared()
110
+ for attempt in range(1, attempts + 1):
111
+ started = time.time()
112
+ log(f"opening a tunnel for port {port} (attempt {attempt} of {attempts}, this can take up to a minute)")
113
+ self.lines = []
114
+ self.proc = subprocess.Popen([binary, "tunnel", "--no-autoupdate", "--protocol", "http2", "--url", f"http://127.0.0.1:{port}"],
115
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
116
+ encoding="utf-8", errors="replace", **child_options())
117
+ threading.Thread(target=self._read, daemon=True).start()
118
+ try:
119
+ self.url = self._wait_url(timeout)
120
+ self._wait_reachable(timeout)
121
+ log(f"tunnel ready at {self.url} after {time.time() - started:.0f}s")
122
+ return
123
+ except RuntimeError as e:
124
+ log(f"tunnel attempt {attempt} failed: {str(e).splitlines()[0]}")
125
+ if attempt == attempts:
126
+ raise
127
+
128
+ def _read(self):
129
+ for line in self.proc.stdout:
130
+ self.lines.append(line)
131
+ if len(self.lines) > 400:
132
+ del self.lines[:200]
133
+
134
+ def _wait_url(self, timeout: float) -> str:
135
+ deadline = time.time() + timeout
136
+ while time.time() < deadline:
137
+ for line in self.lines:
138
+ found = re.search(r"https://(?!api\.)[a-z0-9-]+\.trycloudflare\.com", line)
139
+ if found:
140
+ return found.group(0)
141
+ if self.proc.poll() is not None:
142
+ break
143
+ time.sleep(0.2)
144
+ self.close()
145
+ raise RuntimeError("cloudflared did not give a tunnel address:\n" + "".join(self.lines[-20:]))
146
+
147
+ def _wait_reachable(self, timeout: float):
148
+ deadline = time.time() + timeout
149
+ while time.time() < deadline:
150
+ if ping(self.url, 10):
151
+ return
152
+ time.sleep(1)
153
+ self.close()
154
+ raise RuntimeError(f"the tunnel {self.url} did not become reachable within {timeout:.0f}s")
155
+
156
+ def alive(self) -> bool:
157
+ return self.proc is not None and self.proc.poll() is None
158
+
159
+ def close(self):
160
+ if self.proc.poll() is None:
161
+ self.proc.terminate()
162
+ try:
163
+ self.proc.wait(timeout=10)
164
+ except subprocess.TimeoutExpired:
165
+ self.proc.kill()