shipyard-rl 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.
- shipyard/README.md +24 -0
- shipyard/__init__.py +18 -0
- shipyard/cli.py +291 -0
- shipyard/config.py +410 -0
- shipyard/env.example +48 -0
- shipyard/groups.py +289 -0
- shipyard/jobs/README.md +27 -0
- shipyard/jobs/__init__.py +1 -0
- shipyard/jobs/admit.py +134 -0
- shipyard/jobs/engine.py +497 -0
- shipyard/jobs/file.py +280 -0
- shipyard/jobs/harnesses.py +255 -0
- shipyard/jobs/hooks.py +90 -0
- shipyard/jobs/modules.py +327 -0
- shipyard/jobs/progress.py +53 -0
- shipyard/jobs/runner.py +230 -0
- shipyard/jobs/secrets.py +113 -0
- shipyard/jobs/together.py +562 -0
- shipyard/model.py +177 -0
- shipyard/models/README.md +21 -0
- shipyard/models/__init__.py +0 -0
- shipyard/models/backends.py +317 -0
- shipyard/models/clients/__init__.py +37 -0
- shipyard/models/clients/tinker.py +421 -0
- shipyard/models/clients/together.py +439 -0
- shipyard/models/endpoints.py +388 -0
- shipyard/py.typed +0 -0
- shipyard/recipes/README.md +50 -0
- shipyard/recipes/dapo/README.md +18 -0
- shipyard/recipes/dapo/run.toml +32 -0
- shipyard/recipes/dapo/trainer.py +108 -0
- shipyard/recipes/dapo-async/README.md +18 -0
- shipyard/recipes/dapo-async/run.toml +36 -0
- shipyard/recipes/dapo-async/trainer.py +155 -0
- shipyard/recipes/gepa/README.md +18 -0
- shipyard/recipes/gepa/modules/PROMPT.md +1 -0
- shipyard/recipes/gepa/reflect.py +109 -0
- shipyard/recipes/gepa/run.toml +34 -0
- shipyard/recipes/gepa/trainer.py +219 -0
- shipyard/recipes/grpo/README.md +18 -0
- shipyard/recipes/grpo/run.toml +24 -0
- shipyard/recipes/grpo/trainer.py +53 -0
- shipyard/recipes/opd/README.md +18 -0
- shipyard/recipes/opd/run.toml +28 -0
- shipyard/recipes/opd/trainer.py +56 -0
- shipyard/recipes/rft-async/README.md +19 -0
- shipyard/recipes/rft-async/run.toml +40 -0
- shipyard/recipes/rft-async/trainer.py +127 -0
- shipyard/records.py +198 -0
- shipyard/run/README.md +24 -0
- shipyard/run/__init__.py +0 -0
- shipyard/run/checkpoint.py +93 -0
- shipyard/run/costs.py +178 -0
- shipyard/run/data.py +183 -0
- shipyard/run/directory.py +243 -0
- shipyard/run/dry.py +197 -0
- shipyard/run/files.py +90 -0
- shipyard/run/logs.py +304 -0
- shipyard/state.py +39 -0
- shipyard/trainer.py +572 -0
- shipyard_rl-0.1.0.dist-info/METADATA +100 -0
- shipyard_rl-0.1.0.dist-info/RECORD +65 -0
- shipyard_rl-0.1.0.dist-info/WHEEL +4 -0
- shipyard_rl-0.1.0.dist-info/entry_points.txt +2 -0
- shipyard_rl-0.1.0.dist-info/licenses/LICENSE +202 -0
shipyard/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# shipyard
|
|
2
|
+
|
|
3
|
+
Recipes are implemented as subclasses of `Trainer`. Each recipe writes `step`, from three primitives, `draw`, `rollout` and `update`, and its own scoring; and `evaluate`, when its config has a test set. It reads the models its config names as `self.models[role]` and marks the ones it trains with `training = True`. The trainer does the rest: it opens each model's session and the proxy, takes the steps, evaluates on schedule, checkpoints, logs and resumes.
|
|
4
|
+
|
|
5
|
+
```mermaid
|
|
6
|
+
flowchart LR
|
|
7
|
+
draw["draw()"] -->|tasks| rollout["rollout(tasks, model, harness, ...)"]
|
|
8
|
+
rollout -->|groups| score["the recipe's scoring"]
|
|
9
|
+
score -->|advantages| update["update(model, groups)"]
|
|
10
|
+
update -.->|new weights| rollout
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
| File | Holds |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `trainer.py` | `Trainer`: the primitives, the run loop, its evaluation schedule and checkpoints; the recipe writes `step` and `evaluate` |
|
|
16
|
+
| `model.py` | `Model`, a model the config names under a role, which the recipe rolls out, scores or trains; `Models`, the trainer's `self.models` |
|
|
17
|
+
| `groups.py` | `Group` → `Trial` → `Sequence`: what a rollout returns, and where advantages go |
|
|
18
|
+
| `records.py` | `Records`: what the proxy recorded of a trial's calls, read in one place: the facts a verdict reads, the chains a trial trains on, what its calls cost, and whether a job was served |
|
|
19
|
+
| `state.py` | `State`: what a checkpoint saves and a resume restores |
|
|
20
|
+
| `config.py` | `Config`, `ModelTable`, `Recipe`, `load`: a `run.toml`, checked against the recipe |
|
|
21
|
+
| `cli.py` | `shipyard init`, `run` and `resume` |
|
|
22
|
+
| [`models/`](models/README.md) | the models' backends, the training clients and the run's proxy |
|
|
23
|
+
| [`jobs/`](jobs/README.md) | Harbor jobs, harnesses, secrets and verdicts |
|
|
24
|
+
| [`run/`](run/README.md) | the run's directory: its logs, costs and checkpoints; and the tasks |
|
shipyard/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from shipyard.config import Config, load
|
|
2
|
+
from shipyard.groups import Group, Trial
|
|
3
|
+
from shipyard.jobs.harnesses import Harness
|
|
4
|
+
from shipyard.jobs.modules import Inadmissible, Modules
|
|
5
|
+
from shipyard.model import Model
|
|
6
|
+
from shipyard.trainer import Trainer
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Config",
|
|
10
|
+
"Group",
|
|
11
|
+
"Harness",
|
|
12
|
+
"Inadmissible",
|
|
13
|
+
"Model",
|
|
14
|
+
"Modules",
|
|
15
|
+
"Trainer",
|
|
16
|
+
"Trial",
|
|
17
|
+
"load",
|
|
18
|
+
]
|
shipyard/cli.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import shlex
|
|
6
|
+
import shutil
|
|
7
|
+
import signal
|
|
8
|
+
from collections.abc import Coroutine, Mapping, Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Annotated, Any
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
from dotenv import load_dotenv
|
|
14
|
+
from typer.core import TyperCommand
|
|
15
|
+
|
|
16
|
+
from shipyard.config import Config, ConfigError, config_file, load, shown
|
|
17
|
+
from shipyard.run.checkpoint import Checkpoint
|
|
18
|
+
from shipyard.run.directory import (
|
|
19
|
+
open_run,
|
|
20
|
+
recipe_of,
|
|
21
|
+
resumed,
|
|
22
|
+
running,
|
|
23
|
+
trainer_class,
|
|
24
|
+
trainer_in,
|
|
25
|
+
)
|
|
26
|
+
from shipyard.run.dry import checked
|
|
27
|
+
|
|
28
|
+
#: Where `init` copies the recipes, and the env template it writes, in the directory it runs in.
|
|
29
|
+
RECIPES = "recipes"
|
|
30
|
+
ENV_EXAMPLE = ".env.example"
|
|
31
|
+
#: What a first run needs once `init` has run.
|
|
32
|
+
NEXT = """
|
|
33
|
+
next:
|
|
34
|
+
cp .env.example .env # your keys
|
|
35
|
+
uvx modal setup # your Modal login, for the recipes' sandboxes
|
|
36
|
+
uvx harbor@0.24.0 datasets download reasoning-gym-easy -o tasks
|
|
37
|
+
shipyard run recipes/dapo # each recipe's README.md says what it needs"""
|
|
38
|
+
|
|
39
|
+
#: Where `run` keeps the config keys given as `--table.key VALUE`, in Click's context.
|
|
40
|
+
OVERRIDES = "shipyard.overrides"
|
|
41
|
+
#: What `run --help` says of them.
|
|
42
|
+
SETTABLE = (
|
|
43
|
+
"Any key of the config can be set for this run as --table.key VALUE, such as "
|
|
44
|
+
"--data.train swe-bench."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
app = typer.Typer(
|
|
48
|
+
help="Train with a recipe: a run.toml, and a trainer.py whose step it writes.",
|
|
49
|
+
no_args_is_help=True,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.callback()
|
|
54
|
+
def main() -> None:
|
|
55
|
+
load_dotenv(Path.cwd() / ".env", override=False) # the shell wins over the file
|
|
56
|
+
# Harbor sets its own logger to DEBUG for each trial's log file, and a record reaches the
|
|
57
|
+
# root's handlers whatever the root's level, so the console filters by its own.
|
|
58
|
+
console = logging.StreamHandler()
|
|
59
|
+
console.setLevel(logging.INFO)
|
|
60
|
+
logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=[console])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.command()
|
|
64
|
+
def init() -> None:
|
|
65
|
+
"""Copy the built-in recipes into ./recipes, and write ./.env.example, keeping what is there."""
|
|
66
|
+
try:
|
|
67
|
+
copied, kept, wrote = initialized(Path.cwd())
|
|
68
|
+
except FileNotFoundError as missing:
|
|
69
|
+
_refuse(missing)
|
|
70
|
+
if copied:
|
|
71
|
+
typer.echo(f"copied recipes/: {', '.join(copied)}")
|
|
72
|
+
if kept:
|
|
73
|
+
typer.echo(f"kept your recipes/: {', '.join(kept)}")
|
|
74
|
+
if wrote:
|
|
75
|
+
typer.echo(f"wrote {ENV_EXAMPLE}")
|
|
76
|
+
typer.echo(NEXT)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Overridable(TyperCommand):
|
|
80
|
+
"""A command that takes config keys as `--table.key VALUE`, before Typer parses the rest."""
|
|
81
|
+
|
|
82
|
+
def parse_args(self, ctx: typer.Context, args: list[str]) -> list[str]:
|
|
83
|
+
try:
|
|
84
|
+
ctx.meta[OVERRIDES], rest = overrides_in(args)
|
|
85
|
+
except ValueError as missing:
|
|
86
|
+
ctx.fail(str(missing))
|
|
87
|
+
return super().parse_args(ctx, rest)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.command(cls=Overridable, epilog=SETTABLE)
|
|
91
|
+
def run(
|
|
92
|
+
ctx: typer.Context,
|
|
93
|
+
config: Annotated[Path, typer.Argument(help="A run.toml, or the directory holding one.")],
|
|
94
|
+
trainer: Annotated[
|
|
95
|
+
Path | None,
|
|
96
|
+
typer.Argument(
|
|
97
|
+
help="A Python file defining one Trainer subclass; by default the trainer.py "
|
|
98
|
+
"beside the run.toml."
|
|
99
|
+
),
|
|
100
|
+
] = None,
|
|
101
|
+
root: Annotated[Path | None, typer.Option(help="Where runs live; default ./runs.")] = None,
|
|
102
|
+
dry: Annotated[
|
|
103
|
+
bool,
|
|
104
|
+
typer.Option(
|
|
105
|
+
"--dry",
|
|
106
|
+
help="Print the config as the run reads it, defaults included, and run the "
|
|
107
|
+
"checks the run makes before it opens anything; then stop, with no run made.",
|
|
108
|
+
),
|
|
109
|
+
] = False,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Run CONFIG, trained by TRAINER, by default the trainer.py beside it."""
|
|
112
|
+
overrides = ctx.meta.get(OVERRIDES)
|
|
113
|
+
if dry:
|
|
114
|
+
_dry(config, trainer, overrides)
|
|
115
|
+
return
|
|
116
|
+
try:
|
|
117
|
+
directory, loaded = open_run(config, root=root, trainer=trainer, overrides=overrides)
|
|
118
|
+
except (ConfigError, ValueError) as refused:
|
|
119
|
+
_refuse(refused)
|
|
120
|
+
made = trainer_class(directory).__name__
|
|
121
|
+
typer.echo(f"run {directory.name} in {directory.parent}, trained by {made}")
|
|
122
|
+
_train(directory, loaded)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@app.command()
|
|
126
|
+
def resume(
|
|
127
|
+
directory: Annotated[Path, typer.Argument(help="The run directory.")],
|
|
128
|
+
tag: Annotated[str, typer.Option(help="The checkpoint to go on from.")] = "last",
|
|
129
|
+
) -> None:
|
|
130
|
+
"""Go on from checkpoint TAG of the run in DIRECTORY, the last by default, in a new run."""
|
|
131
|
+
origin = Path(directory)
|
|
132
|
+
try:
|
|
133
|
+
going = resumed(origin, tag=tag)
|
|
134
|
+
except (ConfigError, ValueError) as refused:
|
|
135
|
+
_refuse(refused)
|
|
136
|
+
if going is None:
|
|
137
|
+
typer.echo(f"run {origin.name} finished at checkpoint {tag}: nothing is left to run")
|
|
138
|
+
return
|
|
139
|
+
directory, config, checkpoint = going
|
|
140
|
+
typer.echo(f"run {directory.name} goes on from {origin.name} at {checkpoint.tag}")
|
|
141
|
+
_train(directory, config, origin, checkpoint)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _dry(path: Path, trainer: Path | None, overrides: Mapping[str, str] | None) -> None:
|
|
145
|
+
"""Check the run as it would check itself before it opens anything, and print its config
|
|
146
|
+
with the values it would take: the TOML on stdout, what the check found on stderr. A config
|
|
147
|
+
the check refuses is printed as the file has it."""
|
|
148
|
+
try:
|
|
149
|
+
made = trainer_in(recipe_of(path, trainer))
|
|
150
|
+
loaded = load(path, made.Recipe, overrides)
|
|
151
|
+
except (ConfigError, ValueError) as refused:
|
|
152
|
+
_refuse(refused)
|
|
153
|
+
given = " ".join(shlex.join([f"--{name}", text]) for name, text in (overrides or {}).items())
|
|
154
|
+
read = f"{config_file(path)}" + (f" with {given}" if given else "")
|
|
155
|
+
header = f"# {read}, as {made.__name__} reads it\n\n"
|
|
156
|
+
try:
|
|
157
|
+
found = checked(made, loaded)
|
|
158
|
+
except (ValueError, KeyError, OSError) as refused: # KeyError: a model the recipe reads
|
|
159
|
+
typer.echo(header + shown(loaded), nl=False)
|
|
160
|
+
_refuse(refused)
|
|
161
|
+
typer.echo(header + shown(loaded, found.values), nl=False)
|
|
162
|
+
# Nothing opened: each model's backend was only asked its context length.
|
|
163
|
+
for one in found.warnings:
|
|
164
|
+
typer.echo(f"\n{one}", err=True)
|
|
165
|
+
if found.warnings:
|
|
166
|
+
typer.echo("\nthe run would stop as it opens its models; no run was made", err=True)
|
|
167
|
+
raise typer.Exit(1)
|
|
168
|
+
typer.echo("\nchecked: no run was made; the sandbox's credentials are not checked", err=True)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _train(
|
|
172
|
+
directory: Path,
|
|
173
|
+
config: Config,
|
|
174
|
+
origin: Path | None = None,
|
|
175
|
+
checkpoint: Checkpoint | None = None,
|
|
176
|
+
) -> None:
|
|
177
|
+
"""Train the run, from `checkpoint` of `origin` if given; exit 130 if a signal stops it."""
|
|
178
|
+
made = trainer_class(directory)
|
|
179
|
+
try:
|
|
180
|
+
# The trainer is made inside the process note, so a recipe's `__init__` that fails,
|
|
181
|
+
# such as on a missing [recipe] key, is recorded as the run's error.
|
|
182
|
+
with running(directory, trainer=made.__name__), made(config, directory) as trainer:
|
|
183
|
+
if origin is not None and checkpoint is not None:
|
|
184
|
+
trainer.restore(origin, checkpoint)
|
|
185
|
+
_until_stopped(trainer.run())
|
|
186
|
+
except KeyboardInterrupt as stopped:
|
|
187
|
+
typer.echo(f"run {directory.name} stopped: {str(stopped) or 'SIGINT'}", err=True)
|
|
188
|
+
raise typer.Exit(130) from None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def initialized(into: Path) -> tuple[list[str], list[str], bool]:
|
|
192
|
+
"""Copy the shipped recipes and `.env.example` that `into` lacks: (copied, kept, wrote)."""
|
|
193
|
+
recipes, env = shipped()
|
|
194
|
+
target = into / RECIPES
|
|
195
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
copied, kept = [], []
|
|
197
|
+
for one in sorted(path for path in recipes.iterdir() if path.is_dir()):
|
|
198
|
+
if one.name.startswith((".", "_")):
|
|
199
|
+
continue
|
|
200
|
+
if (target / one.name).exists():
|
|
201
|
+
kept.append(one.name)
|
|
202
|
+
continue
|
|
203
|
+
skipped = shutil.ignore_patterns("__pycache__", "*.pyc", ".*")
|
|
204
|
+
shutil.copytree(one, target / one.name, ignore=skipped)
|
|
205
|
+
copied.append(one.name)
|
|
206
|
+
if (recipes / "README.md").is_file() and not (target / "README.md").exists():
|
|
207
|
+
shutil.copyfile(recipes / "README.md", target / "README.md")
|
|
208
|
+
wrote = not (into / ENV_EXAMPLE).exists()
|
|
209
|
+
if wrote:
|
|
210
|
+
shutil.copyfile(env, into / ENV_EXAMPLE)
|
|
211
|
+
return copied, kept, wrote
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def shipped() -> tuple[Path, Path]:
|
|
215
|
+
"""Return the recipes and env template `init` copies: the package's, else the checkout's."""
|
|
216
|
+
package = Path(__file__).resolve().parent
|
|
217
|
+
checkout = package.parents[1]
|
|
218
|
+
for recipes, env in (
|
|
219
|
+
(package / RECIPES, package / "env.example"),
|
|
220
|
+
(checkout / RECIPES, checkout / ENV_EXAMPLE),
|
|
221
|
+
):
|
|
222
|
+
if recipes.is_dir() and env.is_file():
|
|
223
|
+
return recipes, env
|
|
224
|
+
raise FileNotFoundError(
|
|
225
|
+
"this install of shipyard ships no recipes: reinstall it, or clone the repository"
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _until_stopped(work: Coroutine[Any, Any, None]) -> None:
|
|
230
|
+
"""Run `work`, which SIGTERM and SIGHUP stop as Ctrl-C does."""
|
|
231
|
+
caught: list[str] = []
|
|
232
|
+
|
|
233
|
+
async def main() -> None:
|
|
234
|
+
loop, task = asyncio.get_running_loop(), asyncio.current_task()
|
|
235
|
+
previous: dict[int, Any] = {}
|
|
236
|
+
for name in ("SIGTERM", "SIGHUP"):
|
|
237
|
+
number = getattr(signal, name, None)
|
|
238
|
+
if number is None or task is None:
|
|
239
|
+
continue
|
|
240
|
+
handler = signal.getsignal(number)
|
|
241
|
+
try:
|
|
242
|
+
loop.add_signal_handler(number, _stop, task, caught, name)
|
|
243
|
+
except (NotImplementedError, RuntimeError, ValueError):
|
|
244
|
+
continue # not the main thread, or a loop that cannot take signals
|
|
245
|
+
previous[number] = handler
|
|
246
|
+
try:
|
|
247
|
+
await work
|
|
248
|
+
finally:
|
|
249
|
+
for number, handler in previous.items():
|
|
250
|
+
loop.remove_signal_handler(number)
|
|
251
|
+
signal.signal(number, handler)
|
|
252
|
+
|
|
253
|
+
try:
|
|
254
|
+
asyncio.run(main())
|
|
255
|
+
except asyncio.CancelledError:
|
|
256
|
+
if caught:
|
|
257
|
+
raise KeyboardInterrupt(caught[0]) from None
|
|
258
|
+
raise
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _stop(task: asyncio.Task[Any], caught: list[str], name: str) -> None:
|
|
262
|
+
caught.append(name)
|
|
263
|
+
task.cancel()
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def overrides_in(args: Sequence[str]) -> tuple[dict[str, str], list[str]]:
|
|
267
|
+
"""Return the `--table.key VALUE` and `--table.key=VALUE` flags in `args`, and the rest."""
|
|
268
|
+
found: dict[str, str] = {}
|
|
269
|
+
rest: list[str] = []
|
|
270
|
+
tokens = iter(args)
|
|
271
|
+
for one in tokens:
|
|
272
|
+
if one == "--":
|
|
273
|
+
rest += [one, *tokens]
|
|
274
|
+
break
|
|
275
|
+
name, given, value = one.partition("=")
|
|
276
|
+
if not (name.startswith("--") and "." in name):
|
|
277
|
+
rest.append(one)
|
|
278
|
+
continue
|
|
279
|
+
if not given:
|
|
280
|
+
value = next(tokens, "")
|
|
281
|
+
if not value or value.startswith("--"):
|
|
282
|
+
raise ValueError(f"{name} needs a value: {name} VALUE, or {name}=VALUE")
|
|
283
|
+
found[name.removeprefix("--")] = value
|
|
284
|
+
return found, rest
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _refuse(refused: Exception) -> None:
|
|
288
|
+
problems = refused.problems if isinstance(refused, ConfigError) else [str(refused)]
|
|
289
|
+
for one in problems:
|
|
290
|
+
typer.echo(one, err=True)
|
|
291
|
+
raise typer.Exit(1)
|