From eb4f34a5730863acd9f8e4fed0975084b949f6fd Mon Sep 17 00:00:00 2001 From: Sau1707 <83017316+Sau1707@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:44:28 +0100 Subject: [PATCH] feat: Adopt Qwen3.5-9B with full-dataset training --- model/benchmark/src/evaluate.py | 11 ++++---- model/benchmark/src/execution.py | 11 +++++--- model/benchmark/src/inference.py | 2 +- model/benchmark/tests/test_evaluate.py | 26 ++++++++++++++++++ model/benchmark/tests/test_execution.py | 28 ++++++++++++++++++- model/benchmark/tests/test_inference.py | 2 +- model/train/src/settings.py | 6 ++--- model/train/src/training.py | 15 ++++++++--- model/train/tests/conftest.py | 2 +- model/train/tests/test_settings.py | 2 +- model/train/tests/test_training.py | 36 +++++++++++++++++++++++-- model/train/tests/test_training_log.py | 4 +-- 12 files changed, 122 insertions(+), 23 deletions(-) diff --git a/model/benchmark/src/evaluate.py b/model/benchmark/src/evaluate.py index e8442ea..1aaa8de 100644 --- a/model/benchmark/src/evaluate.py +++ b/model/benchmark/src/evaluate.py @@ -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) @@ -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 = [] @@ -40,8 +42,8 @@ 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 @@ -49,5 +51,4 @@ def run(config: Settings) -> None: 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) diff --git a/model/benchmark/src/execution.py b/model/benchmark/src/execution.py index 88108a7..81f1c4b 100644 --- a/model/benchmark/src/execution.py +++ b/model/benchmark/src/execution.py @@ -2,6 +2,7 @@ import json import time import uuid +import logging import selectors import contextlib import subprocess # noqa: S404 @@ -22,7 +23,6 @@ def __init__(self) -> None: [ # noqa: S607 "docker", "run", - "--rm", "-i", "--name", self.name, @@ -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) diff --git a/model/benchmark/src/inference.py b/model/benchmark/src/inference.py index 3f6fb6c..b9f5881 100644 --- a/model/benchmark/src/inference.py +++ b/model/benchmark/src/inference.py @@ -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 diff --git a/model/benchmark/tests/test_evaluate.py b/model/benchmark/tests/test_evaluate.py index 253dc27..6a28fdb 100644 --- a/model/benchmark/tests/test_evaluate.py +++ b/model/benchmark/tests/test_evaluate.py @@ -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")] diff --git a/model/benchmark/tests/test_execution.py b/model/benchmark/tests/test_execution.py index 93d99aa..370b278 100644 --- a/model/benchmark/tests/test_execution.py +++ b/model/benchmark/tests/test_execution.py @@ -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 @@ -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" @@ -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")], diff --git a/model/benchmark/tests/test_inference.py b/model/benchmark/tests/test_inference.py index 7baf5fa..3508ff3 100644 --- a/model/benchmark/tests/test_inference.py +++ b/model/benchmark/tests/test_inference.py @@ -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): diff --git a/model/train/src/settings.py b/model/train/src/settings.py index d5bb17c..14c27ef 100644 --- a/model/train/src/settings.py +++ b/model/train/src/settings.py @@ -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 diff --git a/model/train/src/training.py b/model/train/src/training.py index ddd28a8..44e4be0 100644 --- a/model/train/src/training.py +++ b/model/train/src/training.py @@ -1,3 +1,4 @@ +import math from pathlib import Path import datasets @@ -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, @@ -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() diff --git a/model/train/tests/conftest.py b/model/train/tests/conftest.py index c78a49c..40a2e35 100644 --- a/model/train/tests/conftest.py +++ b/model/train/tests/conftest.py @@ -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, diff --git a/model/train/tests/test_settings.py b/model/train/tests/test_settings.py index 62c79d4..9211d2b 100644 --- a/model/train/tests/test_settings.py +++ b/model/train/tests/test_settings.py @@ -9,7 +9,7 @@ @pytest.mark.parametrize( "field", [ - "steps", + "epochs", "rank", "alpha", "max_length", diff --git a/model/train/tests/test_training.py b/model/train/tests/test_training.py index 322ed14..9e5c52f 100644 --- a/model/train/tests/test_training.py +++ b/model/train/tests/test_training.py @@ -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 diff --git a/model/train/tests/test_training_log.py b/model/train/tests/test_training_log.py index b6f517b..e16302f 100644 --- a/model/train/tests/test_training_log.py +++ b/model/train/tests/test_training_log.py @@ -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()