Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions model/benchmark/src/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ def run(config: Settings) -> None:
records = [json.loads(line) for line in path.read_text().splitlines()]
if not records:
raise ValueError("Evaluation tasks must not be empty")
if len({record["id"] for record in records}) != len(records):
raise ValueError("Evaluation tasks must have unique IDs")
from model.benchmark.src.inference import HFCompletion

generate = HFCompletion(config)
Expand All @@ -29,7 +31,7 @@ def run(config: Settings) -> None:
for worker in workers:
task = trial(worker, next(remaining), config.calls)
active.append((worker, task, next(task)))
completed = 0
rows = []
while active:
completions = generate([prompt for _, _, prompt in active])
pending = []
Expand All @@ -40,14 +42,13 @@ def run(config: Settings) -> None:
row = result.value
file.write(json.dumps(row) + "\n")
file.flush()
completed += 1
print(f"{completed}/{len(records)}: {row['id']} {row['status']}", flush=True)
rows.append(row)
print(f"{len(rows)}/{len(records)}: {row['id']} {row['status']}", flush=True)
record = next(remaining, None)
if record is None:
continue
task = trial(worker, record, config.calls)
prompt = next(task)
pending.append((worker, task, prompt))
active = pending
rows = [json.loads(line) for line in config.output.read_text().splitlines()]
print(scoring.summary(scoring.score(rows)), flush=True)
print(scoring.summary(scoring.score(rows)), flush=True)
11 changes: 8 additions & 3 deletions model/benchmark/src/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import time
import uuid
import logging
import selectors
import contextlib
import subprocess # noqa: S404
Expand All @@ -22,7 +23,6 @@ def __init__(self) -> None:
[ # noqa: S607
"docker",
"run",
"--rm",
"-i",
"--name",
self.name,
Expand Down Expand Up @@ -117,13 +117,18 @@ def close(self) -> None:
if self.selector is not None:
self.selector.close()
finally:
subprocess.run( # noqa: S603
result = subprocess.run( # noqa: S603
["docker", "rm", "--force", self.name], # noqa: S607
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
check=False,
timeout=15,
)
if result.returncode:
logging.getLogger(__name__).error(
"Failed to remove container %s (exit %s): %s", self.name, result.returncode, result.stderr.strip()
)
finally:
try:
self.process.wait(timeout=15)
Expand Down
2 changes: 1 addition & 1 deletion model/benchmark/src/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, config: Settings) -> None:
self.tokenizer.padding_side = "left"
if self.tokenizer.pad_token_id is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
self.model = AutoModelForImageTextToText.from_pretrained(base, revision=revision, dtype=torch.float32, attn_implementation="sdpa")
self.model = AutoModelForImageTextToText.from_pretrained(base, revision=revision, dtype=torch.bfloat16, attn_implementation="sdpa")
self.model = PeftModel.from_pretrained(self.model, config.adapter)
self.model.to(config.device).eval()
self.max_new_tokens = config.tokens
Expand Down
26 changes: 26 additions & 0 deletions model/benchmark/tests/test_evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,32 @@ def test_empty_tasks_are_rejected_before_loading_model(benchmark):
assert not config.output.exists()


def test_duplicate_tasks_are_rejected_before_loading_model(benchmark):
config, model, worker, rows = benchmark
path = config.output.parent / "dev-tasks.jsonl"
path.write_text("".join(json.dumps(rows[0]) + "\n" for _ in range(2)))
with pytest.raises(ValueError, match="unique IDs"):
evaluate.run(config)
model.assert_not_called()
worker.assert_not_called()
assert not config.output.exists()


def test_cleanup_failure_preserves_results_and_prints_summary_first(benchmark, capsys):
config, _, worker, rows = benchmark

def close():
output = capsys.readouterr().out
assert "Task success: 33.33% (1/3 tasks)" in output
assert "Valid Python: 100.00% (3/3 responses)" in output
raise TimeoutError("cleanup failed")

worker.return_value.close.side_effect = close
with pytest.raises(TimeoutError, match="cleanup failed"):
evaluate.run(config)
assert [json.loads(line) for line in config.output.read_text().splitlines()] == rows


def test_failure_preserves_completed_rows_and_closes_worker(benchmark, monkeypatch):
config, model, worker, rows = benchmark
model.return_value.side_effect = [[("code", True)], RuntimeError("generation failed")]
Expand Down
28 changes: 27 additions & 1 deletion model/benchmark/tests/test_execution.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sys
import pytest
import subprocess
from contextlib import closing
from unittest.mock import patch
from model.benchmark.src import execution

Expand All @@ -26,7 +27,7 @@ def test_worker_launches_directly_with_the_same_container_isolation():
):
assert command[command.index(flag) + 1] == value
assert "--read-only" in command
assert "--rm" in command
assert "--rm" not in command
volumes = [command[index + 1] for index, value in enumerate(command) if value == "--volume"]
assert volumes == [f"{execution.ROOT / 'src/worker.py'}:/model/benchmark/src/worker.py:ro"]
assert command[command.index("--entrypoint") + 2] == "pyshell-pyshell:latest"
Expand All @@ -37,6 +38,31 @@ def test_worker_launches_directly_with_the_same_container_isolation():
main.assert_called_once_with()


@pytest.mark.parametrize("execution_failure", [False, True])
def test_removal_failure_is_reported_without_masking_execution_error(caplog, execution_failure):
with (
patch.object(execution.subprocess, "Popen") as launch,
patch.object(execution.selectors, "DefaultSelector"),
patch.object(execution.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, stderr="daemon unavailable")),
patch.object(execution.os, "set_blocking"),
):
worker = execution.Worker()
error = RuntimeError("execution failed")
if execution_failure:
with pytest.raises(RuntimeError) as raised, closing(worker):
raise error
assert raised.value is error
else:
worker.close()

assert worker.name in caplog.text
assert "exit 1" in caplog.text
assert "daemon unavailable" in caplog.text
launch.return_value.wait.assert_called_once_with(timeout=15)
for stream in (launch.return_value.stdin, launch.return_value.stdout, launch.return_value.stderr):
stream.close.assert_called_once_with()


@pytest.mark.parametrize(
("phase", "cleanup_failure"),
[("stdin", None), ("create", None), ("stdout", None), ("stderr", None), ("stderr", "selector"), ("stderr", "docker")],
Expand Down
2 changes: 1 addition & 1 deletion model/benchmark/tests/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def test_adapter_loads_its_recorded_base_model(self, revision):
self.completion(revision=revision)
self.threads.assert_called_once_with(3)
self.load_tokenizer.assert_called_once_with("fixture-base", revision=revision)
self.load_model.assert_called_once_with("fixture-base", revision=revision, dtype=torch.float32, attn_implementation="sdpa")
self.load_model.assert_called_once_with("fixture-base", revision=revision, dtype=torch.bfloat16, attn_implementation="sdpa")
self.load_adapter.assert_called_once_with(self.model, self.adapter)

def test_configured_generation_budget_is_used(self):
Expand Down
6 changes: 3 additions & 3 deletions model/train/src/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ class Settings(BaseModel):
)

# Model and dataset
base: str = Field(default="Qwen/Qwen3.5-0.8B", min_length=1)
base: str = Field(default="Qwen/Qwen3.5-9B", min_length=1)
data: str = Field(default=str(ROOT / "data"), min_length=1)
base_revision: str | None = Field(
default="2fc06364715b967f1860aea9cf38778875588b17", pattern=r"^[0-9a-f]{40}$"
default="c202236235762e1c871ad0ccb60c8ee5ba337b9a", pattern=r"^[0-9a-f]{40}$"
)

# Run
cpu: bool = True
seed: int = Field(default=713, ge=0)
steps: int = Field(default=125, gt=0)
epochs: int = Field(default=1, gt=0)
output: Path = ROOT / "artifacts/candidate"

# Training
Expand Down
15 changes: 12 additions & 3 deletions model/train/src/training.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
from pathlib import Path

import datasets
Expand Down Expand Up @@ -41,12 +42,11 @@ def train(config: settings.Settings):
seed=config.seed,
bf16=config.dtype == "bfloat16",
use_cpu=config.cpu,
max_steps=config.steps,
num_train_epochs=config.epochs,
data_seed=config.seed,
max_length=config.max_length,
save_strategy="no",
eval_steps=config.steps,
eval_strategy="steps" if "validation" in dataset else "no",
eval_strategy="epoch" if "validation" in dataset else "no",
eval_on_start="validation" in dataset,
logging_steps=1,
learning_rate=config.learning_rate,
Expand All @@ -71,6 +71,15 @@ def train(config: settings.Settings):
eval_dataset=dataset.get("validation"),
peft_config=lora,
)
batch_size = trainer.args.train_batch_size * trainer.args.world_size
effective_batch_size = batch_size * config.gradient_accumulation_steps
batches = math.ceil(len(dataset["train"]) / batch_size)
steps = math.ceil(batches / config.gradient_accumulation_steps) * config.epochs
print(
f"Training: {len(dataset['train'])} rows, {config.epochs} epoch(s), "
f"effective batch size {effective_batch_size}, {steps} optimizer steps",
flush=True,
)
trainer.train()
trainer.save_model()
trainer.save_state()
2 changes: 1 addition & 1 deletion model/train/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def run(name, **changes):
"data": str(data),
"base_revision": None,
"output": tmp_path / name,
"steps": 4,
"epochs": 1,
"max_length": 1024,
"gradient_accumulation_steps": 2,
"learning_rate": 0.001,
Expand Down
2 changes: 1 addition & 1 deletion model/train/tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
@pytest.mark.parametrize(
"field",
[
"steps",
"epochs",
"rank",
"alpha",
"max_length",
Expand Down
36 changes: 34 additions & 2 deletions model/train/tests/test_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,46 @@ def test_missing_local_training_data_is_rejected(training_run, tmp_path):
training_run("missing", data=str(tmp_path / "missing"))


@pytest.mark.parametrize(
("batch_size", "accumulation", "steps"), [(1, 2, 2), (3, 1, 2), (3, 3, 1)]
)
def test_one_epoch_uses_every_row_including_partial_batches(
training_run, tmp_path, monkeypatch, capsys, batch_size, accumulation, steps
):
seen = []
training_step = training.SFTTrainer.training_step

def observe(trainer, model, inputs, *args, **kwargs):
for tokens, mask in zip(
inputs["input_ids"], inputs["attention_mask"], strict=True
):
seen.append(tuple(tokens[mask.bool()].tolist()))
return training_step(trainer, model, inputs, *args, **kwargs)

monkeypatch.setattr(training.SFTTrainer, "training_step", observe)
output = training_run(
"full-epoch", batch_size=batch_size, gradient_accumulation_steps=accumulation
)
state = json.loads((output / "trainer_state.json").read_text())
assert len(seen) == len(set(seen)) == 4
assert state["global_step"] == steps
assert state["epoch"] == 1
assert sum("eval_loss" in row for row in state["log_history"]) == 2
assert (
f"Training: 4 rows, 1 epoch(s), effective batch size {batch_size * accumulation}, {steps} optimizer steps"
in capsys.readouterr().out
)


def test_training_ignores_foreign_files_and_saves_a_reloadable_adapter(
training_run, tmp_path
):
(tmp_path / "data/test-tasks.jsonl").write_text("not a training dataset")
(tmp_path / "data/train-tasks.jsonl").write_text("not a training dataset")
output = training_run("candidate", steps=3, learning_rate=0.002, rank=4, alpha=8)
output = training_run("candidate", epochs=2, learning_rate=0.002, rank=4, alpha=8)
state = json.loads((output / "trainer_state.json").read_text())
assert state["global_step"] == 3
assert state["global_step"] == 4
assert state["epoch"] == 2
adapter = json.loads((output / "adapter_config.json").read_text())
assert adapter["r"] == 4
assert adapter["lora_alpha"] == 8
Expand Down
4 changes: 2 additions & 2 deletions model/train/tests/test_training_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ def test_default_run_logs_losses_and_saves_only_the_final_adapter(training_run):
output = training_run("default")
state = json.loads((output / "trainer_state.json").read_text())
losses = [row for row in state["log_history"] if "loss" in row]
assert [row["step"] for row in losses] == [1, 2, 3, 4]
assert [row["step"] for row in losses] == [1, 2]
assert all(math.isfinite(row["loss"]) and row["loss"] >= 0 for row in losses)
assert [row["step"] for row in state["log_history"] if "eval_loss" in row] == [0, 4]
assert [row["step"] for row in state["log_history"] if "eval_loss" in row] == [0, 2]
assert not list(output.glob("checkpoint-*"))
assert (output / "adapter_model.safetensors").is_file()
assert (output / "adapter_config.json").is_file()
Expand Down