[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EB1Q1Q88MT30C5PANJJXNP":3,"skill-same:01M7EB1Q1Q88MT30C5PANJJXNP":45},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7EB1Q1Q88MT30C5PANJJXNP","custom-recipes",null,"ghidav\u002Fshipyard","ghidav","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F131039402?v=4","01M7EB1MVEMCG9FHH5QH1TQXCD","Davide Ghilardi","01M7EB1MWGQ52M3GCC2HEJ0CXY",5,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fghidav\u002Fshipyard\u002Fblob\u002Fmain\u002Fskills\u002Fcustom-recipes\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: custom-recipes\ndescription: Shipyard recipes: the run.toml config and the Trainer subclass whose step a run takes, written from draw, rollout and update and the recipe's own scoring. Use when post-training a model with shipyard, or writing or changing a recipe.\n---\n\n# Custom recipes\n\nA **recipe** is a folder of two files: `run.toml`, the **config** holding every setting of a run, and `trainer.py`, defining one `Trainer` subclass that holds the algorithm. `shipyard run \u003Cfolder>` checks the config against the trainer before anything opens, runs it, and writes the run to `runs\u002F\u003Cfolder>__\u003Cid>\u002F`.\n\nStart from the shipped recipe closest to your algorithm; `shipyard init` copies them into `.\u002Frecipes`, each a worked example:\n\n| Recipe | Algorithm | Shows |\n| --- | --- | --- |\n| `grpo` | RL on the tests' rewards: each reward less its group's mean | the plain `step` and `score` |\n| `dapo` | RL with rewards normalized per group, every prompt weighing the same | `substeps`, a clipped loss, scaling advantages per group |\n| `dapo-async` | `dapo` with its rollouts overlapping its updates | an asynchronous loop: workers under `spawn`, a queue, groups taken in the order they finished, a staleness rule on `lag` |\n| `opd` | on-policy distillation: each token's advantage is the teacher's logprob less the agent's | a second model, scored with `logprobs` |\n| `gepa` | a search over the prompt and skills, no weight update | modules, a model asked for text through a Harbor task (`reflect.py`) |\n\n## run.toml\n\n| Table | Holds |\n| --- | --- |\n| `modules` (a top-level key) | a folder of `PROMPT.md` and `skills\u002F\u003Cname>\u002FSKILL.md`, relative to the config, that every trial carries |\n| `[models.\u003Crole>]` | one table per model the recipe reads, by **role** (`agent`, `teacher`, ...): `model`; `provider`, `tinker` (default) or `together`, which a run can train, or an API such as `anthropic`, which it only calls; `from_checkpoint`; `renderers`; for a model the recipe trains, `learning_rate` (required), `warmup`, `lora_rank`; sampling: `temperature`, `max_tokens`, `max_context`, ... |\n| `[data]` | `train` and `test`, dataset names: folders of Harbor tasks under `.\u002Ftasks`; `batch_size`, tasks a step; `seed` |\n| `[rollout]` | how trials run: `sandbox` (`docker` on this machine, or a cloud one such as `modal`), `concurrency` (trials sampling at once), `sandboxes` (trials alive at once, getting ready or running tests while others sample), `timeout`, `setup_timeout`, `secrets` |\n| `[recipe]` | `steps`, `substeps`, `evaluate_every`, `grade_timeouts`, and the trainer's own keys, such as its `harness` and `group_size` |\n| `[checkpoints]` | `every` this many steps; `ttl_hours` a save lives |\n| `[logging.wandb]` | `project`, `entity` |\n\n- Every table refuses keys it does not know, and a key that moved says where to. `shipyard run` lists every problem in the config before anything opens, so its message answers what a key may be. Every key, with a comment on each, is in `shipyard\u002Fconfig.py` in the installed package.\n- Any key can be set for one run: `shipyard run recipes\u002Fmine --data.batch_size 2 --recipe.steps 1`. The run's own `run.toml` keeps the overrides, so a resume does too.\n- A harness is `\"pi@0.85.1\"`, a name pinned at a version, or a table with `name`, `env` and `kwargs`.\n- `[rollout.secrets]` leases per-trial credentials: `NAME = \"POOL\"` gives each trial in flight one value of this machine's variable `POOL` (values separated by commas or whitespace) as `NAME`, in its sandbox and its verifier, so no more trials run at once than `POOL` holds.\n\n## Trainer\n\n```python\nfrom collections.abc import Sequence\nfrom pathlib import Path\n\nfrom shipyard import Config, Group, Harness, Trainer\n\n\nclass MyTrainer(Trainer):\n    class Recipe(Trainer.Recipe):\n        harness: Harness  # no default: run.toml must set it, under [recipe]\n        group_size: int\n        coef: float = 1.0\n\n    class State(Trainer.State):\n        solved: dict[str, int] = {}  # each field has a default\n\n    def __init__(self, config: Config, directory: Path) -> None:\n        super().__init__(config, directory)\n        self.agent = self.models[\"agent\"]  # [models.agent]\n        self.agent.training = True  # this run trains it\n        self.teacher = self.models[\"teacher\"]  # [models.teacher], only scored with\n\n    async def step(self) -> None:\n        groups = await self.rollout(\n            self.draw(),\n            model=self.agent,\n            harness=self.recipe.harness,\n            attempts=self.recipe.group_size,\n            modules=self.state.modules,\n        )\n        await self.score(groups)\n        await self.update(self.agent, groups)\n\n    async def score(self, groups: Sequence[Group]) -> None: ...\n```\n\n- `trainer.py` defines one `Trainer` subclass. Its folder loads as a package, so helper files beside it import relatively: `from .helpers import shaped`.\n- `Recipe` declares the recipe's own `[recipe]` keys. A nested table such as `[recipe.reflector]` is a field typed by a pydantic model, as in gepa's `reflect.py`.\n- The recipe writes `step`, and `evaluate(self, tasks) -> list[Group]` when the config has `[data] test`; `score` is the recipe's own method, called from its `step`. The run refuses a trainer missing either.\n- Read every model the config names in `__init__`, as `self.models[role]`, and set `training = True` there on each one the recipe trains: the run refuses a model the recipe never reads, a model in training with no `learning_rate`, and `training` set once the run has opened the model.\n- On the trainer: `self.recipe`, the `[recipe]` table as your `Recipe`; `self.config`, the whole `run.toml`; `self.state`, your `State`; `self.models`; `self.lender.train` and `.test`, every task path.\n- The run does the rest. It opens each model and the proxy, calls `step` `[recipe] steps` times, evaluates the test set every `evaluate_every` steps from step 0 and after the last, checkpoints every `[checkpoints] every` steps and at the end, and writes a row per step, and one per evaluation at the step whose weights it measured, to `metrics.jsonl`. An evaluation runs beside the next step's `update`, every call of its trials on the weights it measures, so `update` is where a recipe's step lets it run; on Together, which serves one version, `update` serves its new weights once the evaluation has finished.\n\n## The primitives\n\n### draw\n\n`self.draw()` returns the next batch: `[data] batch_size` task paths, shuffled once per pass over the tasks with `[data] seed`; `self.draw(1)` one task. A task is out until a rollout returns its group, and the state keeps what is out, so a resumed run gives those first and goes on in the same order. `self.lender.back(task)` gives a task out again before new ones; `self.lender.retire(task)` gives it out no more, as for one the agent always solves.\n\nOverride it for a curriculum: return any list of task directories, such as some of `self.lender.train`, and keep what the choice reads (counts, scores) in your `State`. A task's instruction is readable before any rollout, at `task \u002F \"instruction.md\"`.\n\n### rollout\n\n`await self.rollout(tasks, model=..., harness=..., attempts=..., modules=...)` runs `model` on each task `attempts` times through `harness`, in Harbor sandboxes, as one job, and returns a `Group` per task, in order. Each group holds `attempts` **trials**, each graded by the task's tests.\n\n- `modules=`: `self.state.modules` for the run's own prompt and skills, `None` for none, or any `Modules`.\n- `renderer=`: one of the model's `renderers`; a model with several must be given one.\n- `purpose=`: the job's label: `training` unless `evaluate` makes the rollout, or one you name.\n- A recipe that wants several harnesses or renderers runs several rollouts, at once with `asyncio.gather`, and puts their groups together as it means them.\n- Any model the run holds can be rolled out, a provider's model through its harness with the harness's own credentials. To ask a model for text, write a Harbor task (`instruction.md`, `task.toml`, `environment\u002F`, `tests\u002F`) whose tests copy what the model wrote into the trial's `verifier\u002F`, roll it out, and read it back from `trial.dir \u002F \"verifier\"`: gepa's `reflect.py`.\n\nRoll a batch out in one call, or one task a call from a loop of your own: shipyard keeps up to `[rollout] sandboxes` trials alive and `[rollout] concurrency` of them sampling, an evaluation's trials first, and raises once as many trials in a row as sample at once reached no model.\n\nEach model call takes the weights the model published last when the call starts, so a trial that outlives an `update` is answered by the weights before it and after. `seq.weights` names the weights that answered each of a sequence's spans, and `model.lag(group)` counts the times the model published since the oldest weights that answered the group's graded trials: 0 for a group of the weights it serves now. A loop that overlaps rollouts with updates reads it to drop or down-weight stale groups.\n\nA trial offers `reward`, `graded`, `sequences`, `sampled_tokens`, `instruction`, `transcript`, `steps` (Harbor's trajectory), `test_output`, `result` (Harbor's `result.json`, every key of the verifier's rewards under `verifier_result.rewards`) and `dir`. Its `transcript` includes the prompt and skills it carried, and `test_output` can print the tests' expected answers: filter both before a model reads them.\n\n### score\n\nScoring sets the **advantages**: a number per target token of each sequence, which `update` trains on. A trial's **sequences** are the chains of model calls it made, as the token ids the model read and sampled; `seq.targets` are the positions it sampled. A sequence trains only once it has advantages.\n\n- Per trial: `trial.set_advantage(x)` gives every target token of every sequence `x`. It rewrites them all, so call it before adding advantages of your own.\n- Per token: `seq.advantages = tensor`, one value per target.\n- From a model: `await model.logprobs(seqs)` returns each sequence's logprob at every target, as a tensor, for any model on Tinker or Together the run holds; it reads the agent's token ids, so it shares the agent's tokenizer.\n- From a group: `group.graded`, `group.rewards`, `group.reward_variance`, `group.centered_rewards`.\n- `self.metrics[\"name\"] = value` adds a number to this step's row.\n\n### update\n\n`await self.update(model, groups, loss=..., loss_config=...)` trains `model` on every sequence with advantages, then serves its new weights, which every call that starts from then on takes, an evaluation's excepted. It returns what it trained, or None when nothing was scored. Pass it every group the step took, the ones it drops included: the step's row counts what it was passed, scored or not.\n\n- `loss`: `importance_sampling` (the default); `ppo` and `cispo`, which take `clip_low_threshold` and `clip_high_threshold`, bounds on the ratio itself such as 0.8 and 1.2; `dro`, which takes `beta`; `cross_entropy`, which weighs each target by its advantage: supervised fine-tuning, with advantage 1 on what to imitate.\n- `[recipe] substeps`: optimizer steps per update, each on a share of the groups, whole groups each; the model's `learning_rate` and `warmup`; `ADAM = tinker.AdamParams(...)` as a class attribute.\n\nUpdate each model in training once a step: each call takes its optimizer steps, serves new weights and advances the warmup. The loss sums over tokens, so a long sequence weighs more than a short one; to weigh every group the same, scale its advantages, as dapo's `step` does. The ratio is taken against the sampler's logprobs, which the proxy recorded as the model sampled.\n\n### spawn\n\n`self.spawn(coroutine)` runs a coroutine as a task the run owns, beside the steps, and returns it: a worker that keeps rolling tasks out while the steps update, as an asynchronous loop needs, or any work a step awaits later. Spawn from `step`, once the run has started. `dapo-async` is the loop to copy: its first step spawns the workers, which hand their groups to the steps through a queue.\n\n- If it raises, the run fails at once with its error, even while a step waits on what it would have handed over.\n- When the run ends, it cancels the ones still running before the final checkpoint: their trials close, and the tasks they drew stay out, for a resume to give out first. A group a worker finished that no step passed to `update` is lost; its task comes back in a later pass.\n\n## Additional information\n\n### Graded and masked trials\n\nA trial is **masked** when its outcome says nothing about the agent: the sandbox, the grader or the model's server failed, or Harbor cut it at its timeout (`[recipe] grade_timeouts = true` grades those instead). A masked trial has no reward and no sequences, and `group.graded`, `group.rewards` and the row's `graded` leave it out. A group can hold fewer graded trials than its attempts, or none, so compute group statistics, and counts per task, over its graded trials. The row's `trials`, `graded` and `masked` show how many each step lost.\n\n### Recipe state and resuming\n\nWhat a recipe learns across steps (a bank, a curriculum's counts, a search's best) lives in its `State` fields. Every checkpoint saves `self.state`, and `shipyard resume runs\u002F\u003Crun>` starts a new run from the last checkpoint, `--tag step-\u003Cn>` from another. A field needs a default and a JSON value. A plain attribute starts empty again on a resume.\n\n### Models\n\nEvery model comes from the config by role, as `self.models[role]`, and does nothing until the run starts and binds it; using one before raises \"not connected yet\". Its role names its lane in the proxy and its rows in `usage.jsonl`.\n\n| Model | Runs on | `logprobs` | Trains |\n| --- | --- | --- | --- |\n| on Tinker or Together | a session on its training service, served through its lane of the run's proxy | yes | while `training` |\n| behind a provider's API, such as `provider = \"anthropic\"` | the provider's API, with its harness's own credentials | no | no |\n\n- `trainable` says whether a run could train it: a base model or a training state on Tinker or Together. Weights saved for sampling (`...\u002Fsampler_weights\u002F...`) are served and scored as they are.\n- `budget` is the most tokens one trial may sample, once the model is served.\n\n### Modules\n\n`modules` names a folder of `PROMPT.md` and `skills\u002F\u003Cname>\u002FSKILL.md`, which every trial carries into its harness. `Modules.read(folder)` reads one; `modules.texts` and `modules.with_texts({...})` read and replace their texts, raising `Inadmissible` for text a harness cannot be given; `self.keep(modules, \"best\")` writes them into the run; setting `self.state.modules` changes what the next rollouts carry.\n\n### Task hooks\n\nA task can carry a `hooks.py` beside its `task.toml`: code the run executes on this machine, outside the sandboxes, at events of each of the task's trials, such as setting up an outside system before the agent starts and tearing it down once the trial is done. Every recipe runs a task's hooks; the config names none.\n\n- A hook is `async def \u003Cevent>(event: TrialHookEvent)`, named after one of Harbor's trial events: `start`, `environment_start`, `agent_start`, `agent_end`, `verification_start`, `end` or `cancel`. Helpers start with `_`. Any other public function, or a hook that is not `async`, stops the run before anything opens.\n- `event.config` is the trial's own Harbor config: its leased secrets are in `event.config.environment.env`, its folder is `Path(event.config.trials_dir) \u002F event.config.trial_name`, and a value set in `event.config.verifier.env` reaches that trial's verifier alone, never its agent.\n- Harbor's rules apply. A hook that raises at `start` skips `end`; one that raises at `environment_start` masks its trial, and `end` still runs, so set-up belongs there; one that raises at `end` leaves the grade as it was. A hook has no time limit of its own, so bound what it waits on.\n- The run logs each hook it runs and how it ended.\n\n### The step's row\n\n`metrics.jsonl` holds a row per step, counting the groups the step passed to `update`, wherever they were rolled out: `trained`, `jobs` (the jobs they came from), `groups`, `trials`, `graded`, `masked`, `uniform` (groups with graded trials and nothing to train), `sequences`, `reward_mean`, `reward_spread`, `sampled_mean`, and the update's `train_tokens`, `kl_v1`, `kl_v2`, `entropy`, `learning_rate`, `substeps`, `loss` and `update_seconds`; a step that trained several models prefixes each one's update fields with its role. After an evaluation it holds `eval_` fields, and then `self.metrics`, which starts empty each step; a key that matches one of these is written as `recipe_\u003Ckey>`.\n\n`jobs.jsonl` holds a row per rollout, under the step it ran in, with `weights`: the weights that answered its calls, in the order the model published them. An evaluation's name the weights it measured.\n\n### Checking a recipe\n\n1. `shipyard run recipes\u002Fmine` refuses a wrong config, trainer or model before anything opens, listing every problem. Fix each until the run starts.\n2. Run one small step on this machine: `shipyard run recipes\u002Fmine --recipe.steps 1 --data.batch_size 2 --recipe.group_size 4 --rollout.sandbox docker`.\n\nThe recipe is checked when that run's `metrics.jsonl` holds one row with `graded` above 0 and `trained: true`. A row with `trained: false` and `uniform` equal to `groups` had nothing to learn, every group's rewards being equal: raise `group_size` or pick harder tasks, and run it again.\n","# Custom recipes\n\nA **recipe** is a folder of two files: `run.toml`, the **config** holding every setting of a run, and `trainer.py`, defining one `Trainer` subclass that holds the algorithm. `shipyard run \u003Cfolder>` checks the config against the trainer before anything opens, runs it, and writes the run to `runs\u002F\u003Cfolder>__\u003Cid>\u002F`.\n\nStart from the shipped recipe closest to your algorithm; `shipyard init` copies them into `.\u002Frecipes`, each a worked example:\n\n| Recipe | Algorithm | Shows |\n| --- | --- | --- |\n| `grpo` | RL on the tests' rewards: each reward less its group's mean | the plain `step` and `score` |\n| `dapo` | RL with rewards normalized per group, every prompt weighing the same | `substeps`, a clipped loss, scaling advantages per group |\n| `dapo-async` | `dapo` with its rollouts overlapping its updates | an asynchronous loop: workers under `spawn`, a queue, groups taken in the order they finished, a staleness rule on `lag` |\n| `opd` | on-policy distillation: each token's advantage is the teacher's logprob less the agent's | a second model, scored with `logprobs` |\n| `gepa` | a search over the prompt and skills, no weight update | modules, a model asked for text through a Harbor task (`reflect.py`) |\n\n## run.toml\n\n| Table | Holds |\n| --- | --- |\n| `modules` (a top-level key) | a folder of `PROMPT.md` and `skills\u002F\u003Cname>\u002FSKILL.md`, relative to the config, that every trial carries |\n| `[models.\u003Crole>]` | one table per model the recipe reads, by **role** (`agent`, `teacher`, ...): `model`; `provider`, `tinker` (default) or `together`, which a run can train, or an API such as `anthropic`, which it only calls; `from_checkpoint`; `renderers`; for a model the recipe trains, `learning_rate` (required), `warmup`, `lora_rank`; sampling: `temperature`, `max_tokens`, `max_context`, ... |\n| `[data]` | `train` and `test`, dataset names: folders of Harbor tasks under `.\u002Ftasks`; `batch_size`, tasks a step; `seed` |\n| `[rollout]` | how trials run: `sandbox` (`docker` on this machine, or a cloud one such as `modal`), `concurrency` (trials sampling at once), `sandboxes` (trials alive at once, getting ready or running tests while others sample), `timeout`, `setup_timeout`, `secrets` |\n| `[recipe]` | `steps`, `substeps`, `evaluate_every`, `grade_timeouts`, and the trainer's own keys, such as its `harness` and `group_size` |\n| `[checkpoints]` | `every` this many steps; `ttl_hours` a save lives |\n| `[logging.wandb]` | `project`, `entity` |\n\n- Every table refuses keys it does not know, and a key that moved says where to. `shipyard run` lists every problem in the config before anything opens, so its message answers what a key may be. Every key, with a comment on each, is in `shipyard\u002Fconfig.py` in the installed package.\n- Any key can be set for one run: `shipyard run recipes\u002Fmine --data.batch_size 2 --recipe.steps 1`. The run's own `run.toml` keeps the overrides, so a resume does too.\n- A harness is `\"pi@0.85.1\"`, a name pinned at a version, or a table with `name`, `env` and `kwargs`.\n- `[rollout.secrets]` leases per-trial credentials: `NAME = \"POOL\"` gives each trial in flight one value of this machine's variable `POOL` (values separated by commas or whitespace) as `NAME`, in its sandbox and its verifier, so no more trials run at once than `POOL` holds.\n\n## Trainer\n\n```python\nfrom collections.abc import Sequence\nfrom pathlib import Path\n\nfrom shipyard import Config, Group, Harness, Trainer\n\n\nclass MyTrainer(Trainer):\n    class Recipe(Trainer.Recipe):\n        harness: Harness  # no default: run.toml must set it, under [recipe]\n        group_size: int\n        coef: float = 1.0\n\n    class State(Trainer.State):\n        solved: dict[str, int] = {}  # each field has a default\n\n    def __init__(self, config: Config, directory: Path) -> None:\n        super().__init__(config, directory)\n        self.agent = self.models[\"agent\"]  # [models.agent]\n        self.agent.training = True  # this run trains it\n        self.teacher = self.models[\"teacher\"]  # [models.teacher], only scored with\n\n    async def step(self) -> None:\n        groups = await self.rollout(\n            self.draw(),\n            model=self.agent,\n            harness=self.recipe.harness,\n            attempts=self.recipe.group_size,\n            modules=self.state.modules,\n        )\n        await self.score(groups)\n        await self.update(self.agent, groups)\n\n    async def score(self, groups: Sequence[Group]) -> None: ...\n```\n\n- `trainer.py` defines one `Trainer` subclass. Its folder loads as a package, so helper files beside it import relatively: `from .helpers import shaped`.\n- `Recipe` declares the recipe's own `[recipe]` keys. A nested table such as `[recipe.reflector]` is a field typed by a pydantic model, as in gepa's `reflect.py`.\n- The recipe writes `step`, and `evaluate(self, tasks) -> list[Group]` when the config has `[data] test`; `score` is the recipe's own method, called from its `step`. The run refuses a trainer missing either.\n- Read every model the config names in `__init__`, as `self.models[role]`, and set `training = True` there on each one the recipe trains: the run refuses a model the recipe never reads, a model in training with no `learning_rate`, and `training` set once the run has opened the model.\n- On the trainer: `self.recipe`, the `[recipe]` table as your `Recipe`; `self.config`, the whole `run.toml`; `self.state`, your `State`; `self.models`; `self.lender.train` and `.test`, every task path.\n- The run does the rest. It opens each model and the proxy, calls `step` `[recipe] steps` times, evaluates the test set every `evaluate_every` steps from step 0 and after the last, checkpoints every `[checkpoints] every` steps and at the end, and writes a row per step, and one per evaluation at the step whose weights it measured, to `metrics.jsonl`. An evaluation runs beside the next step's `update`, every call of its trials on the weights it measures, so `update` is where a recipe's step lets it run; on Together, which serves one version, `update` serves its new weights once the evaluation has finished.\n\n## The primitives\n\n### draw\n\n`self.draw()` returns the next batch: `[data] batch_size` task paths, shuffled once per pass over the tasks with `[data] seed`; `self.draw(1)` one task. A task is out until a rollout returns its group, and the state keeps what is out, so a resumed run gives those first and goes on in the same order. `self.lender.back(task)` gives a task out again before new ones; `self.lender.retire(task)` gives it out no more, as for one the agent always solves.\n\nOverride it for a curriculum: return any list of task directories, such as some of `self.lender.train`, and keep what the choice reads (counts, scores) in your `State`. A task's instruction is readable before any rollout, at `task \u002F \"instruction.md\"`.\n\n### rollout\n\n`await self.rollout(tasks, model=..., harness=..., attempts=..., modules=...)` runs `model` on each task `attempts` times through `harness`, in Harbor sandboxes, as one job, and returns a `Group` per task, in order. Each group holds `attempts` **trials**, each graded by the task's tests.\n\n- `modules=`: `self.state.modules` for the run's own prompt and skills, `None` for none, or any `Modules`.\n- `renderer=`: one of the model's `renderers`; a model with several must be given one.\n- `purpose=`: the job's label: `training` unless `evaluate` makes the rollout, or one you name.\n- A recipe that wants several harnesses or renderers runs several rollouts, at once with `asyncio.gather`, and puts their groups together as it means them.\n- Any model the run holds can be rolled out, a provider's model through its harness with the harness's own credentials. To ask a model for text, write a Harbor task (`instruction.md`, `task.toml`, `environment\u002F`, `tests\u002F`) whose tests copy what the model wrote into the trial's `verifier\u002F`, roll it out, and read it back from `trial.dir \u002F \"verifier\"`: gepa's `reflect.py`.\n\nRoll a batch out in one call, or one task a call from a loop of your own: shipyard keeps up to `[rollout] sandboxes` trials alive and `[rollout] concurrency` of them sampling, an evaluation's trials first, and raises once as many trials in a row as sample at once reached no model.\n\nEach model call takes the weights the model published last when the call starts, so a trial that outlives an `update` is answered by the weights before it and after. `seq.weights` names the weights that answered each of a sequence's spans, and `model.lag(group)` counts the times the model published since the oldest weights that answered the group's graded trials: 0 for a group of the weights it serves now. A loop that overlaps rollouts with updates reads it to drop or down-weight stale groups.\n\nA trial offers `reward`, `graded`, `sequences`, `sampled_tokens`, `instruction`, `transcript`, `steps` (Harbor's trajectory), `test_output`, `result` (Harbor's `result.json`, every key of the verifier's rewards under `verifier_result.rewards`) and `dir`. Its `transcript` includes the prompt and skills it carried, and `test_output` can print the tests' expected answers: filter both before a model reads them.\n\n### score\n\nScoring sets the **advantages**: a number per target token of each sequence, which `update` trains on. A trial's **sequences** are the chains of model calls it made, as the token ids the model read and sampled; `seq.targets` are the positions it sampled. A sequence trains only once it has advantages.\n\n- Per trial: `trial.set_advantage(x)` gives every target token of every sequence `x`. It rewrites them all, so call it before adding advantages of your own.\n- Per token: `seq.advantages = tensor`, one value per target.\n- From a model: `await model.logprobs(seqs)` returns each sequence's logprob at every target, as a tensor, for any model on Tinker or Together the run holds; it reads the agent's token ids, so it shares the agent's tokenizer.\n- From a group: `group.graded`, `group.rewards`, `group.reward_variance`, `group.centered_rewards`.\n- `self.metrics[\"name\"] = value` adds a number to this step's row.\n\n### update\n\n`await self.update(model, groups, loss=..., loss_config=...)` trains `model` on every sequence with advantages, then serves its new weights, which every call that starts from then on takes, an evaluation's excepted. It returns what it trained, or None when nothing was scored. Pass it every group the step took, the ones it drops included: the step's row counts what it was passed, scored or not.\n\n- `loss`: `importance_sampling` (the default); `ppo` and `cispo`, which take `clip_low_threshold` and `clip_high_threshold`, bounds on the ratio itself such as 0.8 and 1.2; `dro`, which takes `beta`; `cross_entropy`, which weighs each target by its advantage: supervised fine-tuning, with advantage 1 on what to imitate.\n- `[recipe] substeps`: optimizer steps per update, each on a share of the groups, whole groups each; the model's `learning_rate` and `warmup`; `ADAM = tinker.AdamParams(...)` as a class attribute.\n\nUpdate each model in training once a step: each call takes its optimizer steps, serves new weights and advances the warmup. The loss sums over tokens, so a long sequence weighs more than a short one; to weigh every group the same, scale its advantages, as dapo's `step` does. The ratio is taken against the sampler's logprobs, which the proxy recorded as the model sampled.\n\n### spawn\n\n`self.spawn(coroutine)` runs a coroutine as a task the run owns, beside the steps, and returns it: a worker that keeps rolling tasks out while the steps update, as an asynchronous loop needs, or any work a step awaits later. Spawn from `step`, once the run has started. `dapo-async` is the loop to copy: its first step spawns the workers, which hand their groups to the steps through a queue.\n\n- If it raises, the run fails at once with its error, even while a step waits on what it would have handed over.\n- When the run ends, it cancels the ones still running before the final checkpoint: their trials close, and the tasks they drew stay out, for a resume to give out first. A group a worker finished that no step passed to `update` is lost; its task comes back in a later pass.\n\n## Additional information\n\n### Graded and masked trials\n\nA trial is **masked** when its outcome says nothing about the agent: the sandbox, the grader or the model's server failed, or Harbor cut it at its timeout (`[recipe] grade_timeouts = true` grades those instead). A masked trial has no reward and no sequences, and `group.graded`, `group.rewards` and the row's `graded` leave it out. A group can hold fewer graded trials than its attempts, or none, so compute group statistics, and counts per task, over its graded trials. The row's `trials`, `graded` and `masked` show how many each step lost.\n\n### Recipe state and resuming\n\nWhat a recipe learns across steps (a bank, a curriculum's counts, a search's best) lives in its `State` fields. Every checkpoint saves `self.state`, and `shipyard resume runs\u002F\u003Crun>` starts a new run from the last checkpoint, `--tag step-\u003Cn>` from another. A field needs a default and a JSON value. A plain attribute starts empty again on a resume.\n\n### Models\n\nEvery model comes from the config by role, as `self.models[role]`, and does nothing until the run starts and binds it; using one before raises \"not connected yet\". Its role names its lane in the proxy and its rows in `usage.jsonl`.\n\n| Model | Runs on | `logprobs` | Trains |\n| --- | --- | --- | --- |\n| on Tinker or Together | a session on its training service, served through its lane of the run's proxy | yes | while `training` |\n| behind a provider's API, such as `provider = \"anthropic\"` | the provider's API, with its harness's own credentials | no | no |\n\n- `trainable` says whether a run could train it: a base model or a training state on Tinker or Together. Weights saved for sampling (`...\u002Fsampler_weights\u002F...`) are served and scored as they are.\n- `budget` is the most tokens one trial may sample, once the model is served.\n\n### Modules\n\n`modules` names a folder of `PROMPT.md` and `skills\u002F\u003Cname>\u002FSKILL.md`, which every trial carries into its harness. `Modules.read(folder)` reads one; `modules.texts` and `modules.with_texts({...})` read and replace their texts, raising `Inadmissible` for text a harness cannot be given; `self.keep(modules, \"best\")` writes them into the run; setting `self.state.modules` changes what the next rollouts carry.\n\n### Task hooks\n\nA task can carry a `hooks.py` beside its `task.toml`: code the run executes on this machine, outside the sandboxes, at events of each of the task's trials, such as setting up an outside system before the agent starts and tearing it down once the trial is done. Every recipe runs a task's hooks; the config names none.\n\n- A hook is `async def \u003Cevent>(event: TrialHookEvent)`, named after one of Harbor's trial events: `start`, `environment_start`, `agent_start`, `agent_end`, `verification_start`, `end` or `cancel`. Helpers start with `_`. Any other public function, or a hook that is not `async`, stops the run before anything opens.\n- `event.config` is the trial's own Harbor config: its leased secrets are in `event.config.environment.env`, its folder is `Path(event.config.trials_dir) \u002F event.config.trial_name`, and a value set in `event.config.verifier.env` reaches that trial's verifier alone, never its agent.\n- Harbor's rules apply. A hook that raises at `start` skips `end`; one that raises at `environment_start` masks its trial, and `end` still runs, so set-up belongs there; one that raises at `end` leaves the grade as it was. A hook has no time limit of its own, so bound what it waits on.\n- The run logs each hook it runs and how it ended.\n\n### The step's row\n\n`metrics.jsonl` holds a row per step, counting the groups the step passed to `update`, wherever they were rolled out: `trained`, `jobs` (the jobs they came from), `groups`, `trials`, `graded`, `masked`, `uniform` (groups with graded trials and nothing to train), `sequences`, `reward_mean`, `reward_spread`, `sampled_mean`, and the update's `train_tokens`, `kl_v1`, `kl_v2`, `entropy`, `learning_rate`, `substeps`, `loss` and `update_seconds`; a step that trained several models prefixes each one's update fields with its role. After an evaluation it holds `eval_` fields, and then `self.metrics`, which starts empty each step; a key that matches one of these is written as `recipe_\u003Ckey>`.\n\n`jobs.jsonl` holds a row per rollout, under the step it ran in, with `weights`: the weights that answered its calls, in the order the model published them. An evaluation's name the weights it measured.\n\n### Checking a recipe\n\n1. `shipyard run recipes\u002Fmine` refuses a wrong config, trainer or model before anything opens, listing every problem. Fix each until the run starts.\n2. Run one small step on this machine: `shipyard run recipes\u002Fmine --recipe.steps 1 --data.batch_size 2 --recipe.group_size 4 --rollout.sandbox docker`.\n\nThe recipe is checked when that run's `metrics.jsonl` holds one row with `graded` above 0 and `trained: true`. A row with `trained: false` and `uniform` equal to `groups` had nothing to learn, every group's rewards being equal: raise `group_size` or pick harder tasks, and run it again.\n",{},"main","90f6b65640b73a6287952d674d19f7cae3122a11","skills\u002Fcustom-recipes",0,"https:\u002F\u002Fgithub.com\u002Fghidav\u002Fshipyard","https:\u002F\u002Fgithub.com\u002Fghidav","PhD student @ Milano Bicocca University","2026-11-02 18:15:27",{"source":7,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add ghidav\u002Fshipyard --skill custom-recipes",{"tool":37,"command":38},"bunx","bunx skills add ghidav\u002Fshipyard --skill custom-recipes",{"tool":40,"command":41},"pnpm","pnpm dlx skills add ghidav\u002Fshipyard --skill custom-recipes","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fghidav\u002Fshipyard\u002Fblob\u002Fmain\u002Fskills\u002Fcustom-recipes\u002FSKILL.md",true,[],[46,53],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M7EB1VFB5B5MA4P1J4QWPMJM","solving","How to approach a task before writing anything.","https:\u002F\u002Fgithub.com\u002Fghidav\u002Fshipyard\u002Fblob\u002Fmain\u002Ftests\u002Fmodules\u002Fvalid\u002Fskills\u002Fsolving\u002FSKILL.md",[],[],{"skillNo":54,"name":48,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":18},"01M7EB1RRA9NZXMDE6FK22P9W7","https:\u002F\u002Fgithub.com\u002Fghidav\u002Fshipyard\u002Fblob\u002Fmain\u002Ftests\u002Fmodules\u002Fbare\u002Fskills\u002Fsolving\u002FSKILL.md",[],[]]