Datasets:
Download artifacts/runtime-source/modal_training.py from suunny/terminal-agent-rl: direct link, hf CLI and curl.
- Browser
- Download file 153 kB
-
https://huggingface.co/datasets/suunny/terminal-agent-rl/resolve/main/artifacts/runtime-source/modal_training.py
- Command line
-
hf download hf://datasets/suunny/terminal-agent-rl/artifacts/runtime-source/modal_training.py
-
curl -L -o modal_training.py https://huggingface.co/datasets/suunny/terminal-agent-rl/resolve/main/artifacts/runtime-source/modal_training.py
153 kB
| """Modal launcher for the official Prime RL training and inference processes.""" | |
| import modal | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent | |
| ACTIVE_PROFILE = 'rl-next' | |
| ACTIVE_WORKSPACE = 'susindra-turtlelabs' | |
| if modal.is_local(): | |
| from task_source import contract_digest | |
| CONTRACT = contract_digest() | |
| else: | |
| import os | |
| CONTRACT = os.environ["WORKSPACE_CONTRACT_SHA256"] | |
| task_cache = modal.Volume.from_name("workspace-agent-task-cache", create_if_missing=True) | |
| RELEASE_IMAGE = "ghcr.io/primeintellect-ai/prime-rl@sha256:bd810178d034ea134663be6d21b6269af02e88b4a54517d481a1874b139af52f" | |
| app = modal.App("workspace-prime-training-smoke") | |
| outputs = modal.Volume.from_name("workspace-agent-training") | |
| cache = modal.Volume.from_name("workspace-agent-hf-cache") | |
| image = (modal.Image.from_registry(RELEASE_IMAGE).entrypoint([]) | |
| .dockerfile_commands("USER root") | |
| .apt_install("git", "openssh-client") | |
| .run_commands("uv pip install --exclude-newer-package modal=2026-10-30 --exclude-newer-package synchronicity=2026-10-30 --python /app/.venv/bin/python 'verifiers[harbor,modal]==0.4.1.dev12' 'renderers[multimodal]==0.1.13.dev5' 'harbor==0.24.0' 'modal==1.6.3'") | |
| .env({"WORKSPACE_CONTRACT_SHA256": CONTRACT}) | |
| .add_local_file(ROOT / "task_source.py", "/workspace-smoke/task_source.py", copy=True) | |
| .add_local_file(ROOT / "task-source.json", "/workspace-smoke/task-source.json", copy=True) | |
| .add_local_file(ROOT / "bash_timeout.py", "/workspace-smoke/bash_timeout.py", copy=True) | |
| .run_commands("/app/.venv/bin/python /workspace-smoke/bash_timeout.py") | |
| .add_local_file(ROOT / "compaction_task.py", "/workspace-smoke/compaction_task.py", copy=True) | |
| .run_commands("/app/.venv/bin/python /workspace-smoke/compaction_task.py") | |
| .add_local_file(ROOT / "bash_recovery.py", "/workspace-smoke/bash_recovery.py", copy=True) | |
| .run_commands("/app/.venv/bin/python /workspace-smoke/bash_recovery.py") | |
| .add_local_file(ROOT / "train.toml", "/workspace-training/train.toml", copy=True) | |
| .add_local_file(ROOT / "training_lifecycle.py", "/workspace-smoke/training_lifecycle.py", copy=True) | |
| .add_local_file(ROOT / "final_training.py", "/workspace-smoke/final_training.py", copy=True) | |
| ) | |
| # Reuse the evaluation runtime; Harbor fetches tasks from the private Git repo. | |
| evaluation_image = (image | |
| .add_local_file(ROOT / "calibration/config.json", "/workspace-calibration/config.json", copy=True) | |
| .add_local_file(ROOT / "calibration/candidates.json", "/workspace-calibration/candidates.json", copy=True) | |
| .add_local_file(ROOT / "calibration/screening-selected100.json", "/workspace-calibration/screening-selected100.json", copy=True) | |
| .add_local_file(ROOT / "calibration/screening-all116-manifest.json", "/workspace-calibration/screening-all116-manifest.json", copy=True) | |
| .add_local_file(ROOT / "calibration/screening-round2-selected100.json", "/workspace-calibration/screening-round2-selected100.json", copy=True) | |
| .add_local_file(ROOT / "calibration/screening-round2-manifest.json", "/workspace-calibration/screening-round2-manifest.json", copy=True)) | |
| def calibration_config(): | |
| import hashlib | |
| import json | |
| base = ROOT / "calibration" if modal.is_local() else Path("/workspace-calibration") | |
| config = json.loads((base / "config.json").read_text()) | |
| config['experiment'].update(profile=ACTIVE_PROFILE, workspace=ACTIVE_WORKSPACE) | |
| taskset = config['evaluation']['source'][0]['env']['taskset'] | |
| assert taskset['repo'].endswith('@'+config['experiment']['task_git_commit']) | |
| runtime = ROOT if modal.is_local() else Path("/workspace-smoke") | |
| for name, expected in config["runtime_sha256"].items(): | |
| assert hashlib.sha256((runtime / name).read_bytes()).hexdigest() == expected, name | |
| experiment = config['experiment'] | |
| assert experiment['replicas'] == 2 and experiment['task_count'] == 16 | |
| assert experiment['episode_concurrency_per_replica'] == 32 | |
| assert experiment['total_episode_concurrency'] == 64 | |
| assert config['inference']['vllm']['max_num_seqs'] == 32 | |
| assert all(config['evaluation']['concurrency'][key] == 32 | |
| for key in ('initial_inflight', 'min_inflight', 'max_inflight')) | |
| assert config['evaluation']['source'][0]['serve']['max_concurrent'] == 32 | |
| assert config['evaluation']['group_size'] * experiment['replicas'] == 8 | |
| assert config['evaluation']['select']['limit'] == 16 | |
| assert len(set(config['evaluation']['source'][0]['env']['taskset']['tasks'])) == 16 | |
| from prime_rl.configs.inference import InferenceConfig | |
| from prime_rl.configs.eval import EvalConfig | |
| from copy import deepcopy | |
| parsed = InferenceConfig.model_validate(deepcopy(config['inference'])) | |
| assert parsed.router is None, 'One engine per replica uses native direct-engine mode' | |
| assert parsed.to_namespace().served_model_name == [config['evaluation']['model']] | |
| EvalConfig.model_validate(deepcopy(config['evaluation'])) | |
| return config | |
| ROLLOUT_COMPARISON_TASKS = ( | |
| 'ds2-task_12106_bd7f8d', 'task_00002_aa2b6f', 'task_00137_41c355', | |
| 'task_00158_a21b36', 'task_01019_af7e37', 'task_00991_47ea8b', | |
| ) | |
| def comparison_taskset(): | |
| from copy import deepcopy | |
| taskset = deepcopy(calibration_config()['evaluation']['source'][0]['env']['taskset']) | |
| taskset['tasks'] = list(ROLLOUT_COMPARISON_TASKS) | |
| return taskset | |
| def load_comparison_tasks(): | |
| import json | |
| import sys | |
| sys.path.insert(0, '/workspace-smoke') | |
| from task_source import git_credentials, task_manifest | |
| from verifiers.v1.tasksets.harbor import HarborConfig, HarborTaskset | |
| with git_credentials(): | |
| tasks = list(HarborTaskset(HarborConfig.model_validate(comparison_taskset())).load()) | |
| base = ROOT/'calibration' if modal.is_local() else Path('/workspace-calibration') | |
| expected = json.loads((base/'candidates.json').read_text())['task_manifest'] | |
| assert task_manifest(tasks) == {name:expected[name] for name in ROLLOUT_COMPARISON_TASKS} | |
| assert all(t.data.upload_environment for t in tasks) | |
| return tasks | |
| def load_evaluation_tasks(sources, expected_manifest): | |
| """One native Git/Harbor loading gate for CPU preflight and GPU startup.""" | |
| from copy import deepcopy | |
| from task_source import git_credentials, task_manifest | |
| from verifiers.v1.tasksets.harbor import HarborConfig, HarborTaskset | |
| with git_credentials(): | |
| tasks = [task for source in sources for task in | |
| HarborTaskset(HarborConfig.model_validate(deepcopy(source['env']['taskset']))).load()] | |
| names = [name for source in sources for name in source['env']['taskset']['tasks']] | |
| assert {task.data.name for task in tasks} == set(names), 'Loaded task selection differs' | |
| assert all(task.data.upload_environment for task in tasks), 'Prebuilt task setup must be uploaded by Harbor' | |
| assert task_manifest(tasks) == expected_manifest, 'Remote Git task bytes differ from pinned manifest' | |
| return tasks | |
| def configuration(directory, tunnel_url, eval_tunnel_url, max_steps=2, rollout_concurrency=16, | |
| comparison=False, validate_tasks=True): | |
| from copy import deepcopy | |
| import json | |
| import sys | |
| import tomllib | |
| from pathlib import Path | |
| sys.path.insert(0, "/workspace-smoke") | |
| from task_source import load_tasks, source_config | |
| from verifiers.v1.tasksets.harbor.taskset import HarborConfig | |
| from prime_rl.configs.rl import RLConfig | |
| config = tomllib.loads((ROOT/'train.toml' if modal.is_local() else | |
| Path('/workspace-training/train.toml')).read_text()) | |
| assert max_steps in (1, 2), "Only one or two bounded optimizer updates are allowed" | |
| assert rollout_concurrency in ((64, 128) if comparison else (16, 32)) | |
| config.update(output_dir=str(directory), run={"name": "training"}, dashboard=False, max_steps=max_steps) | |
| config["orchestrator"]["concurrency"].update( | |
| initial_inflight=rollout_concurrency, min_inflight=rollout_concurrency, | |
| max_inflight=rollout_concurrency) | |
| source = config["orchestrator"]["train"]["source"][0] | |
| source["env"]["taskset"] = (comparison_taskset() if comparison else | |
| source_config().model_dump(mode="json", exclude_none=True)) | |
| if validate_tasks: | |
| loaded = [task.data.name for task in (load_comparison_tasks() if comparison else load_tasks())] | |
| else: | |
| assert comparison | |
| loaded = list(ROLLOUT_COMPARISON_TASKS) | |
| assert len(loaded) == (6 if comparison else 4) | |
| # Keep worker/server capacity unchanged; the native dispatcher caps rollouts. | |
| source["serve"] = {"pool": {"type": "static", "num_workers": 1}, | |
| "max_concurrent": rollout_concurrency if comparison else 32} | |
| source["env"]["interception"] = {"type": "server", "tunnel": { | |
| "type": "custom", "url": tunnel_url, "port": 8001}} | |
| evaluation = deepcopy(source) | |
| evaluation["name"] = "workspace-final" | |
| evaluation["env"]["interception"]["tunnel"].update(url=eval_tunnel_url, port=8002) | |
| config["orchestrator"]["eval"]["source"] = [evaluation] | |
| if comparison: | |
| config['inference'].update(router=None) | |
| config['inference']['vllm'].update(max_num_seqs=rollout_concurrency, | |
| max_num_batched_tokens=8192) | |
| config['orchestrator']['eval']['select']['limit'] = 6 | |
| parsed = RLConfig.model_validate(deepcopy(config)) | |
| assert parsed.trainer.model.compile is not None | |
| assert parsed.trainer.model.compile.model_dump() == {"fullgraph": False, "mode": None} | |
| assert parsed.max_steps == max_steps and parsed.orchestrator.batch_size == 16 | |
| assert parsed.orchestrator.concurrency.max_inflight == rollout_concurrency | |
| assert parsed.trainer.model.lora.alpha == 32 and parsed.trainer.model.lora.rank == 16 | |
| assert parsed.weight_broadcast.type == "filesystem" | |
| assert parsed.orchestrator.train.sampling.max_completion_tokens == 8192 | |
| assert "thinking_token_budget" not in parsed.orchestrator.train.source[0].sampling.extra_body | |
| assert source["env"]["agent"]["max_turns"] == 50 | |
| return config, loaded | |
| async def train(run_id: str, max_steps: int = 2, rollout_concurrency: int = 16, | |
| comparison: bool = False, tiny: dict | None = None, final: dict | None = None): | |
| import asyncio | |
| import json | |
| import os | |
| import signal | |
| import sys | |
| import contextlib | |
| from pathlib import Path | |
| from huggingface_hub import snapshot_download | |
| sys.path.insert(0, "/workspace-smoke") | |
| from training_lifecycle import stop_launcher | |
| root = Path("/outputs/prime") | |
| if final is not None: | |
| from final_training import validate | |
| validate(final) | |
| assert max_steps == 10 and rollout_concurrency == 128 and tiny is None and not comparison | |
| else: | |
| assert max_steps in (1, 2), "Only one or two bounded optimizer updates are allowed" | |
| assert rollout_concurrency in ((8,) if tiny is not None else (64, 128) if comparison else (16, 32)) | |
| if tiny is not None: | |
| assert max_steps == 1 and not comparison | |
| validate_tiny_training(tiny) | |
| assert Path(run_id).name == run_id and run_id not in ("", ".", "..") | |
| directory = root / run_id | |
| directory.mkdir(parents=True, exist_ok=False) | |
| receipt = {"status": "starting", "contract_sha256": os.environ["WORKSPACE_CONTRACT_SHA256"], "inference_gpus": 1, "trainer_gpus": 1, | |
| "gpu": "H100:2", "max_steps": max_steps, "batch_size": 16, "group_size": 4, | |
| "concurrency": rollout_concurrency, "lora_rank": 16, "lora_alpha": 32, | |
| "revision": "c202236235762e1c871ad0ccb60c8ee5ba337b9a", "profile": "baseline", | |
| "comparison": comparison, "initialization": "same pinned base model; new LoRA and optimizer"} | |
| if tiny is not None: | |
| receipt.update(batch_size=8, group_size=8, profile='tiny-training', | |
| expected_updates=1, online_eval=False, recovery_per_episode=1) | |
| if final is not None: | |
| from final_training import digest | |
| import time | |
| receipt.update(batch_size=64, group_size=8, profile='final-training', inference_gpus=2, | |
| gpu='H100:3', expected_updates=10, online_eval=False, recovery_per_episode=1, | |
| frozen_sha256=digest(final), started_unix=time.time(), function_call_id=modal.current_function_call_id()) | |
| (directory/'frozen.json').write_text(json.dumps(final,indent=2)+'\n') | |
| watchdog = final['watchdog_seconds'] if final is not None else 1800 if tiny is not None else 6600 | |
| async def save(): | |
| (directory / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| async def persist(): | |
| while True: | |
| await asyncio.sleep(30) | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| process = None | |
| validation = None | |
| waiter = None | |
| persistence = asyncio.create_task(persist()) | |
| try: | |
| await save() | |
| # The trainer has no revision field: resolve one immutable snapshot for all | |
| # native components so training and serving cannot load different revisions. | |
| snapshot = await asyncio.to_thread(snapshot_download, "Qwen/Qwen3.5-9B", revision=receipt["revision"]) | |
| async with modal.forward(8001) as tunnel, modal.forward(8002) as eval_tunnel: | |
| if final is not None: | |
| from copy import deepcopy | |
| from final_training import verify_runtime | |
| receipt['runtime'] = verify_runtime(final) | |
| config = deepcopy(final['training']) | |
| selected = config['orchestrator']['train']['source'] | |
| tasks = load_evaluation_tasks(selected, {name:final['task_manifest'][name] for name in final['train_tasks']}) | |
| loaded = [task.data.name for task in tasks] | |
| assert len(selected) == 2 | |
| for source, selected_tunnel in zip(selected, (tunnel, eval_tunnel)): | |
| source['env']['interception']['tunnel']['url'] = selected_tunnel.url | |
| config['output_dir'] = str(directory) | |
| await task_cache.commit.aio() | |
| elif tiny is None: | |
| config, loaded = configuration(directory, tunnel.url, eval_tunnel.url, max_steps, | |
| rollout_concurrency, comparison=comparison) | |
| else: | |
| from copy import deepcopy | |
| from bash_recovery import verify_runtime | |
| config = deepcopy(tiny['training']) | |
| receipt['recovery_runtime'] = verify_runtime(tiny['recovery_sha256']) | |
| tasks = load_evaluation_tasks(config['orchestrator']['train']['source'], tiny['task_manifest']) | |
| loaded = [task.data.name for task in tasks] | |
| config['output_dir'] = str(directory) | |
| config['orchestrator']['train']['source'][0]['env']['interception']['tunnel']['url'] = tunnel.url | |
| await task_cache.commit.aio() | |
| config["model"]["name"] = snapshot | |
| config["inference"]["vllm"].pop("revision", None) | |
| path = directory / "launch.json" | |
| path.write_text(json.dumps(config, indent=2) + "\n") | |
| receipt.update(status="training_starting", loaded_tasks=loaded, model_snapshot=snapshot) | |
| await save() | |
| with (directory / "launcher.log").open("w") as log: | |
| # An OS watchdog still runs if Python or mounted-file I/O stalls. | |
| # Prime retains responsibility for its components and DCP writes. | |
| process = await asyncio.create_subprocess_exec( | |
| "/usr/bin/timeout", "--signal=TERM", "--kill-after=30s", f"{watchdog}s", | |
| "/app/.venv/bin/rl", "@", str(path), | |
| cwd="/app", env={**os.environ, "PATH": "/app/.venv/bin:" + os.environ["PATH"], | |
| "WANDB_MODE": "disabled", "VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT]}, | |
| stdout=log, stderr=log, start_new_session=True) | |
| receipt["launcher_pid"] = process.pid | |
| await save() | |
| waiter = asyncio.create_task(process.wait()) | |
| done, _ = await asyncio.wait((waiter, persistence), timeout=watchdog+70, | |
| return_when=asyncio.FIRST_COMPLETED) | |
| if persistence in done: | |
| await persistence | |
| if waiter not in done: | |
| raise TimeoutError("Official RL launcher exceeded its bounded walltime") | |
| receipt["exit_code"] = waiter.result() | |
| assert receipt["exit_code"] == 0, "Official RL process failed; inspect launcher/component logs" | |
| checkpoint_steps = (5, 10) if final is not None else (max_steps,) | |
| receipt.update(status="validating_checkpoint") | |
| await save() | |
| for step in checkpoint_steps: | |
| step_dir = directory / "training" / "checkpoints" / f"step_{step}" | |
| with (directory / (f"checkpoint-validation-{step}.log" if final is not None else "checkpoint-validation.log")).open("w") as log: | |
| validation = await asyncio.create_subprocess_exec( | |
| "/usr/bin/timeout", "--signal=TERM", "--kill-after=5s", "180s", | |
| "/app/.venv/bin/python", "/workspace-smoke/training_lifecycle.py", | |
| str(step_dir), str(step), str(step + 1 if step < max_steps else step), | |
| stdout=log, stderr=log, start_new_session=True) | |
| await asyncio.wait_for(validation.wait(), 195) | |
| assert validation.returncode == 0, f"Native checkpoint {step} validation failed" | |
| receipt.update(status="completed", checkpoints=[f"training/checkpoints/step_{step}" for step in checkpoint_steps], | |
| checkpoint_metadata_verified=True, checkpoint_progress_loaded=True, | |
| full_resume_tested=False) | |
| except BaseException as error: | |
| receipt.update(status="failed", error=repr(error)) | |
| raise | |
| finally: | |
| persistence.cancel() | |
| original_error = sys.exception() | |
| cleanup_errors = [] | |
| for child in (validation, process): | |
| if child is not None: | |
| try: | |
| await stop_launcher(child) | |
| except Exception as error: | |
| cleanup_errors.append(repr(error)) | |
| if waiter is not None: | |
| waiter.cancel() | |
| with contextlib.suppress(asyncio.CancelledError): | |
| await waiter | |
| try: | |
| await persistence | |
| except asyncio.CancelledError: | |
| pass | |
| except Exception as error: | |
| cleanup_errors.append(f"periodic persistence: {error!r}") | |
| receipt["launcher_stopped"] = process is None or process.returncode is not None | |
| if cleanup_errors: | |
| receipt.update(status="failed", cleanup_errors=cleanup_errors) | |
| # Always emit the final outcome to Modal logs, even when Volume commit fails. | |
| print(json.dumps(receipt, sort_keys=True), flush=True) | |
| try: | |
| await save() | |
| except Exception as error: | |
| print(f"Final receipt persistence failed: {error!r}", flush=True) | |
| if original_error is None: | |
| raise | |
| if cleanup_errors and original_error is None: | |
| raise RuntimeError("Training cleanup failed; inspect final receipt and Modal logs") | |
| if final is not None: | |
| import time | |
| receipt['ended_unix'] = time.time() | |
| # Only submit the short CPU handoff after native processes are stopped. | |
| # It waits for this FunctionCall to return, then lets this GPU container scale down. | |
| call = await final_evaluation_handoff.spawn.aio(run_id, final, modal.current_function_call_id()) | |
| receipt['evaluation_handoff_call_id'] = call.object_id | |
| await save() | |
| return receipt | |
| @app.function(image=evaluation_image, gpu="H100", cpu=8, memory=65536, timeout=21600, | |
| max_containers=4, retries=0, scaledown_window=2, | |
| secrets=[modal.Secret.from_name("workspace-official-harbor-controller"), | |
| modal.Secret.from_name("workspace-task-registry-readonly")], | |
| volumes={"/outputs": outputs, "/root/.cache/huggingface": cache, | |
| "/root/.cache/harbor": task_cache}) | |
| async def evaluate(run_id: str, adapter_run: str = "", calibration: bool = False, replica: int = 0, | |
| benchmark: str = "", startup_only: bool = False, screening64: bool = False, screening116: bool = False, screening100: bool = False, | |
| validation: dict | None = None, adapter_step: int = 2): | |
| """Official Prime inference + eval CLIs; no trainer or optimizer is started.""" | |
| import asyncio | |
| import contextlib | |
| import hashlib | |
| import json | |
| import os | |
| import signal | |
| import sys | |
| import time | |
| import tomllib | |
| from copy import deepcopy | |
| import httpx | |
| from prime_rl.configs.eval import EvalConfig | |
| from prime_rl.configs.inference import InferenceConfig | |
| sys.path.insert(0, "/workspace-smoke") | |
| from task_source import load_tasks, source_config | |
| final_heldout = validation is not None and validation['experiment'].get('purpose') == 'final_heldout' | |
| assert adapter_step == (10 if final_heldout else 2) | |
| multi_screen = screening116 or screening100 | |
| assert not (screening116 and screening100) | |
| assert Path(run_id).name == run_id and run_id not in ("", ".", "..") | |
| assert calibration or (Path(adapter_run).name == adapter_run and adapter_run not in ("", ".", "..")) | |
| assert benchmark in ("", "baseline", "candidate") | |
| assert not calibration or (replica in (range(4) if multi_screen else (0, 1)) and (not adapter_run or benchmark or final_heldout)) | |
| frozen = calibration_config() if calibration else None | |
| if screening64: | |
| assert calibration and replica == 0 and not adapter_run and not benchmark and not startup_only | |
| frozen = screening64_config() | |
| if multi_screen: | |
| assert calibration and not adapter_run and not benchmark and not startup_only and not screening64 | |
| frozen = screening116_config(replica, "screening-round2-selected100.json" if screening100 else "screening-selected100.json") | |
| if validation is not None: | |
| assert calibration and replica == 0 and not any((benchmark, startup_only, screening64, multi_screen)) | |
| assert not adapter_run or final_heldout | |
| frozen = deepcopy(validation) | |
| _validate_evaluation_budget(frozen) | |
| assert frozen['evaluation']['group_size'] == 8 and frozen['experiment']['replicas'] == 1 | |
| EvalConfig.model_validate(deepcopy(frozen['evaluation'])) | |
| if benchmark or final_heldout: | |
| await outputs.reload.aio() | |
| directory = Path('/outputs/prime') / run_id | |
| if calibration: | |
| directory = directory / f"replica-{replica}" | |
| directory.mkdir(parents=True, exist_ok=False) | |
| adapter = (Path('/outputs/prime') / adapter_run / f'training/broadcasts/step_{adapter_step}') if adapter_run else None | |
| receipt = {'status': 'starting', 'training_updates': 0, 'trainer_gpus': 0, | |
| 'inference_gpus': 1, 'adapter': str(adapter) if adapter else None, 'planned_attempts': 64 if calibration else 4, | |
| 'contract_sha256': os.environ['WORKSPACE_CONTRACT_SHA256']} | |
| if calibration: | |
| receipt.update(replica=replica, concurrency=32, attempts_per_task=4, | |
| calibration_config_sha256=hashlib.sha256(Path('/workspace-calibration/config.json').read_bytes()).hexdigest()) | |
| if screening64: | |
| receipt.update(concurrency=64, attempts_per_task=8, planned_attempts=128, | |
| experiment='single-H100 terminal screening, fresh cohort', | |
| task_git_commit=frozen['experiment']['task_git_commit']) | |
| if multi_screen: | |
| receipt.update(concurrency=64, attempts_per_task=8, planned_attempts=frozen["experiment"]["shard_task_count"] * 8, | |
| experiment='four-H100 fresh screening100 round2' if screening100 else 'four-H100 fresh screening116', | |
| task_git_commit=frozen['experiment']['task_git_commit']) | |
| (directory/'frozen-config.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| if validation is not None: | |
| receipt.update(concurrency=64, attempts_per_task=8, | |
| planned_attempts=frozen['experiment']['total_attempts'], | |
| experiment=frozen['experiment'].get('purpose', 'base model validation only'), | |
| output_token_limit=frozen['evaluation']['sampling']['max_tokens'], | |
| temperature=frozen['evaluation']['sampling']['temperature'], | |
| started_unix=time.time(), task_git_commits=frozen['experiment']['task_git_commits']) | |
| (directory/'frozen-config.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| server = job = None | |
| logs = [] | |
| started = time.monotonic() | |
| if benchmark: | |
| receipt.update(benchmark=benchmark, startup_only=startup_only, planned_attempts=0 if startup_only else 64, | |
| weight_updates_tested=False, training_acceptance_tested=False) | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt, indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| async def persist(): | |
| while True: | |
| await asyncio.sleep(30) | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| persistence = asyncio.create_task(persist()) | |
| try: | |
| if validation is not None and frozen['experiment'].get('purpose') in ('output_limit_comparison', 'temperature_probe', 'length_recovery_comparison', 'final_heldout'): | |
| from importlib.metadata import version | |
| receipt['versions'] = {name: version(name) for name in ('prime-rl','vllm','torch','verifiers','harbor','modal','renderers')} | |
| hardware = await asyncio.create_subprocess_exec('nvidia-smi', '--query-gpu=name,uuid', | |
| '--format=csv,noheader', stdout=asyncio.subprocess.PIPE) | |
| stdout, _ = await asyncio.wait_for(hardware.communicate(), 30) | |
| assert hardware.returncode == 0 | |
| receipt['gpu_hardware'] = stdout.decode().strip() | |
| if final_heldout: | |
| from final_training import verify_runtime | |
| receipt['runtime'] = verify_runtime(frozen) | |
| if frozen['experiment']['purpose'] == 'length_recovery_comparison': | |
| from bash_recovery import ENVIRONMENT_VARIABLE, verify_runtime | |
| receipt['recovery_runtime'] = verify_runtime(frozen['runtime_sha256']['bash_recovery.py']) | |
| receipt['length_recovery_per_episode'] = int(frozen['evaluation']['source'][0]['env']['agent']['harness']['env'][ENVIRONMENT_VARIABLE]) | |
| receipt['recovery_patch_sha256'] = frozen['runtime_sha256']['bash_recovery.py'] | |
| if calibration: | |
| from huggingface_hub import snapshot_download | |
| model_path = await asyncio.to_thread(snapshot_download, frozen['experiment']['model'], | |
| revision=frozen['experiment']['model_revision']) | |
| else: | |
| assert (adapter/'.finished').exists() | |
| from safetensors import safe_open | |
| with safe_open(adapter/'adapter_model.safetensors', framework='numpy') as tensors: | |
| assert len(tensors.keys()) > 0 | |
| receipt['adapter_sha256'] = hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| original = json.loads((Path('/outputs/prime')/adapter_run/'launch.json').read_text()) | |
| model_path = original['model']['name'] | |
| if final_heldout and adapter is not None: | |
| assert Path(adapter_run).name == adapter_run and adapter_run not in ('', '.', '..') | |
| prior = json.loads((Path('/outputs/prime')/adapter_run/'receipt.json').read_text()) | |
| if prior['status'] != 'completed': | |
| # Preserve the original failed postflight receipt. A separately | |
| # recorded CPU revalidation may authorize only this saved adapter. | |
| verified = json.loads((Path('/outputs/prime')/(adapter_run+'-heldout')/'verification.json').read_text()) | |
| prior_path = Path('/outputs/prime')/adapter_run/'receipt.json' | |
| assert verified['original_receipt_sha256'] == hashlib.sha256(prior_path.read_bytes()).hexdigest() | |
| assert verified['status']=='checkpoint_verified' and verified['full_resume_tested'] is False | |
| assert verified['frozen_sha256']==prior['frozen_sha256'] | |
| assert verified['adapter_sha256']==hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| assert prior['exit_code']==0 and prior['launcher_stopped'] | |
| assert [c['step'] for c in verified['checkpoints']]==[5,10] | |
| else: | |
| assert prior['checkpoint_metadata_verified'] and prior['launcher_stopped'] | |
| assert prior['max_steps']==10 and (adapter/'.finished').is_file() | |
| from safetensors import safe_open | |
| with safe_open(adapter/'adapter_model.safetensors', framework='numpy') as tensors: | |
| assert len(tensors.keys()) > 0 | |
| receipt['adapter_sha256'] = hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| if benchmark: | |
| assert adapter is not None and (adapter/'.finished').is_file() | |
| digest = hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| assert digest == BENCHMARK_ADAPTER_SHA256, 'Adapter changed' | |
| adapter_config = json.loads((adapter/'adapter_config.json').read_text()) | |
| assert adapter_config['r'] == 16 and adapter_config['lora_alpha'] == 32 | |
| receipt.update(adapter_sha256=digest, adapter_config=adapter_config) | |
| assert Path(model_path).is_dir() | |
| config = tomllib.loads(Path('/workspace-training/train.toml').read_text()) | |
| if calibration: | |
| selected_sources = frozen['evaluation']['source'] | |
| expected = json.loads(Path('/workspace-calibration/candidates.json').read_text())['task_manifest'] | |
| if multi_screen: | |
| expected = json.loads((Path('/workspace-calibration') / ('screening-round2-manifest.json' if screening100 else 'screening-all116-manifest.json')).read_text()) | |
| expected = {name:expected[name] for source in selected_sources | |
| for name in source['env']['taskset']['tasks']} | |
| if validation is not None: | |
| expected = frozen['task_manifest'] | |
| tasks = load_evaluation_tasks(selected_sources, expected) | |
| else: | |
| tasks = load_tasks() | |
| assert len(tasks) == 4 | |
| await task_cache.commit.aio() | |
| model_name = 'workspace-step-2' | |
| serving = {'deployment': {'type': 'single_node', 'gpus_per_node': 1}, | |
| 'output_dir': str(directory/'inference'), | |
| 'vllm': {**config['inference']['vllm'], 'model': model_path, | |
| 'enable_lora': True, 'max_lora_rank': 16, | |
| 'max_num_seqs': 4, 'served_model_name': 'workspace-base', | |
| 'tool_call_parser': 'qwen3_coder', 'enable_auto_tool_choice': True}} | |
| serving['vllm'].pop('revision', None) | |
| if calibration: | |
| serving = deepcopy(frozen['inference']) | |
| serving['output_dir'] = str(directory/'inference') | |
| serving['vllm'].update(model=model_path, seed=frozen['experiment']['inference_seeds'][replica]) | |
| model_name = 'workspace-final-step10' if final_heldout and adapter is not None else frozen['evaluation']['model'] | |
| if benchmark: | |
| serving = benchmark_serving(serving, benchmark) | |
| model_name = 'workspace-step-2-benchmark' | |
| parsed = InferenceConfig.model_validate(deepcopy(serving)) | |
| namespace = parsed.to_namespace() | |
| assert namespace.tool_call_parser == 'qwen3_coder' and namespace.enable_auto_tool_choice | |
| (directory/'inference.json').write_text(json.dumps(serving)) | |
| log = (directory/'inference.log').open('w');logs.append(log) | |
| env = {**os.environ, 'PATH': '/app/.venv/bin:'+os.environ['PATH'], | |
| 'VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT], 'VLLM_ALLOW_RUNTIME_LORA_UPDATING': 'true'} | |
| if benchmark: | |
| # Baseline namespaces are unique per pass; candidate reuses its first-pass cache. | |
| if benchmark == 'candidate': | |
| cache_root = Path('/outputs/prime/native-compile-cache') / run_id.removesuffix('-startup').removesuffix('-eval') / benchmark | |
| else: | |
| cache_root = Path('/tmp') / run_id / 'vllm-cache' | |
| env.update(VLLM_CACHE_ROOT=str(cache_root)) | |
| receipt['cache_root'] = str(cache_root) | |
| from importlib.metadata import version | |
| receipt['versions'] = {name: version(name) for name in ('prime-rl', 'vllm', 'torch', 'verifiers', 'harbor', 'modal', 'renderers')} | |
| engine_started = time.monotonic() | |
| server = await asyncio.create_subprocess_exec('/usr/bin/timeout', '--signal=TERM', '--kill-after=30s', | |
| '21000s' if multi_screen else '6600s', '/app/.venv/bin/inference','@',str(directory/'inference.json'), | |
| cwd='/app',env=env,stdout=log,stderr=log,start_new_session=True) | |
| receipt['status'] = 'inference_starting';await save() | |
| async with httpx.AsyncClient(timeout=30,headers={'[REDACTED_CREDENTIAL_ASSIGNMENT]}) as client: | |
| deadline = time.monotonic()+1500 | |
| while time.monotonic() < deadline: | |
| if server.returncode is not None: | |
| raise RuntimeError('Inference exited; inspect inference.log') | |
| try: | |
| response = await client.get('http://127.0.0.1:8000/health') | |
| if response.status_code == 200: break | |
| except httpx.HTTPError: pass | |
| await asyncio.sleep(5) | |
| else: raise TimeoutError('Inference startup exceeded 1500s') | |
| if adapter is not None: | |
| response = await client.post('http://127.0.0.1:8000/load_lora_adapter', | |
| json={'lora_name':model_name,'lora_path':str(adapter)},timeout=180) | |
| response.raise_for_status() | |
| response = await client.get('http://127.0.0.1:8000/v1/models');response.raise_for_status() | |
| advertised_models = [m['id'] for m in response.json()['data']] | |
| receipt['advertised_models'] = advertised_models | |
| assert model_name in advertised_models, f'Expected {model_name!r}; server advertised {advertised_models!r}' | |
| if calibration: | |
| unauthorized = await client.get('http://127.0.0.1:8000/v1/models', | |
| headers={'[REDACTED_CREDENTIAL_ASSIGNMENT]}) | |
| assert unauthorized.status_code == 401, 'Inference must reject invalid API keys' | |
| receipt['authentication_verified'] = True | |
| smoke = await client.post('http://127.0.0.1:8000/v1/chat/completions', | |
| json={'model': model_name, 'messages': [{'role': 'user', 'content': 'Reply OK.'}], | |
| 'temperature': 1.0 if benchmark else 0.0, 'max_tokens': 32, | |
| **({'top_k': 20, 'top_p': 0.95, 'min_p': 0.0, 'seed': 9001} if benchmark else {}), | |
| 'chat_template_kwargs': {'enable_thinking': bool(benchmark)}}, timeout=180) | |
| smoke.raise_for_status() | |
| assert smoke.json().get('choices'), 'Readiness generation returned no choices' | |
| receipt['generation_verified'] = True | |
| if benchmark: | |
| receipt['training_inference_probe'] = await benchmark_probe(model_path, model_name, directory) | |
| receipt['ready_seconds'] = time.monotonic() - engine_started | |
| await save() | |
| if startup_only: | |
| receipt['status'] = 'startup_probe_completed' | |
| return receipt | |
| receipt['adapter_loaded'] = adapter is not None | |
| async with contextlib.AsyncExitStack() as tunnels: | |
| tunnel = await tunnels.enter_async_context(modal.forward(8001)) | |
| source = deepcopy(config['orchestrator']['train']['source'][0]) | |
| source['name'] = 'workspace-final' | |
| source['env']['taskset'] = source_config().model_dump(mode='json',exclude_none=True) | |
| source['env']['interception'] = {'type':'server','tunnel':{'type':'custom','url':tunnel.url,'port':8001}} | |
| source['serve'] = {'pool':{'type':'static','num_workers':1},'max_concurrent':4} | |
| evaluation = {'model':model_name,'client':{'base_url':'http://127.0.0.1:8000/v1','api_key_var':'VLLM_API_KEY'}, | |
| 'concurrency':{'initial_inflight':4,'min_inflight':4,'max_inflight':4}, | |
| 'group_size':1,'select':{'limit':4,'shuffle':False}, | |
| 'sampling':config['orchestrator']['eval']['sampling'], 'source':[source], | |
| 'output_dir':str(directory),'run':{'name':'evaluation'},'dashboard':False} | |
| if calibration: | |
| evaluation = deepcopy(frozen['evaluation']) | |
| evaluation['output_dir'] = str(directory) | |
| if final_heldout: | |
| evaluation['model'] = model_name | |
| for index, eval_source in enumerate(evaluation['source']): | |
| source_tunnel = tunnel if index == 0 else await tunnels.enter_async_context(modal.forward(8001+index)) | |
| eval_source['env']['interception']['tunnel'].update(url=source_tunnel.url, port=8001+index) | |
| if benchmark: | |
| evaluation['model'] = model_name | |
| evaluation['sampling']['extra_body']['cache_salt'] = 'benchmark-step2-' + BENCHMARK_ADAPTER_SHA256 | |
| EvalConfig.model_validate(deepcopy(evaluation)) | |
| (directory/'eval.json').write_text(json.dumps(evaluation,indent=2)) | |
| log = (directory/'eval.log').open('w');logs.append(log) | |
| receipt['status']='evaluating';await save() | |
| eval_started = time.monotonic() | |
| job = await asyncio.create_subprocess_exec('/usr/bin/timeout', '--signal=TERM', '--kill-after=60s', | |
| '18000s' if multi_screen else '5100s', '/app/.venv/bin/eval','@',str(directory/'eval.json'), | |
| cwd='/app',env=env,stdout=log,stderr=log,start_new_session=True) | |
| receipt['eval_exit_code'] = await asyncio.wait_for(job.wait(),18060 if multi_screen else (5100 if calibration else 3000)) | |
| receipt['eval_seconds'] = time.monotonic() - eval_started | |
| assert receipt['eval_exit_code']==0, 'Official eval failed; inspect eval.log' | |
| receipt['status']='eval_process_completed_results_pending_review' | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error)) | |
| raise | |
| finally: | |
| for process in (job,server): | |
| if process is not None and process.returncode is None: | |
| from training_lifecycle import stop_launcher | |
| await stop_launcher(process, grace=60) | |
| for log in logs: log.close() | |
| persistence.cancel() | |
| try: await persistence | |
| except asyncio.CancelledError: pass | |
| receipt['function_seconds'] = time.monotonic() - started | |
| receipt['ended_unix'] = time.time() | |
| receipt['processes_stopped']=all(p is None or p.returncode is not None for p in (server,job)) | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def calibrate(run_id: str = "calibration-sixteen-v1", launch: bool = False): | |
| """Submit both evaluation replicas only when explicitly requested.""" | |
| import json | |
| config = calibration_config() | |
| print(json.dumps(config['experiment'], indent=2)) | |
| if not launch: | |
| print("Prepared only. No GPU functions submitted.") | |
| return | |
| assert Path(run_id).name == run_id and run_id not in ('', '.', '..') | |
| import subprocess | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not any(entry.path.strip('/') == 'prime/'+run_id for entry in outputs.iterdir('/prime', recursive=False)), 'Run ID already exists' | |
| calls = [evaluate.spawn(run_id, calibration=True, replica=i) for i in range(2)] | |
| receipt = {'run_id': run_id, 'app_id': app.app_id, 'function_call_ids': [c.object_id for c in calls], | |
| 'output': 'workspace-agent-training:/prime/'+run_id} | |
| (ROOT/'calibration'/('launch-'+run_id+'.json')).write_text(json.dumps(receipt, indent=2)+'\n') | |
| print(json.dumps(receipt, indent=2), flush=True) | |
| for call in calls: | |
| print(call.get()) | |
| BENCHMARK_ADAPTER_SHA256 = 'd33033f3755bd14e90a945dcf104a89b86a32505e7835040609bb77e03a30d96' | |
| def benchmark_serving(serving, arm): | |
| """One supported knob comparison, with the real training inference contract.""" | |
| from copy import deepcopy | |
| result = deepcopy(serving) | |
| result.update(router=None, enable_return_sampling_mask=True) | |
| result['vllm'].update(enable_lora=True, max_lora_rank=16, max_num_seqs=32, | |
| served_model_name=['workspace-benchmark-base'], seed=4100, | |
| logprobs_mode='processed_logprobs', | |
| max_num_batched_tokens=8192 if arm == 'baseline' else 16384) | |
| if arm == 'candidate': | |
| result['vllm']['safetensors_load_strategy'] = 'prefetch' | |
| assert result['vllm']['quantization'] == 'fp8_per_block' | |
| return result | |
| async def benchmark_probe(model_path, model_name, directory): | |
| """Use the installed official renderer client to verify sampled-token evidence.""" | |
| import asyncio | |
| import json | |
| import math | |
| from openai import AsyncOpenAI | |
| from renderers import create_renderer, Qwen35RendererConfig | |
| from renderers.base import load_tokenizer | |
| from renderers.client import generate | |
| from verifiers.v1.types import SamplingMask | |
| renderer = await asyncio.to_thread(lambda: create_renderer( | |
| load_tokenizer(model_path), Qwen35RendererConfig(enable_thinking=True))) | |
| async with AsyncOpenAI(base_url='http://127.0.0.1:8000/v1', [REDACTED_CREDENTIAL_ASSIGNMENT], | |
| timeout=180, max_retries=0) as client: | |
| result = await generate(client=client, renderer=renderer, model=model_name, | |
| messages=[{'role': 'user', 'content': 'Reply OK.'}], | |
| sampling_params={'temperature': 1.0, 'top_k': 20, 'top_p': 0.95, | |
| 'min_p': 0.0, 'max_tokens': 32, 'seed': 9002}, | |
| cache_salt='benchmark-step2-' + BENCHMARK_ADAPTER_SHA256) | |
| tokens = result['completion_ids']; logprobs = result['completion_logprobs'] | |
| assert tokens and len(tokens) == len(logprobs) and all(math.isfinite(x) and x > -9999 for x in logprobs) | |
| mask = SamplingMask.from_sampling_mask(result['sampling_mask']) | |
| assert len(mask.counts) == len(tokens) and all(0 < int(c) <= 20 for c in mask.counts) | |
| offset = 0 | |
| for token, count in zip(tokens, mask.counts): | |
| assert token in mask.ids[offset:offset+int(count)] | |
| offset += int(count) | |
| evidence = {'completion_ids': tokens, 'completion_logprobs': logprobs, | |
| 'sampling_mask_counts': mask.counts.tolist(), 'sampling_mask_ids': mask.ids.tolist(), | |
| 'cache_salt': 'benchmark-step2-' + BENCHMARK_ADAPTER_SHA256, | |
| 'weight_transition_tested': False, 'policy_attribution_in_training_tested': False} | |
| (directory/'training-inference-probe.json').write_text(json.dumps(evidence, indent=2)+'\n') | |
| return {'tokens': len(tokens), 'finite_logprobs': True, 'sampled_token_in_every_mask': True, | |
| 'cache_salt_sent': True, 'weight_transition_tested': False} | |
| @app.function(image=evaluation_image, cpu=1, memory=2048, timeout=15000, | |
| max_containers=1, scaledown_window=2, retries=0, volumes={'/outputs': outputs}) | |
| async def benchmark_campaign(run_id: str, submitted): | |
| """A single remote parent owns all child calls after the local client exits.""" | |
| import asyncio | |
| import hashlib | |
| import json | |
| import time | |
| assert Path(run_id).name == run_id and run_id not in ('', '.', '..') | |
| directory = Path('/outputs/prime') / run_id | |
| directory.mkdir(parents=True, exist_ok=False) | |
| receipt = {'run_id': run_id, 'status': 'preflight', 'app_id': app.app_id, | |
| 'profile': ACTIVE_PROFILE, 'workspace': ACTIVE_WORKSPACE, 'trainer_gpus': 0, | |
| 'max_concurrent_inference_gpus': 2, 'training_updates': 0, | |
| 'calls': [], 'started_unix': time.time(), | |
| 'output': 'workspace-agent-training:/prime/'+run_id} | |
| calls = [] | |
| async def save(): | |
| (directory/'campaign.json').write_text(json.dumps(receipt, indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| try: | |
| adapter = Path('/outputs/prime/training4-20261028-02/training/broadcasts/step_2') | |
| assert (adapter/'.finished').is_file() | |
| digest = hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| assert digest == BENCHMARK_ADAPTER_SHA256 | |
| cfg = json.loads((adapter/'adapter_config.json').read_text()) | |
| assert cfg['r'] == 16 and cfg['lora_alpha'] == 32 | |
| receipt.update(adapter=str(adapter), adapter_sha256=digest) | |
| frozen = calibration_config() | |
| (directory/'frozen-calibration.json').write_text(json.dumps(frozen, indent=2)+'\n') | |
| configs = {arm: benchmark_serving(frozen['inference'], arm) for arm in ('baseline', 'candidate')} | |
| (directory/'benchmark-configs.json').write_text(json.dumps(configs, indent=2)+'\n') | |
| receipt['configuration_changes'] = { | |
| 'common': {'adapter': digest, 'enable_return_sampling_mask': True, 'logprobs_mode': 'processed_logprobs', | |
| 'seed': 4100, 'max_num_seqs': 32, 'stochastic_readiness': True}, | |
| 'candidate_vs_baseline': {'max_num_batched_tokens': [8192, 16384], | |
| 'safetensors_load_strategy': [None, 'prefetch'], | |
| 'cache': ['fresh /tmp namespace each pass', 'same persistent Volume namespace both passes']}} | |
| await save() | |
| for phase in ('startup', 'eval'): | |
| calls = [] | |
| for replica, arm in enumerate(('baseline', 'candidate')): | |
| call = await evaluate.spawn.aio(run_id+'-'+phase, | |
| adapter_run='training4-20261028-02', calibration=True, replica=replica, | |
| benchmark=arm, startup_only=phase == 'startup') | |
| calls.append(call) | |
| receipt['calls'].append({'phase': phase, 'arm': arm, 'function_call_id': call.object_id, | |
| 'output': f'workspace-agent-training:/prime/{run_id}-{phase}/replica-{replica}'}) | |
| receipt['status'] = phase+'_submitted' | |
| await save() | |
| if phase == 'startup': | |
| try: | |
| await submitted.put.aio(receipt) | |
| except Exception as exc: | |
| receipt['submission_ack_error'] = repr(exc) | |
| await save() | |
| results = await asyncio.wait_for( | |
| asyncio.gather(*(c.get.aio() for c in calls), return_exceptions=True), | |
| 2100 if phase == 'startup' else 7000) | |
| receipt[phase+'_results'] = [repr(r) if isinstance(r, BaseException) else r for r in results] | |
| if any(isinstance(r, BaseException) for r in results): | |
| raise RuntimeError(f'{phase} failed; no further phases will be launched') | |
| await save() | |
| receipt['status'] = 'completed_results_pending_review' | |
| except BaseException as exc: | |
| receipt.update(status='failed', error=repr(exc)) | |
| # Explicit cancellation is only needed if the remote parent itself is interrupted. | |
| await asyncio.gather(*(c.cancel.aio() for c in calls), return_exceptions=True) | |
| raise | |
| finally: | |
| receipt['finished_unix'] = time.time() | |
| print(json.dumps(receipt), flush=True) | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def optimize(run_id: str, launch: bool = False): | |
| """Run with modal run --detach; wait only for remote submission, never results.""" | |
| import json | |
| import subprocess | |
| from copy import deepcopy | |
| from prime_rl.configs.inference import InferenceConfig | |
| frozen = calibration_config() | |
| configs = {arm: benchmark_serving(frozen['inference'], arm) for arm in ('baseline', 'candidate')} | |
| for config in configs.values(): | |
| parsed = InferenceConfig.model_validate(deepcopy(config)); ns = parsed.to_namespace() | |
| assert parsed.router is None and ns.enable_lora and ns.max_lora_rank == 16 | |
| assert ns.return_sampling_mask and ns.logprobs_mode == 'processed_logprobs' | |
| path = ROOT/'calibration'/('launch-'+run_id+'.json') | |
| assert not path.exists(), 'Local launch receipt already exists' | |
| if not launch: | |
| print(json.dumps(configs, indent=2)); return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not any(e.path.strip('/') == 'prime/'+run_id for e in outputs.iterdir('/prime', recursive=False)) | |
| with modal.Queue.ephemeral() as submitted: | |
| call = benchmark_campaign.spawn(run_id, submitted) | |
| local_receipt = {'run_id': run_id, 'app_id': app.app_id, 'controller_call_id': call.object_id, | |
| 'status': 'controller_submitted', 'configs': configs, | |
| 'output': 'workspace-agent-training:/prime/'+run_id} | |
| path.write_text(json.dumps(local_receipt, indent=2)+'\n') | |
| try: | |
| remote_receipt = submitted.get(timeout=120) | |
| local_receipt.update(remote_submission=remote_receipt, status='gpu_calls_submitted') | |
| except Exception as exc: | |
| local_receipt['submission_ack_error'] = repr(exc) | |
| path.write_text(json.dumps(local_receipt, indent=2)+'\n') | |
| print(json.dumps(local_receipt, indent=2), flush=True) | |
| # The remote controller remains active and owns the awaited child calls. | |
| def rollout_comparison_plan(): | |
| """Freeze a two-update systems comparison, not a ten-epoch training run.""" | |
| from copy import deepcopy | |
| configs = {} | |
| for concurrency in (64, 128): | |
| cfg, _ = configuration(Path('/validation'), 'https://train.invalid', | |
| 'https://eval.invalid', 2, concurrency, | |
| comparison=True, validate_tasks=False) | |
| configs[str(concurrency)] = cfg | |
| def differences(a, b, path=''): | |
| if isinstance(a, dict) and isinstance(b, dict): | |
| return sum((differences(a.get(k), b.get(k), path+'.'+k) | |
| for k in sorted(set(a)|set(b))), []) | |
| if isinstance(a, list) and isinstance(b, list) and len(a)==len(b): | |
| return sum((differences(x,y,path+'.'+str(i)) for i,(x,y) in enumerate(zip(a,b))), []) | |
| return [] if a==b else [{'path':path.lstrip('.'),'c64':a,'c128':b}] | |
| diff = differences(configs['64'], configs['128']) | |
| expected = { | |
| 'orchestrator.concurrency.initial_inflight', | |
| 'orchestrator.concurrency.min_inflight', | |
| 'orchestrator.concurrency.max_inflight', | |
| 'orchestrator.train.source.0.serve.max_concurrent', | |
| 'orchestrator.eval.source.0.serve.max_concurrent', | |
| 'inference.vllm.max_num_seqs', | |
| } | |
| assert {d['path'] for d in diff} == expected, diff | |
| from prime_rl.configs.rl import RLConfig | |
| for c, cfg in configs.items(): | |
| parsed=RLConfig.model_validate(deepcopy(cfg)) | |
| ns=parsed.inference.to_namespace() | |
| assert parsed.inference.router is None | |
| assert ns.return_sampling_mask and ns.max_num_seqs==int(c) | |
| assert ns.tool_call_parser=='qwen3_coder' and ns.enable_auto_tool_choice | |
| assert parsed.orchestrator.model.client.api_key_var=='VLLM_API_KEY' | |
| assert parsed.orchestrator.max_off_policy_steps==1 | |
| assert parsed.orchestrator.monitors.file is not None and parsed.trainer.monitors.file is not None | |
| return { | |
| 'concurrencies':[64,128], 'order':'sequential, one H100 trainer + one H100 inference per arm', | |
| 'max_steps_per_arm':2, 'batch_size':16, 'group_size':4, 'task_group_slots_per_update':4, | |
| 'tasks':list(ROLLOUT_COMPARISON_TASKS), 'taskset':comparison_taskset(), | |
| 'selection':'same Qwen3.5-9B/bash calibration: 2-6 passes inclusive out of 8; six qualify', | |
| 'initialization':'same immutable base revision; fresh LoRA and optimizer per arm; no resume', | |
| 'config_diff':diff, 'configs':configs, | |
| 'metrics':{ | |
| 'usable_batch_time':'native orchestrator time/step plus shipment timestamp; first/second step separately', | |
| 'accepted_samples_per_second':'effective shipped episodes, attributed to a completed trainer step, divided by matching wall interval', | |
| 'trainer_idle_time':'native trainer time/wait_for_batch; fraction=sum(wait)/sum(time/step)', | |
| 'acceptance':'use effective cohort annotations, not all arrivals or trainer packed microbatch counts', | |
| 'additional':['optimizer steps','stale drops','policy lag','trainable fraction','task distribution', | |
| 'reward','truncation','provider errors','checkpoint and cleanup'], | |
| }, | |
| 'limits':['two-update pilot, one run per arm; no learning-quality or steady-state certification', | |
| 'same seeds/order do not guarantee identical asynchronous accepted cohorts', | |
| 'passes and failures can be usable; zero-advantage traces reported separately', | |
| 'checkpoint save remains native and may hit existing watchdog if finalization stalls'], | |
| } | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=15000, | |
| max_containers=1,retries=0, | |
| secrets=[modal.Secret.from_name("workspace-task-registry-readonly")], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def rollout_comparison_controller(run_id: str, submitted): | |
| import asyncio | |
| import json | |
| import os | |
| import time | |
| from copy import deepcopy | |
| directory=Path('/outputs/prime')/run_id | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'cpu_preflight', | |
| 'started_unix':time.time(),'arms':[], | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| async def save(): | |
| (directory/'campaign.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| active=None | |
| try: | |
| await save() | |
| plan=rollout_comparison_plan() | |
| (directory/'plan.json').write_text(json.dumps(plan,indent=2)+'\n') | |
| tasks=await asyncio.to_thread(load_comparison_tasks) | |
| assert {t.data.name for t in tasks}==set(ROLLOUT_COMPARISON_TASKS) | |
| receipt['native_git_manifest_verified']=True | |
| await task_cache.commit.aio() | |
| for concurrency in (64,128): | |
| cfg=deepcopy(plan['configs'][str(concurrency)]) | |
| cfg['output_dir']=str(directory/f'cpu-c{concurrency}') | |
| cfg['run']['name']='validation' | |
| path=directory/f'cpu-c{concurrency}.json' | |
| path.write_text(json.dumps(cfg,indent=2)+'\n') | |
| with (directory/f'cpu-c{concurrency}.log').open('w') as log: | |
| proc=await asyncio.create_subprocess_exec('/usr/bin/timeout','180s', | |
| '/app/.venv/bin/rl','@',str(path),'--dry-run',cwd='/app', | |
| env={**os.environ,'WANDB_MODE':'disabled','VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT]}, | |
| stdout=log,stderr=log) | |
| code=await asyncio.wait_for(proc.wait(),195) | |
| assert code==0, f'Official CPU dry-run c{concurrency} failed: {code}' | |
| receipt.update(status='cpu_preflight_passed',cpu_dry_runs_passed=[64,128]) | |
| await save() | |
| for concurrency in (64,128): | |
| arm_id=f'{run_id}-c{concurrency}' | |
| active=await train.spawn.aio(arm_id,max_steps=2,rollout_concurrency=concurrency,comparison=True) | |
| arm={'concurrency':concurrency,'run_id':arm_id,'call_id':active.object_id, | |
| 'status':'submitted','submitted_unix':time.time(), | |
| 'output':'workspace-agent-training:/prime/'+arm_id} | |
| receipt['arms'].append(arm);receipt['status']='training_comparison_running' | |
| await save() | |
| if concurrency==64: | |
| await submitted.put.aio(receipt) | |
| try: | |
| result=await active.get.aio() | |
| arm.update(status=result['status'],result=result) | |
| except Exception as exc: | |
| arm.update(status='failed',error=repr(exc)) | |
| arm['finished_unix']=time.time() | |
| active=None | |
| await save() | |
| receipt['status']='completed' if all(a['status']=='completed' for a in receipt['arms']) else 'completed_with_failures' | |
| except BaseException as exc: | |
| receipt.update(status='failed',error=repr(exc)) | |
| if active is not None:await active.cancel.aio() | |
| try:await submitted.put.aio(receipt) | |
| except Exception:pass | |
| raise | |
| finally: | |
| receipt['updated_unix']=time.time() | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def compare_rollouts(run_id: str, launch: bool=False): | |
| import json | |
| import subprocess | |
| plan=rollout_comparison_plan() | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| assert not path.exists(), 'Existing launch receipt; do not duplicate' | |
| if not launch: | |
| print(json.dumps(plan,indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| assert not any(e.path.strip('/')=='prime/'+run_id for e in outputs.iterdir('/prime',recursive=False)) | |
| with modal.Queue.ephemeral() as queue: | |
| call=rollout_comparison_controller.spawn(run_id,queue) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'controller_submitted','plan':plan} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| try: | |
| receipt['remote_submission']=queue.get(timeout=420) | |
| receipt['status']=receipt['remote_submission']['status'] | |
| except Exception as exc:receipt['submission_ack_error']=repr(exc) | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps({k:v for k,v in receipt.items() if k!='plan'},indent=2),flush=True) | |
| def screening64_config(): | |
| from copy import deepcopy | |
| from prime_rl.configs.eval import EvalConfig | |
| from prime_rl.configs.inference import InferenceConfig | |
| frozen=deepcopy(calibration_config()) | |
| frozen['evaluation']['group_size']=8 | |
| frozen['evaluation']['concurrency']={k:64 for k in ('initial_inflight','min_inflight','max_inflight')} | |
| frozen['evaluation']['source'][0]['serve']['max_concurrent']=64 | |
| frozen['inference']['vllm']['max_num_seqs']=64 | |
| frozen['experiment'].update(replicas=1,attempts_per_task_per_replica=8, | |
| episode_concurrency_per_replica=64,total_episode_concurrency=64) | |
| EvalConfig.model_validate(deepcopy(frozen['evaluation'])) | |
| parsed=InferenceConfig.model_validate(deepcopy(frozen['inference'])) | |
| assert parsed.router is None and parsed.to_namespace().max_num_seqs==64 | |
| assert frozen['evaluation']['group_size']*frozen['evaluation']['select']['limit']==128 | |
| return frozen | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=7500, | |
| max_containers=1,retries=0, | |
| secrets=[modal.Secret.from_name("workspace-task-registry-readonly")], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def screening64_controller(run_id: str, submitted): | |
| import asyncio | |
| import json | |
| import time | |
| import sys | |
| sys.path.insert(0,'/workspace-smoke') | |
| from task_source import git_credentials,task_manifest | |
| from verifiers.v1.tasksets.harbor import HarborConfig,HarborTaskset | |
| directory=Path('/outputs/prime')/run_id | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'cpu_preflight', | |
| 'started_unix':time.time(),'output':'workspace-agent-training:/prime/'+run_id} | |
| async def save(): | |
| (directory/'campaign.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| call=None | |
| try: | |
| await save() | |
| frozen=screening64_config() | |
| (directory/'frozen-config.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| def validate_git(): | |
| with git_credentials(): | |
| tasks=list(HarborTaskset(HarborConfig.model_validate( | |
| frozen['evaluation']['source'][0]['env']['taskset'])).load()) | |
| expected=json.loads(Path('/workspace-calibration/candidates.json').read_text())['task_manifest'] | |
| assert task_manifest(tasks)==expected and len(tasks)==16 | |
| assert all(t.data.upload_environment for t in tasks) | |
| await asyncio.to_thread(validate_git) | |
| await task_cache.commit.aio() | |
| receipt['native_git_manifest_verified']=True | |
| call=await evaluate.spawn.aio(run_id,calibration=True,replica=0,screening64=True) | |
| receipt.update(status='worker_submitted',worker_call_id=call.object_id) | |
| await save() | |
| await submitted.put.aio(receipt) | |
| result=await call.get.aio() | |
| receipt.update(status=result['status'],worker_receipt=result) | |
| except BaseException as exc: | |
| receipt.update(status='failed',error=repr(exc)) | |
| if call is not None:await call.cancel.aio() | |
| try:await submitted.put.aio(receipt) | |
| except Exception:pass | |
| raise | |
| finally: | |
| receipt['updated_unix']=time.time() | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def screen64(run_id: str, launch: bool=False): | |
| import json | |
| import subprocess | |
| frozen=screening64_config() | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| receipt_path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| assert not receipt_path.exists() | |
| if not launch: | |
| print(json.dumps(frozen,indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not any(e.path.strip('/')=='prime/'+run_id for e in outputs.iterdir('/prime',recursive=False)) | |
| with modal.Queue.ephemeral() as queue: | |
| call=screening64_controller.spawn(run_id,queue) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'controller_submitted','planned_attempts':128,'concurrency':64, | |
| 'inference_gpus':1,'trainer_gpus':0} | |
| receipt_path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| try: | |
| receipt['remote_submission']=queue.get(timeout=180) | |
| receipt['status']=receipt['remote_submission']['status'] | |
| except Exception as exc:receipt['submission_ack_error']=repr(exc) | |
| receipt_path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| STEADY_CONCURRENCIES = (16, 32, 64, 128) | |
| def steady_capacities(concurrency=0): | |
| assert concurrency in (0, 16, 32, 64, 98, 128) | |
| return (concurrency,) if concurrency else STEADY_CONCURRENCIES | |
| STEADY_CASES = ( | |
| {'name': 'uncached-long-prefill', 'input': 16384, 'prefix': 0, 'output': 2048, 'seed': 7101}, | |
| {'name': 'shared-prefix-long-decode', 'input': 4096, 'prefix': 24576, 'output': 8192, 'seed': 7102}, | |
| ) | |
| def steady_serving(frozen, model_path, directory, concurrency): | |
| from copy import deepcopy | |
| assert concurrency in steady_capacities(concurrency) | |
| serving = benchmark_serving(frozen['inference'], 'baseline') | |
| serving['output_dir'] = str(directory/'inference') | |
| serving['vllm'].update(model=model_path, max_num_seqs=concurrency, max_num_batched_tokens=8192) | |
| assert 'safetensors_load_strategy' not in serving['vllm'] and 'env_vars' not in serving | |
| return serving | |
| def steady_command(case, concurrency, model_path, directory): | |
| import json | |
| extra = {'temperature': 1.0, 'top_p': 0.95, 'top_k': 20, 'min_p': 0.0, | |
| 'chat_template_kwargs': {'enable_thinking': True}, | |
| 'logprobs': True, 'top_logprobs': 1, | |
| 'cache_salt': 'steady-step2-' + BENCHMARK_ADAPTER_SHA256} | |
| return ['/app/.venv/bin/vllm', 'bench', 'serve', '--backend', 'openai-chat', | |
| '--base-url', 'http://127.0.0.1:8000', '--endpoint', '/v1/chat/completions', | |
| '--model', model_path, '--tokenizer', model_path, | |
| '--served-model-name', 'workspace-step-2-benchmark', '--dataset-name', 'random', | |
| '--random-input-len', str(case['input']), '--random-prefix-len', str(case['prefix']), | |
| '--random-output-len', str(case['output']), '--random-range-ratio', '0', | |
| '--num-prompts', '64', '--max-concurrency', str(concurrency//2), | |
| '--request-rate', 'inf', '--seed', str(case['seed']), '--num-warmups', '0', | |
| '--ignore-eos', '--extra-body', json.dumps(extra), '--save-result', | |
| '--save-detailed', '--result-dir', str(directory), | |
| '--result-filename', case['name']+'.json', '--percentile-metrics', 'ttft,tpot,itl,e2el', | |
| '--metric-percentiles', '50,95,99', '--disable-tqdm'] | |
| @app.function(image=evaluation_image, gpu='H100', cpu=8, memory=65536, timeout=14400, | |
| max_containers=1, scaledown_window=2, retries=0, | |
| volumes={'/outputs': outputs, '/root/.cache/huggingface': cache}) | |
| async def steady_worker(run_id: str, concurrency: int = 0): | |
| """Official bench serve only; sequential capacities, no task servers/trainer.""" | |
| import asyncio | |
| import contextlib | |
| import hashlib | |
| import json | |
| import os | |
| import time | |
| from importlib.metadata import version | |
| import httpx | |
| from huggingface_hub import snapshot_download | |
| from prime_rl.configs.inference import InferenceConfig | |
| import sys | |
| sys.path.insert(0, '/workspace-smoke') | |
| from training_lifecycle import stop_launcher | |
| await outputs.reload.aio() | |
| directory = Path('/outputs/prime')/run_id/'worker' | |
| directory.mkdir(parents=True, exist_ok=False) | |
| receipt = {'status': 'starting', 'trainer_gpus': 0, 'gpu': 'H100', 'cases': STEADY_CASES, | |
| 'concurrencies': steady_capacities(concurrency), 'batch_token_budget': 8192, | |
| 'requests_per_case': 64, 'output_tokens_per_configuration': 655360, | |
| 'versions': {n: version(n) for n in ('prime-rl','vllm','torch','renderers','modal')}, | |
| 'phases': [], 'started_unix': time.time(), 'contract_sha256': os.environ['WORKSPACE_CONTRACT_SHA256'], | |
| 'limitations': ['synthetic fixed output lengths; no task scores', | |
| 'shared prefix is not a multi-turn/tool/compaction replay', | |
| 'OpenAI transport benchmark; Prime generate checked only by native probe', | |
| 'no distinct weight transitions or trainer acceptance tested']} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| env = {**os.environ, 'PATH': '/app/.venv/bin:'+os.environ['PATH'], | |
| 'VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT], 'OPENAI_[REDACTED_CREDENTIAL_ASSIGNMENT], | |
| 'VLLM_ALLOW_RUNTIME_LORA_UPDATING': 'true'} | |
| adapter = Path('/outputs/prime/training4-20261028-02/training/broadcasts/step_2') | |
| processes = []; files = [] | |
| try: | |
| assert (adapter/'.finished').is_file() | |
| digest = hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| assert digest == BENCHMARK_ADAPTER_SHA256 | |
| ac = json.loads((adapter/'adapter_config.json').read_text()) | |
| assert ac['r']==16 and ac['lora_alpha']==32 | |
| receipt['adapter_sha256'] = digest | |
| frozen = calibration_config() | |
| model = await asyncio.to_thread(snapshot_download, frozen['experiment']['model'], | |
| revision=frozen['experiment']['model_revision']) | |
| # Check installed native CLI before allocating any measured load. | |
| check = await asyncio.create_subprocess_exec('/app/.venv/bin/vllm','bench','serve','--help=all', | |
| env=env,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT) | |
| help_text = (await asyncio.wait_for(check.communicate(),90))[0].decode() | |
| (directory/'bench-help.txt').write_text(help_text) | |
| assert check.returncode==0 | |
| for flag in ('--random-prefix-len','--num-warmups','--save-detailed','--max-concurrency','--extra-body'): | |
| assert flag in help_text, flag | |
| await save() | |
| for concurrency in steady_capacities(concurrency): | |
| phase_dir = directory/f'c{concurrency}'; phase_dir.mkdir() | |
| phase = {'concurrency': concurrency, 'engine_max_num_seqs': concurrency, | |
| 'client_max_concurrency_total': concurrency, 'clients': 2, | |
| 'status': 'engine_starting', 'started_unix': time.time()} | |
| receipt['phases'].append(phase); processes=[]; files=[] | |
| try: | |
| serving = steady_serving(frozen,model,phase_dir,concurrency) | |
| parsed = InferenceConfig.model_validate(serving) | |
| ns = parsed.to_namespace() | |
| assert ns.return_sampling_mask and ns.logprobs_mode=='processed_logprobs' | |
| assert ns.max_num_seqs==concurrency and ns.max_num_batched_tokens==8192 | |
| (phase_dir/'inference.json').write_text(json.dumps(serving,indent=2)+'\n') | |
| log=(phase_dir/'inference.log').open('w');files.append(log) | |
| server=await asyncio.create_subprocess_exec('/usr/bin/timeout','--signal=TERM','--kill-after=30s', | |
| '3000s','/app/.venv/bin/inference','@',str(phase_dir/'inference.json'), | |
| cwd='/app',env=env,stdout=log,stderr=log,start_new_session=True) | |
| processes.append(server);await save() | |
| async with httpx.AsyncClient(timeout=30,headers={'[REDACTED_CREDENTIAL_ASSIGNMENT]}) as client: | |
| deadline=time.monotonic()+1000 | |
| while time.monotonic()<deadline: | |
| assert server.returncode is None, 'engine exited' | |
| try: | |
| if (await client.get('http://127.0.0.1:8000/health')).status_code==200:break | |
| except httpx.HTTPError:pass | |
| await asyncio.sleep(5) | |
| else:raise TimeoutError('engine readiness deadline') | |
| r=await client.get('http://127.0.0.1:8000/v1/models',headers={'[REDACTED_CREDENTIAL_ASSIGNMENT]});assert r.status_code==401 | |
| r=await client.post('http://127.0.0.1:8000/load_lora_adapter',json={'lora_name':'workspace-step-2-benchmark','lora_path':str(adapter)},timeout=180);r.raise_for_status() | |
| phase['native_probe']=await benchmark_probe(model,'workspace-step-2-benchmark',phase_dir) | |
| # Same chat fields as measured clients; engine rejects incompatible mask requests. | |
| r=await client.post('http://127.0.0.1:8000/v1/chat/completions',json={ | |
| 'model':'workspace-step-2-benchmark','messages':[{'role':'user','content':'Reply OK.'}], | |
| 'temperature':1.0,'top_k':20,'top_p':.95,'min_p':0.,'max_completion_tokens':32, | |
| 'chat_template_kwargs':{'enable_thinking':True},'logprobs':True,'top_logprobs':1},timeout=180) | |
| r.raise_for_status();assert r.json()['choices'][0].get('logprobs') | |
| phase['chat_logprobs_verified']=True | |
| r=await client.get('http://127.0.0.1:8000/server_info') | |
| if r.status_code==200: | |
| (phase_dir/'effective-server-info.json').write_text(r.text) | |
| phase['effective_server_info_saved']=True | |
| else: | |
| phase['effective_server_info_status']=r.status_code | |
| phase['effective_engine_limits_review']='Inspect server-info and engine startup log; schema alone is not runtime proof' | |
| phase['warmup']='native32token probe + chat32token probe; bench initial test per client also unmeasured' | |
| async def metrics(): | |
| last_commit=time.monotonic() | |
| with (phase_dir/'metrics.jsonl').open('w') as output: | |
| while True: | |
| try: | |
| r=await client.get('http://127.0.0.1:8000/metrics') | |
| output.write(json.dumps({'time':time.time(),'prometheus':r.text})+'\n');output.flush() | |
| except httpx.HTTPError:pass | |
| if time.monotonic()-last_commit > 30: | |
| await asyncio.wait_for(outputs.commit.aio(),90);last_commit=time.monotonic() | |
| await asyncio.sleep(5) | |
| collector=asyncio.create_task(metrics()) | |
| gpu_log=(phase_dir/'nvidia-smi.csv').open('w');files.append(gpu_log) | |
| gpu=await asyncio.create_subprocess_exec('nvidia-smi','--query-gpu=timestamp,utilization.gpu,utilization.memory,memory.used,power.draw','--format=csv','-l','5',stdout=gpu_log,stderr=gpu_log,start_new_session=True) | |
| processes.append(gpu) | |
| phase['cpu_cgroup_before']={str(p):p.read_text() for p in (Path('/sys/fs/cgroup/cpu.stat'),) if p.exists()} | |
| commands=[steady_command(c,concurrency,model,phase_dir) for c in STEADY_CASES] | |
| (phase_dir/'commands.json').write_text(json.dumps(commands,indent=2)+'\n') | |
| phase.update(status='benchmarking',measured_launch_unix=time.time());await save() | |
| benches=[] | |
| try: | |
| for case,cmd in zip(STEADY_CASES,commands): | |
| out=(phase_dir/(case['name']+'.log')).open('w');files.append(out) | |
| job=await asyncio.create_subprocess_exec('/usr/bin/timeout','--signal=TERM','--kill-after=30s','1800s',*cmd, | |
| env=env,cwd='/app',stdout=out,stderr=out,start_new_session=True) | |
| processes.append(job);benches.append(job) | |
| codes=await asyncio.wait_for(asyncio.gather(*(p.wait() for p in benches)),1840) | |
| phase['bench_exit_codes']=codes | |
| assert codes==[0,0], 'native benchmark failed; inspect preserved logs' | |
| for case in STEADY_CASES: | |
| result=json.loads((phase_dir/(case['name']+'.json')).read_text()) | |
| assert result.get('completed')==64, 'not all requests completed' | |
| phase['status']='completed_results_pending_review' | |
| finally: | |
| collector.cancel() | |
| with contextlib.suppress(asyncio.CancelledError):await collector | |
| phase['cpu_cgroup_after']={str(p):p.read_text() for p in (Path('/sys/fs/cgroup/cpu.stat'),) if p.exists()} | |
| except Exception as exc: | |
| phase.update(status='failed',error=repr(exc)) | |
| # No retries or automatic relaxation; other explicitly authorized capacities still run. | |
| finally: | |
| for proc in reversed(processes): | |
| await stop_launcher(proc,grace=30) | |
| for stream in files:stream.close() | |
| phase.update(finished_unix=time.time(),processes_stopped=all(p.returncode is not None for p in processes)) | |
| await save() | |
| receipt['status']='completed_with_failures' if any(p['status']=='failed' for p in receipt['phases']) else 'completed_results_pending_review' | |
| except BaseException as exc: | |
| receipt.update(status='failed',error=repr(exc));raise | |
| finally: | |
| for proc in reversed(processes): | |
| if proc.returncode is None:await stop_launcher(proc,grace=30) | |
| for stream in files: | |
| if not stream.closed:stream.close() | |
| receipt['finished_unix']=time.time();await save() | |
| return receipt | |
| @app.function(image=evaluation_image,cpu=1,memory=2048, | |
| timeout=15000,max_containers=1,retries=0,volumes={'/outputs':outputs}) | |
| async def steady_controller(run_id: str, submitted, concurrency: int = 0): | |
| import json | |
| directory=Path('/outputs/prime')/run_id;directory.mkdir(parents=True,exist_ok=False) | |
| # Execute the pinned native argparse path on this CPU-only controller first. | |
| # No engine, model generation, or benchmark main() is invoked by parsing. | |
| import asyncio | |
| commands = [steady_command(case, c, '/runtime/model', directory) | |
| for c in steady_capacities(concurrency) for case in STEADY_CASES] | |
| command_file = directory/'cpu-validation-commands.json' | |
| command_file.write_text(json.dumps(commands,indent=2)+'\n') | |
| parser_code = ( | |
| 'import json,sys; from vllm.benchmarks.serve import add_cli_args; ' | |
| 'from vllm.utils.argparse_utils import FlexibleArgumentParser; ' | |
| 'commands=json.load(open(sys.argv[1])); ' | |
| 'p=FlexibleArgumentParser(); add_cli_args(p); ' | |
| 'parsed=[vars(p.parse_args(c[3:])) for c in commands]; ' | |
| 'print(json.dumps({"commands_validated":len(parsed),' | |
| '"commands":[{k:a[k] for k in ' | |
| '("backend","num_prompts","max_concurrency","random_input_len",' | |
| '"random_prefix_len","random_output_len")} for a in parsed]}))' | |
| ) | |
| with (directory/'cpu-command-validation.log').open('w') as log: | |
| validation = await asyncio.create_subprocess_exec('/app/.venv/bin/python','-c',parser_code, | |
| str(command_file),stdout=log,stderr=log) | |
| code = await asyncio.wait_for(validation.wait(),120) | |
| await outputs.commit.aio() | |
| if code != 0: | |
| failure={'run_id':run_id,'app_id':app.app_id,'status':'cpu_command_validation_failed', | |
| 'exit_code':code,'gpu_submitted':False,'output':'workspace-agent-training:/prime/'+run_id} | |
| (directory/'campaign.json').write_text(json.dumps(failure,indent=2)+'\n');await outputs.commit.aio() | |
| await submitted.put.aio(failure) | |
| return failure | |
| call=await steady_worker.spawn.aio(run_id, concurrency=concurrency) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'worker_call_id':call.object_id,'status':'worker_submitted', | |
| 'output':'workspace-agent-training:/prime/'+run_id,'max_gpu_concurrency':1} | |
| (directory/'campaign.json').write_text(json.dumps(receipt,indent=2)+'\n');await outputs.commit.aio() | |
| try: | |
| await submitted.put.aio(receipt) | |
| except Exception as exc: | |
| receipt['submission_ack_error']=repr(exc) | |
| try: | |
| result=await call.get.aio();receipt['status']=result['status'] | |
| except BaseException as exc: | |
| await call.cancel.aio();receipt.update(status='failed',error=repr(exc));raise | |
| finally: | |
| (directory/'campaign.json').write_text(json.dumps(receipt,indent=2)+'\n');await outputs.commit.aio() | |
| return receipt | |
| @app.local_entrypoint() | |
| def steady(run_id: str, launch: bool=False, concurrency: int=0): | |
| import json | |
| import subprocess | |
| from copy import deepcopy | |
| from prime_rl.configs.inference import InferenceConfig | |
| frozen=calibration_config() | |
| capacities=steady_capacities(concurrency) | |
| plan={'run_id':run_id,'concurrencies':capacities,'cases':STEADY_CASES, | |
| 'requests_per_case':64,'batch_tokens':8192,'max_gpu_concurrency':1, | |
| 'output_tokens_per_configuration':655360,'total_output_tokens':655360*len(capacities), | |
| 'engine_limit_equals_total_client_limit':True,'cpu':8,'gpu':'H100', | |
| 'case_timeout_seconds':1800,'worker_timeout_seconds':14400, | |
| 'estimate':'~7-15minutes measured/config at700-1500tokens/s, plus long-prefill/queue variability; hard limits govern', | |
| 'observed5350calls':{'output_p50_p90_p95_p99_max':[204,1658,2689,5862,8192], | |
| 'cached_prompt_p50_p90_p95_p99_max':[12144,23232,25872,28512,29568]}, | |
| 'interpretation':'long-work stress mix, not empirical-frequency replay; no quality grades or nativeRLtransport certification'} | |
| for c in capacities: | |
| parsed=InferenceConfig.model_validate(deepcopy(steady_serving(frozen,'/runtime/model',Path('/runtime/out'),c))) | |
| assert parsed.to_namespace().max_num_seqs==c | |
| if not launch:print(json.dumps(plan,indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json');assert not path.exists() | |
| assert not any(e.path.strip('/')=='prime/'+run_id for e in outputs.iterdir('/prime',recursive=False)) | |
| with modal.Queue.ephemeral() as queue: | |
| call=steady_controller.spawn(run_id,queue,concurrency=concurrency) | |
| receipt={'plan':plan,'app_id':app.app_id,'controller_call_id':call.object_id,'status':'controller_submitted'} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| try:receipt.update(remote_submission=queue.get(timeout=180));receipt['status']=receipt['remote_submission']['status'] | |
| except Exception as exc:receipt['submission_ack_error']=repr(exc) | |
| path.write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt,indent=2),flush=True) | |
| def screening116_config(replica: int = 0, pin_filename: str = "screening-selected100.json"): | |
| """Four disjoint native Harbor selections; every task has eight fresh attempts.""" | |
| import json | |
| from copy import deepcopy | |
| from prime_rl.configs.eval import EvalConfig | |
| from prime_rl.configs.inference import InferenceConfig | |
| assert replica in range(4) | |
| base = ROOT/'calibration' if modal.is_local() else Path('/workspace-calibration') | |
| assert pin_filename in ('screening-selected100.json', 'screening-round2-selected100.json') | |
| pin = json.loads((base/pin_filename).read_text()) | |
| manifest = json.loads((base/pin.get('manifest_filename', 'screening-all116-manifest.json')).read_text()) | |
| task_count = pin.get('task_count', 116) | |
| assert task_count in (100,116) and (task_count == 116 or pin.get('status') == 'cpu_qualified') | |
| shard_size = task_count // 4 | |
| names = sorted(manifest) | |
| assert len(names) == len(set(names)) == task_count | |
| frozen = deepcopy(screening64_config()) | |
| taskset = deepcopy(pin['taskset']) | |
| taskset.update(dataset=pin['combined_dataset'], tasks=names[replica*shard_size:(replica+1)*shard_size]) | |
| frozen['evaluation']['source'][0]['env']['taskset'] = taskset | |
| frozen['evaluation']['source'][0]['name'] = pin['combined_dataset'].split('@')[0] | |
| frozen['evaluation']['select']['limit'] = shard_size | |
| frozen['experiment'].update(replicas=4, task_count=task_count, total_attempts=task_count*8, | |
| total_episode_concurrency=256, task_git_commit=pin['commit'], | |
| inference_seeds=[4100,4101,4102,4103], shard_index=replica, shard_task_count=shard_size) | |
| assert frozen['evaluation']['source'][0]['env']['agent']['runtime'] == {'type':'modal','cpu':0.125,'memory':0.125} | |
| EvalConfig.model_validate(deepcopy(frozen['evaluation'])) | |
| parsed = InferenceConfig.model_validate(deepcopy(frozen['inference'])) | |
| assert parsed.router is None and parsed.to_namespace().max_num_seqs == 64 | |
| return frozen | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=22200, | |
| max_containers=1,retries=0, | |
| secrets=[modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def screening116_controller(run_id: str, cpu_gate: dict, original_gate: dict | None, | |
| pin_filename: str = "screening-selected100.json"): | |
| import asyncio,json,time,sys | |
| sys.path.insert(0,'/workspace-smoke') | |
| from task_source import git_credentials,task_manifest | |
| from verifiers.v1.tasksets.harbor import HarborConfig,HarborTaskset | |
| configs=[screening116_config(i,pin_filename) for i in range(4)] | |
| pin=json.loads((Path('/workspace-calibration')/pin_filename).read_text()) | |
| task_count=pin.get('task_count',116) | |
| directory=Path('/outputs/prime')/run_id | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'preflight', | |
| 'started_unix':time.time(),'planned_attempts':task_count*8,'inference_gpus':4, | |
| 'trainer_gpus':0,'concurrency_per_gpu':64,'worker_call_ids':[], | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| calls=[] | |
| async def save(): | |
| (directory/'campaign.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| assert len({n for c in configs for n in c['evaluation']['source'][0]['env']['taskset']['tasks']}) == task_count | |
| assert cpu_gate['status']=='selected100' and cpu_gate['selected']==pin['tasks'] | |
| if task_count==116: | |
| assert original_gate is not None and original_gate['status']=='passed' and original_gate['package_base_commit']==pin['commit'] | |
| else: | |
| assert original_gate is None and cpu_gate['package_base_commit']==pin['cpu_gate_base_commit'] | |
| assert all(any(c['task']==n and c['mode']==m and c['status']=='passed' | |
| for c in cpu_gate['checks']) for n in pin['tasks'] for m in ('noop','oracle')) | |
| (directory/'original16-cpu-gate.json').write_text(json.dumps(original_gate,indent=2)+'\n') | |
| (directory/'cpu-gate.json').write_text(json.dumps(cpu_gate,indent=2)+'\n') | |
| (directory/'frozen-configs.json').write_text(json.dumps(configs,indent=2)+'\n') | |
| expected=json.loads((Path('/workspace-calibration')/pin.get('manifest_filename','screening-all116-manifest.json')).read_text()) | |
| import hashlib | |
| for n in pin['tasks']: | |
| digest=hashlib.sha256(json.dumps(expected[n],sort_keys=True).encode()).hexdigest() | |
| assert all(any(c['task']==n and c['mode']==m and c['status']=='passed' and | |
| c.get('task_manifest_sha256')==digest for c in cpu_gate['checks']) | |
| for m in ('noop','oracle')) | |
| old_names=set(expected)-set(pin['tasks']) | |
| if task_count==116: | |
| assert len(old_names)==16 | |
| assert all(any(c['task']==n and c['mode']==m and c['status']=='passed' | |
| for c in original_gate['checks']) for n in old_names for m in ('noop','oracle')) | |
| else: | |
| assert not old_names | |
| previous=json.loads(Path('/workspace-calibration/screening-all116-manifest.json').read_text()) | |
| assert not set(expected)&set(previous), 'Round2 must be disjoint from all previously evaluated116' | |
| def validate_git(): | |
| from copy import deepcopy | |
| conf=deepcopy(configs[0]['evaluation']['source'][0]['env']['taskset']) | |
| conf['tasks']=sorted(expected) | |
| with git_credentials(): | |
| tasks=list(HarborTaskset(HarborConfig.model_validate(conf)).load()) | |
| assert len(tasks)==task_count and task_manifest(tasks)==expected | |
| assert all(t.data.upload_environment for t in tasks) | |
| await asyncio.to_thread(validate_git) | |
| await task_cache.commit.aio() | |
| receipt['native_git_manifest_verified']=True | |
| await save() | |
| for i in range(4): | |
| call=await evaluate.spawn.aio(run_id,calibration=True,replica=i,screening116=task_count==116,screening100=task_count==100) | |
| calls.append(call);receipt['worker_call_ids'].append(call.object_id) | |
| receipt['status']='workers_submitting';await save() | |
| receipt['status']='evaluating';await save() | |
| receipt['workers']=await asyncio.gather(*(c.get.aio() for c in calls)) | |
| receipt['status']='eval_processes_completed_results_pending_review' | |
| except BaseException as exc: | |
| receipt.update(status='failed',error=repr(exc)) | |
| for c in calls: | |
| try:await c.cancel.aio() | |
| except Exception:pass | |
| raise | |
| finally: | |
| receipt['updated_unix']=time.time();await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def screen116(run_id: str, launch: bool=False): | |
| import json,subprocess | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| configs=[screening116_config(i) for i in range(4)] | |
| shards=[c['evaluation']['source'][0]['env']['taskset']['tasks'] for c in configs] | |
| assert all(len(s)==29 for s in shards) and len(set(sum(shards,[])))==116 | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| if not launch: | |
| print(json.dumps(configs,indent=2));return | |
| gate=json.loads((ROOT/'.state/screening-pool200-cpu-gate.json').read_text()) | |
| original_gate=json.loads((ROOT/'.state/screening-original16-cpu-gate.json').read_text()) | |
| assert gate['status']=='selected100' and original_gate['status']=='passed','Both CPU gates must pass before GPU submission' | |
| assert not path.exists(),'Run id already submitted; inspect its durable receipt' | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not any(e.path.strip('/')=='prime/'+run_id for e in outputs.iterdir('/prime',recursive=False)) | |
| call=screening116_controller.spawn(run_id,gate,original_gate) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'controller_submitted','planned_attempts':928,'inference_gpus':4, | |
| 'trainer_gpus':0,'concurrency_per_gpu':64, | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| @app.local_entrypoint() | |
| def screen100(run_id: str, launch: bool=False): | |
| """Second disjoint100-task inference screen, using the existing four-worker pipeline.""" | |
| import json,subprocess | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| pin_name='screening-round2-selected100.json' | |
| configs=[screening116_config(i,pin_name) for i in range(4)] | |
| shards=[c['evaluation']['source'][0]['env']['taskset']['tasks'] for c in configs] | |
| assert all(len(s)==25 for s in shards) and len(set(sum(shards,[])))==100 | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| if not launch: | |
| print(json.dumps(configs,indent=2));return | |
| gate=json.loads((ROOT/'.state/screening-round2-cpu-gate.json').read_text()) | |
| pin=json.loads((ROOT/'calibration'/pin_name).read_text()) | |
| assert gate['status']=='selected100' and gate['selected']==pin['tasks'] | |
| assert not path.exists(),'Run id already submitted; inspect its durable receipt' | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not any(e.path.strip('/')=='prime/'+run_id for e in outputs.iterdir('/prime',recursive=False)) | |
| call=screening116_controller.spawn(run_id,gate,None,pin_name) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'controller_submitted','planned_attempts':800,'inference_gpus':4, | |
| 'trainer_gpus':0,'concurrency_per_gpu':64,'task_commit':pin['commit'], | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| def validation11_config(): | |
| """Freeze the existing held-out selection without changing training settings.""" | |
| import json | |
| from copy import deepcopy | |
| plan = json.loads((ROOT/'plans/training103-plan.json').read_text()) | |
| names = plan['split']['validation'] | |
| assert len(names) == len(set(names)) == 11 | |
| assert not set(names) & (set(plan['split']['train']) | set(plan['split']['test'])) | |
| frozen = json.loads((ROOT/'calibration/config.json').read_text()) | |
| frozen['experiment'].update(profile=ACTIVE_PROFILE, workspace=ACTIVE_WORKSPACE) | |
| frozen['evaluation']['group_size'] = 8 | |
| frozen['evaluation']['concurrency'] = {k:64 for k in ('initial_inflight','min_inflight','max_inflight')} | |
| frozen['evaluation']['source'][0]['serve']['max_concurrent'] = 64 | |
| frozen['inference']['vllm']['max_num_seqs'] = 64 | |
| frozen['experiment'].update(episode_concurrency_per_replica=64,total_episode_concurrency=64) | |
| template = deepcopy(frozen['evaluation']['source'][0]) | |
| sources, manifest, commits = [], {}, [] | |
| for index, pin_name in enumerate(('screening-selected100.json', 'screening-round2-selected100.json')): | |
| pin = json.loads((ROOT/'calibration'/pin_name).read_text()) | |
| available = json.loads((ROOT/'calibration'/pin.get('manifest_filename', 'screening-all116-manifest.json')).read_text()) | |
| selected = [name for name in names if name in available] | |
| source = deepcopy(template) | |
| source['name'] = 'validation-round'+str(index+1) | |
| source['env']['taskset'] = deepcopy(pin['taskset']) | |
| source['env']['taskset'].update(dataset=pin['combined_dataset'], tasks=selected) | |
| source['select'] = {'limit':len(selected), 'shuffle':False} | |
| source['env']['interception']['tunnel']['port'] = 8001+index | |
| assert source['env']['taskset']['repo'].endswith('@'+pin['commit']) | |
| sources.append(source) | |
| manifest.update({name:available[name] for name in selected}) | |
| commits.append(pin['commit']) | |
| assert sum(len(s['env']['taskset']['tasks']) for s in sources) == len(manifest) == 11 | |
| frozen['evaluation']['source'] = sources | |
| frozen['evaluation']['select'] = {'limit':11, 'shuffle':False} | |
| frozen['experiment'].update(task_count=11, total_attempts=88, replicas=1, | |
| attempts_per_task=8, attempts_per_task_per_replica=8, inference_seeds=[4100], | |
| task_git_commits=commits, task_git_commit=None, split='validation', trainer_gpus=0) | |
| frozen['task_manifest'] = manifest | |
| frozen['split_note'] = plan['split_review_status'] | |
| assert frozen['evaluation']['group_size'] == 8 and frozen['evaluation']['concurrency']['max_inflight'] == 64 | |
| return frozen | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=8100,retries=0, | |
| secrets=[modal.Secret.from_name('workspace-official-harbor-controller'), | |
| modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def validation_controller(run_id: str, frozen: dict, comparison: dict | None = None, | |
| submit_only: bool = False): | |
| """Native CPU loader and dry-run gate, then one existing inference-only worker.""" | |
| import asyncio,json,sys,time | |
| from copy import deepcopy | |
| from prime_rl.configs.eval import EvalConfig | |
| from prime_rl.configs.inference import InferenceConfig | |
| sys.path.insert(0,'/workspace-smoke') | |
| directory=Path('/outputs/prime')/(run_id+'-controller') | |
| recovery_comparison = comparison is not None and frozen['experiment'].get('purpose') == 'length_recovery_comparison' | |
| assert not submit_only or comparison is None or recovery_comparison | |
| directory.mkdir(parents=True,exist_ok=submit_only) | |
| if submit_only and (directory/'receipt.json').exists(): | |
| existing = json.loads((directory/'receipt.json').read_text()) | |
| if existing.get('gpu_call_id'): | |
| return existing # A restarted CPU submitter must reuse its saved worker. | |
| arms = [frozen] if comparison is None else [frozen, comparison] | |
| if comparison is not None: | |
| left, right = deepcopy(frozen), deepcopy(comparison) | |
| if recovery_comparison: | |
| _validate_recovery_arms(left, right) | |
| else: | |
| assert left['experiment']['purpose'] == right['experiment']['purpose'] == 'output_limit_comparison' | |
| assert [left['evaluation']['sampling']['max_tokens'], right['evaluation']['sampling']['max_tokens']] == [8192, 16384] | |
| right['evaluation']['sampling']['max_tokens'] = 8192 | |
| assert left == right, 'Only the output token limit may differ between arms' | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'cpu_preflight', | |
| 'planned_attempts':sum(arm['experiment']['total_attempts'] for arm in arms), | |
| 'trainer_gpus':0,'inference_gpus':1,'started_unix':time.time()} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| for arm in arms: | |
| _validate_evaluation_budget(arm) | |
| EvalConfig.model_validate(deepcopy(arm['evaluation'])) | |
| if recovery_comparison: | |
| from bash_recovery import verify_runtime | |
| receipt['recovery_runtime'] = verify_runtime(frozen['runtime_sha256']['bash_recovery.py']) | |
| receipt['opt_in_recovery_bundle_verified'] = True | |
| serving=InferenceConfig.model_validate(deepcopy(frozen['inference'])) | |
| assert serving.router is None and serving.to_namespace().max_num_seqs==64 | |
| load_evaluation_tasks(frozen['evaluation']['source'], frozen['task_manifest']) | |
| await task_cache.commit.aio() | |
| for arm in arms: | |
| suffix = ('-recovery'+arm['evaluation']['source'][0]['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY'] | |
| if recovery_comparison else '' if comparison is None else '-'+str(arm['evaluation']['sampling']['max_tokens'])) | |
| config=deepcopy(arm['evaluation']);config['output_dir']=str(directory/('dry-run'+suffix)) | |
| path=directory/('eval'+suffix+'.json');path.write_text(json.dumps(config,indent=2)+'\n') | |
| with (directory/('dry-run'+suffix+'.log')).open('w') as log: | |
| process=await asyncio.create_subprocess_exec('/app/.venv/bin/eval','@',str(path),'--dry-run', | |
| cwd='/app',stdout=log,stderr=log,start_new_session=True) | |
| try:code=await asyncio.wait_for(process.wait(),120) | |
| except asyncio.TimeoutError: | |
| from training_lifecycle import stop_launcher | |
| await stop_launcher(process);raise | |
| assert code==0,'Native eval CPU dry-run failed' | |
| receipt.update(native_git_manifests_verified=True,native_eval_dry_run_passed=True,status='cpu_preflight_passed') | |
| (directory/'frozen-config.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| await save() | |
| if recovery_comparison: | |
| call = await recovery_comparison_worker.spawn.aio(run_id, frozen, comparison) | |
| receipt.update(status='gpu_submitted', gpu_call_id=call.object_id, | |
| arm_run_ids=[run_id+'-off', run_id+'-on'], | |
| comparison_output='/prime/'+run_id+'-comparison/receipt.json') | |
| await save() | |
| return receipt | |
| receipt['arms'] = [] | |
| for arm in arms: | |
| limit = arm['evaluation']['sampling']['max_tokens'] | |
| arm_id = run_id if comparison is None else run_id+'-limit'+str(limit) | |
| worker = evaluate.with_options(gpu='H100!') if comparison is not None or submit_only else evaluate | |
| call=await worker.spawn.aio(arm_id,calibration=True,replica=0,validation=arm) | |
| item = {'run_id':arm_id, 'output_token_limit':limit, 'gpu_call_id':call.object_id, | |
| 'status':'gpu_submitted', 'submitted_unix':time.time()} | |
| receipt['arms'].append(item) | |
| receipt.update(status='gpu_submitted',gpu_call_id=call.object_id);await save() | |
| if submit_only: | |
| return receipt # The detached GPU owns execution; no long-lived CPU waiter. | |
| result=await call.get.aio() | |
| assert result['authentication_verified'] and result['generation_verified'] | |
| assert result['eval_exit_code'] == 0 and result['processes_stopped'] | |
| item.update(status=result['status'], result=result, ended_unix=time.time()) | |
| receipt.update(status=result['status'],result=result);await save() | |
| except BaseException as error: | |
| receipt.update(status='failed',error_type=type(error).__name__,error=str(error));raise | |
| finally: | |
| receipt['ended_unix']=time.time();await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def validate11(run_id: str, launch: bool=False): | |
| import json,subprocess | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| frozen=validation11_config() | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| frozen_path=ROOT/'calibration'/(run_id+'-frozen.json') | |
| if not launch: | |
| print(json.dumps(frozen,indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next for this project' | |
| assert not path.exists() and not frozen_path.exists(),'Use the existing receipt; never duplicate-launch' | |
| frozen_path.write_text(json.dumps(frozen,indent=2)+'\n') | |
| call=validation_controller.spawn(run_id,frozen) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'controller_submitted','planned_attempts':88,'task_count':11,'attempts_per_task':8, | |
| 'inference_gpus':1,'trainer_gpus':0,'concurrency':64,'model':frozen['experiment']['model'], | |
| 'model_revision':frozen['experiment']['model_revision'], | |
| 'task_git_commits':frozen['experiment']['task_git_commits'], | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| @app.function(image=evaluation_image,cpu=1,memory=4096,timeout=600,retries=0, | |
| secrets=[modal.Secret.from_name(name) for name in | |
| ('workspace-official-harbor-controller','workspace-task-registry-readonly','wandb')], | |
| volumes={'/outputs':outputs,'/root/.cache/huggingface':cache,'/root/.cache/harbor':task_cache}) | |
| def account_cpu_check(run_id: str, frozen: dict): | |
| """Validate recreated account resources without a model, trainer or GPU.""" | |
| import json,os,subprocess,sys,time | |
| from copy import deepcopy | |
| import wandb | |
| from prime_rl.configs.eval import EvalConfig | |
| from prime_rl.configs.inference import InferenceConfig | |
| sys.path.insert(0,'/workspace-smoke') | |
| from task_source import git_credentials,task_manifest | |
| from verifiers.v1.tasksets.harbor import HarborConfig,HarborTaskset | |
| directory=Path('/outputs/prime')/run_id;directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'workspace':ACTIVE_WORKSPACE,'app_id':app.app_id, | |
| 'status':'checking','gpu_calls':0,'model_calls':0,'started_unix':time.time()} | |
| box=None | |
| try: | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE | |
| required=('TASK_REGISTRY_SSH_KEY','TASK_REGISTRY_KNOWN_HOSTS','WANDB_API_KEY','MODAL_TOKEN_ID','MODAL_TOKEN_SECRET') | |
| assert all(os.environ.get(key) for key in required) | |
| controller_client=modal.Client.from_credentials(os.environ['MODAL_TOKEN_ID'],os.environ['MODAL_TOKEN_SECRET']) | |
| assert modal.Workspace.from_context(client=controller_client).hydrate().name==ACTIVE_WORKSPACE | |
| receipt['controller_credentials_target_verified']=True | |
| api=wandb.Api(timeout=20);viewer=api.viewer | |
| username=viewer.get('username') if isinstance(viewer,dict) else viewer.username | |
| assert username=='susindrar' and api.project('workspace-agent-rl',entity='susindrar-university-of-houston') is not None | |
| receipt['wandb_authentication_verified']=True | |
| with git_credentials(): | |
| tasks=[task for source in frozen['evaluation']['source'] for task in | |
| HarborTaskset(HarborConfig.model_validate(deepcopy(source['env']['taskset']))).load()] | |
| assert task_manifest(tasks)==frozen['task_manifest'] and len(tasks)==11 | |
| assert all(task.data.upload_environment for task in tasks) | |
| receipt['native_git_manifests_verified']=11 | |
| EvalConfig.model_validate(deepcopy(frozen['evaluation'])) | |
| assert InferenceConfig.model_validate(deepcopy(frozen['inference'])).router is None | |
| cfg=deepcopy(frozen['evaluation']);cfg['output_dir']=str(directory/'dry-run') | |
| path=directory/'eval.json';path.write_text(json.dumps(cfg,indent=2)+'\n') | |
| with (directory/'dry-run.log').open('w') as log: | |
| check=subprocess.run(['/app/.venv/bin/eval','@',str(path),'--dry-run'],cwd='/app', | |
| stdout=log,stderr=log,timeout=120) | |
| assert check.returncode==0,'Native eval dry-run failed' | |
| receipt['native_eval_dry_run_passed']=True | |
| marker=json.dumps({'workspace':ACTIVE_WORKSPACE,'run_id':run_id}) | |
| for root in ('/outputs','/root/.cache/huggingface','/root/.cache/harbor'): | |
| probe=Path(root)/'.account-setup-check.json';probe.write_text(marker) | |
| assert probe.read_text()==marker | |
| cache.commit();task_cache.commit();outputs.commit() | |
| receipt['three_volumes_read_write_verified']=True | |
| box=modal.Sandbox.create('python','-c','print("ACCOUNT_CPU_OK")', | |
| image=modal.Image.debian_slim(python_version='3.12'),app=app, | |
| cpu=0.125,memory=128,timeout=60) | |
| receipt['sandbox_id']=box.object_id | |
| result=box.stdout.read();box.wait() | |
| assert box.returncode==0 and result.strip()=='ACCOUNT_CPU_OK' | |
| receipt.update(cpu_sandbox_verified=True,status='passed') | |
| except BaseException as error: | |
| receipt.update(status='failed',error_type=type(error).__name__) | |
| raise | |
| finally: | |
| if box is not None: | |
| box.terminate();receipt['sandbox_terminated']=True | |
| receipt['ended_unix']=time.time() | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n');outputs.commit() | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| return receipt | |
| @app.local_entrypoint() | |
| def prepare_account(run_id: str): | |
| """Submit the CPU-only account check; GPU functions are never called.""" | |
| import json | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE,'Use --profile rl-next' | |
| receipt_path=ROOT/'.state'/('launch-'+run_id+'.json') | |
| assert not receipt_path.exists(),'Account check already submitted' | |
| frozen=validation11_config() | |
| call=account_cpu_check.spawn(run_id,frozen) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'call_id':call.object_id,'status':'cpu_check_submitted', | |
| 'profile':ACTIVE_PROFILE,'workspace':ACTIVE_WORKSPACE,'gpu_calls':0, | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| receipt_path.write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt,indent=2),flush=True) | |
| OUTPUT_LIMIT_TASKS = ('task_03964_fc89b9', 'task_02367_865b08', | |
| 'task_04253_b72253', 'task_04928_0f691a') | |
| def _validate_evaluation_budget(frozen: dict): | |
| experiment = frozen['experiment'] | |
| names = [name for source in frozen['evaluation']['source'] | |
| for name in source['env']['taskset']['tasks']] | |
| assert len(names) == len(set(names)) == len(frozen['task_manifest']) == experiment['task_count'] | |
| assert set(names) == set(frozen['task_manifest']) | |
| assert frozen['evaluation']['group_size'] == 8 | |
| assert experiment['total_attempts'] == len(names) * 8 | |
| if experiment.get('purpose') == 'output_limit_comparison': | |
| assert set(names) == set(OUTPUT_LIMIT_TASKS) and experiment['total_attempts'] == 32 | |
| assert frozen['evaluation']['sampling']['max_tokens'] in (8192, 16384) | |
| elif experiment.get('purpose') in ('temperature_probe', 'length_recovery_comparison'): | |
| assert set(names) == set(OUTPUT_LIMIT_TASKS[:2]) and experiment['total_attempts'] == 16 | |
| assert frozen['evaluation']['sampling']['max_tokens'] == 8192 | |
| assert frozen['evaluation']['sampling']['temperature'] == 0.6 | |
| if experiment['purpose'] == 'length_recovery_comparison': | |
| assert all(source['env']['agent']['harness']['env'].get('VF_BASH_LENGTH_RECOVERY') in ('0', '1') | |
| for source in frozen['evaluation']['source']) | |
| elif experiment.get('purpose') == 'final_heldout': | |
| assert experiment['task_count'] in (11, 12) | |
| assert frozen['evaluation']['sampling']['max_tokens'] == 8192 | |
| assert frozen['evaluation']['sampling']['temperature'] == 0.6 | |
| assert all(source['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY']=='1' | |
| for source in frozen['evaluation']['source']) | |
| else: | |
| assert experiment['task_count'] == 11 and experiment['total_attempts'] == 88 | |
| def output_limit_configs(): | |
| """Subset the actual previous evaluation; alter only the per-turn output cap.""" | |
| import json | |
| from copy import deepcopy | |
| baseline = json.loads((ROOT/'calibration/validation11-c64-20261029-01-frozen.json').read_text()) | |
| selected = set(OUTPUT_LIMIT_TASKS) | |
| baseline['experiment'].update(profile=ACTIVE_PROFILE, workspace=ACTIVE_WORKSPACE, | |
| task_count=4, total_attempts=32, purpose='output_limit_comparison', | |
| gpu_per_replica='H100!', split='diagnostic_on_previously_evaluated_validation_tasks') | |
| baseline['diagnostic_note'] = ('Failure-enriched selection, not an unbiased evaluation or training task reassignment. ' | |
| 'Both arms rerun all 32 attempts fresh; no old attempts merged. ' | |
| 'Concurrency cap remains 64, with at most 32 attempts available per arm.') | |
| baseline['evaluation']['select'] = {'limit':4, 'shuffle':False} | |
| for source in baseline['evaluation']['source']: | |
| names = [name for name in source['env']['taskset']['tasks'] if name in selected] | |
| assert names | |
| source['env']['taskset']['tasks'] = names | |
| source['select'] = {'limit':len(names), 'shuffle':False} | |
| baseline['task_manifest'] = {name:baseline['task_manifest'][name] for name in OUTPUT_LIMIT_TASKS} | |
| candidate = deepcopy(baseline) | |
| candidate['evaluation']['sampling']['max_tokens'] = 16384 | |
| for arm in (baseline, candidate): | |
| _validate_evaluation_budget(arm) | |
| return baseline, candidate | |
| @app.local_entrypoint() | |
| def compare_output_limits(run_id: str, launch: bool = False): | |
| """Exactly two sequential inference-only arms, using the existing evaluator.""" | |
| import json | |
| assert Path(run_id).name == run_id and run_id not in ('', '.', '..') | |
| baseline, candidate = output_limit_configs() | |
| if not launch: | |
| print(json.dumps({'arms':[baseline,candidate]},indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next' | |
| path = ROOT/'calibration'/('launch-'+run_id+'.json') | |
| assert not path.exists(), 'Use the submitted controller; never duplicate-launch' | |
| frozen_path = ROOT/'calibration'/(run_id+'-frozen.json') | |
| frozen_path.write_text(json.dumps({'arms':[baseline,candidate]},indent=2)+'\n') | |
| call = validation_controller.with_options(timeout=14400).spawn(run_id,baseline,comparison=candidate) | |
| receipt = {'run_id':run_id, 'app_id':app.app_id, 'controller_call_id':call.object_id, | |
| 'status':'cpu_preflight_submitted', 'profile':ACTIVE_PROFILE, 'workspace':ACTIVE_WORKSPACE, | |
| 'planned_attempts':64, 'task_count':4, 'attempts_per_task_per_arm':8, | |
| 'output_token_limits':[8192,16384], 'concurrency_cap':64, 'inference_gpus_at_once':1, | |
| 'gpu_type':'H100!', 'trainer_gpus':0, 'tasks':list(OUTPUT_LIMIT_TASKS), | |
| 'output':'workspace-agent-training:/prime/'+run_id+'-controller', | |
| 'arm_outputs':['workspace-agent-training:/prime/'+run_id+'-limit'+str(limit)+'/replica-0' | |
| for limit in (8192,16384)]} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| def temperature_probe_config(): | |
| frozen, _ = output_limit_configs() | |
| selected = set(OUTPUT_LIMIT_TASKS[:2]) | |
| frozen['experiment'].update(task_count=2, total_attempts=16, purpose='temperature_probe', | |
| reference_baseline_run='output-limit4-20261030-01-limit8192') | |
| frozen['diagnostic_note'] = ('Two previously cutoff-affected tasks, eight fresh attempts each. ' | |
| 'Keep output8192/thinkingtrue; change temperature1.0 to0.6. ' | |
| 'Failure-enriched diagnostic; at most16 active attempts under the unchanged64 cap. ' | |
| 'Historical baseline used a larger4-task cohort, so time comparisons are descriptive.') | |
| frozen['evaluation']['sampling']['temperature'] = 0.6 | |
| frozen['evaluation']['select']['limit'] = 2 | |
| sources = [] | |
| for source in frozen['evaluation']['source']: | |
| names = [name for name in source['env']['taskset']['tasks'] if name in selected] | |
| if not names: | |
| continue | |
| source['env']['taskset']['tasks'] = names | |
| source['select']['limit'] = len(names) | |
| source['env']['interception']['tunnel']['port'] = 8001+len(sources) | |
| sources.append(source) | |
| frozen['evaluation']['source'] = sources | |
| frozen['task_manifest'] = {name:frozen['task_manifest'][name] for name in OUTPUT_LIMIT_TASKS[:2]} | |
| _validate_evaluation_budget(frozen) | |
| return frozen | |
| @app.local_entrypoint() | |
| def probe_temperature(run_id: str, launch: bool = False): | |
| import json | |
| assert Path(run_id).name == run_id and run_id not in ('', '.', '..') | |
| frozen = temperature_probe_config() | |
| if not launch: | |
| print(json.dumps(frozen,indent=2));return | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next' | |
| path = ROOT/'calibration'/('launch-'+run_id+'.json') | |
| assert not path.exists(), 'Use the existing submitted worker; never duplicate-launch' | |
| (ROOT/'calibration'/(run_id+'-frozen.json')).write_text(json.dumps(frozen,indent=2)+'\n') | |
| call = validation_controller.spawn(run_id,frozen,submit_only=True) | |
| receipt = {'run_id':run_id, 'app_id':app.app_id, 'controller_call_id':call.object_id, | |
| 'status':'cpu_preflight_submitted', 'profile':ACTIVE_PROFILE, 'workspace':ACTIVE_WORKSPACE, | |
| 'planned_attempts':16, 'tasks':list(OUTPUT_LIMIT_TASKS[:2]), 'attempts_per_task':8, | |
| 'temperature':0.6, 'max_tokens':8192, 'thinking':True, 'concurrency_cap':64, | |
| 'inference_gpus':1, 'gpu_type':'H100!', 'trainer_gpus':0, | |
| 'output':'workspace-agent-training:/prime/'+run_id, | |
| 'reference_baseline_run':frozen['experiment']['reference_baseline_run']} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| def _validate_recovery_arms(baseline: dict, candidate: dict): | |
| from copy import deepcopy | |
| left, right = deepcopy(baseline), deepcopy(candidate) | |
| assert left['experiment']['purpose'] == right['experiment']['purpose'] == 'length_recovery_comparison' | |
| for arm, setting in ((left, '0'), (right, '1')): | |
| _validate_evaluation_budget(arm) | |
| for source in arm['evaluation']['source']: | |
| assert source['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY'] == setting | |
| source['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY'] = '0' | |
| assert left == right, 'Only the per-episode recovery setting may differ' | |
| def recovery_comparison_configs(): | |
| import hashlib | |
| from copy import deepcopy | |
| baseline = temperature_probe_config() | |
| baseline['experiment'].update(purpose='length_recovery_comparison', | |
| reference_baseline_run='temperature2-t06-8k-20261030-01') | |
| baseline['diagnostic_note'] = ('Two cutoff-affected tasks x8 fresh attempts per arm; ' | |
| '32 total, sequential arms on one H100. Only opt-in no-tool length recovery differs. ' | |
| 'One corrective request per episode; failed raw generation remains in native traces ' | |
| 'but is omitted from the next model prompt. Thinking and all other budgets unchanged. ' | |
| 'Failure-enriched diagnostic, not a blind evaluation; later arm may benefit from warm caches.') | |
| baseline['runtime_sha256']['bash_recovery.py'] = hashlib.sha256((ROOT/'bash_recovery.py').read_bytes()).hexdigest() | |
| for source in baseline['evaluation']['source']: | |
| source['env']['agent']['harness'].setdefault('env', {})['VF_BASH_LENGTH_RECOVERY'] = '0' | |
| candidate = deepcopy(baseline) | |
| for source in candidate['evaluation']['source']: | |
| source['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY'] = '1' | |
| _validate_recovery_arms(baseline, candidate) | |
| return baseline, candidate | |
| @app.function(image=evaluation_image, gpu='H100!', cpu=8, memory=65536, timeout=14400, | |
| retries=0, scaledown_window=2, max_containers=1, | |
| secrets=[modal.Secret.from_name('workspace-official-harbor-controller'), | |
| modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs, '/root/.cache/huggingface':cache, '/root/.cache/harbor':task_cache}) | |
| async def recovery_comparison_worker(run_id: str, baseline: dict, candidate: dict): | |
| """Reuse the existing native evaluator twice on the same allocated GPU.""" | |
| import asyncio, json, time | |
| _validate_recovery_arms(baseline, candidate) | |
| directory = Path('/outputs/prime')/(run_id+'-comparison') | |
| directory.mkdir(parents=True, exist_ok=False) | |
| receipt = {'run_id':run_id, 'app_id':app.app_id, 'status':'starting', | |
| 'started_unix':time.time(), 'planned_attempts':32, 'inference_gpus':1, 'trainer_gpus':0, 'arms':[]} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(), 90) | |
| try: | |
| for label, frozen in (('off', baseline), ('on', candidate)): | |
| receipt['status'] = 'running_'+label | |
| await save() | |
| result = await evaluate.local(run_id+'-'+label, calibration=True, replica=0, validation=frozen) | |
| receipt['arms'].append({'arm':label, 'result':result}) | |
| await save() | |
| assert result['authentication_verified'] and result['generation_verified'] | |
| assert result['eval_exit_code'] == 0 and result['processes_stopped'] | |
| receipt['status'] = 'both_eval_processes_completed_results_pending_review' | |
| except BaseException as error: | |
| receipt.update(status='failed', error_type=type(error).__name__, error=str(error)) | |
| raise | |
| finally: | |
| receipt['ended_unix'] = time.time() | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def compare_recovery(run_id: str, launch: bool = False): | |
| import json | |
| baseline, candidate = recovery_comparison_configs() | |
| if not launch: | |
| print(json.dumps({'arms':[baseline,candidate]},indent=2));return | |
| assert Path(run_id).name == run_id and run_id not in ('', '.', '..') | |
| assert modal.Workspace.from_context().hydrate().name == ACTIVE_WORKSPACE, 'Use --profile rl-next' | |
| path = ROOT/'calibration'/('launch-'+run_id+'.json') | |
| frozen_path = ROOT/'calibration'/(run_id+'-frozen.json') | |
| assert not path.exists() and not frozen_path.exists(), 'Use existing submitted call; never duplicate-launch' | |
| frozen_path.write_text(json.dumps({'arms':[baseline,candidate]},indent=2)+'\n') | |
| call = validation_controller.spawn(run_id, baseline, comparison=candidate, submit_only=True) | |
| receipt = {'run_id':run_id, 'app_id':app.app_id, 'controller_call_id':call.object_id, | |
| 'status':'cpu_preflight_submitted', 'profile':ACTIVE_PROFILE, 'workspace':ACTIVE_WORKSPACE, | |
| 'planned_attempts':32, 'tasks':list(OUTPUT_LIMIT_TASKS[:2]), 'attempts_per_task_per_arm':8, | |
| 'temperature':0.6, 'max_tokens':8192, 'thinking':True, 'concurrency_cap':64, | |
| 'recovery_budget_per_episode':[0,1], 'inference_gpus':1, 'gpu_type':'H100!', 'trainer_gpus':0, | |
| 'output':'workspace-agent-training:/prime/'+run_id+'-comparison', | |
| 'arm_outputs':['workspace-agent-training:/prime/'+run_id+'-'+label+'/replica-0' for label in ('off','on')]} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt,indent=2),flush=True) | |
| def tiny_training_config(): | |
| import hashlib,json,tomllib | |
| from copy import deepcopy | |
| task = 'task_00376_dc3706' | |
| assert task in json.loads((ROOT/'plans/training103-plan.json').read_text())['split']['train'] | |
| source = deepcopy(json.loads((ROOT/'calibration/temperature2-t06-8k-20261030-01-frozen.json').read_text())['evaluation']['source'][0]) | |
| source['name'] = 'tiny-training' | |
| source['env']['taskset']['tasks'] = [task] | |
| source['select'] = {'limit':1, 'shuffle':False} | |
| source['serve']['max_concurrent'] = 8 | |
| source['env']['agent']['harness']['env'] = {'VF_BASH_LENGTH_RECOVERY':'1'} | |
| config = tomllib.loads((ROOT/'train.toml').read_text()) | |
| config.update(max_steps=1, output_dir='/outputs/prime/TINY', dashboard=False, run={'name':'training'}) | |
| config['ckpt'] = {'interval':1} | |
| orch = config['orchestrator'] | |
| orch.update(batch_size=8, max_off_policy_steps=0, eval=None, | |
| concurrency={'initial_inflight':8,'min_inflight':8,'max_inflight':8}) | |
| orch['train'].update(group_size=8, source=[source]) | |
| orch['train']['sampling']['temperature'] = 0.6 | |
| config['inference'].update(router=None) | |
| config['inference']['vllm']['max_num_seqs'] = 64 | |
| manifest = json.loads((ROOT/'calibration/screening-round2-manifest.json').read_text()) | |
| result = {'training':config, 'task_manifest':{task:manifest[task]}, | |
| 'recovery_sha256':hashlib.sha256((ROOT/'bash_recovery.py').read_bytes()).hexdigest(), | |
| 'purpose':'one-update-small-batch-smoke', 'profile':ACTIVE_PROFILE, 'workspace':ACTIVE_WORKSPACE} | |
| validate_tiny_training(result) | |
| return result | |
| def validate_tiny_training(frozen): | |
| from copy import deepcopy | |
| from prime_rl.configs.rl import RLConfig | |
| config = deepcopy(frozen['training']) | |
| parsed = RLConfig.model_validate(config) | |
| assert parsed.max_steps == 1 and parsed.orchestrator.batch_size == 8 | |
| assert parsed.orchestrator.train.group_size == 8 and parsed.orchestrator.eval is None | |
| assert parsed.orchestrator.concurrency.max_inflight == 8 | |
| assert parsed.orchestrator.max_off_policy_steps == 0 | |
| assert parsed.inference.vllm.max_num_seqs == 64 and parsed.inference.router is None | |
| assert parsed.deployment.gpus_per_node == 2 | |
| assert parsed.orchestrator.train.sampling.temperature == 0.6 | |
| assert parsed.orchestrator.train.sampling.max_completion_tokens == 8192 | |
| sources = frozen['training']['orchestrator']['train']['source'] | |
| assert len(sources)==1 and sources[0]['env']['taskset']['tasks'] == ['task_00376_dc3706'] | |
| assert sources[0]['env']['agent']['harness']['env'] == {'VF_BASH_LENGTH_RECOVERY':'1'} | |
| assert config['ckpt']['interval'] == 1 | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=600,retries=0, | |
| secrets=[modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def tiny_training_controller(run_id: str, frozen: dict): | |
| import asyncio,json,os,sys | |
| from copy import deepcopy | |
| sys.path.insert(0,'/workspace-smoke') | |
| from bash_recovery import verify_runtime | |
| validate_tiny_training(frozen) | |
| directory = Path('/outputs/prime')/(run_id+'-preflight') | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt = {'run_id':run_id,'app_id':app.app_id,'status':'cpu_preflight','trainer_gpus':1,'inference_gpus':1} | |
| try: | |
| receipt['recovery_runtime'] = verify_runtime(frozen['recovery_sha256']) | |
| tasks = load_evaluation_tasks(frozen['training']['orchestrator']['train']['source'],frozen['task_manifest']) | |
| assert len(tasks)==1 | |
| await task_cache.commit.aio() | |
| config = deepcopy(frozen['training']);config['output_dir']=str(directory/'dry-run') | |
| path=directory/'training.json';path.write_text(json.dumps(config,indent=2)+'\n') | |
| with (directory/'dry-run.log').open('w') as log: | |
| process=await asyncio.create_subprocess_exec('/usr/bin/timeout','180s','/app/.venv/bin/rl','@',str(path),'--dry-run', | |
| cwd='/app',env={**os.environ,'WANDB_MODE':'disabled','VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT]},stdout=log,stderr=log) | |
| code=await asyncio.wait_for(process.wait(),195) | |
| assert code==0,'Native RL CPU dry-run failed; GPU not submitted' | |
| receipt.update(native_cpu_dry_run_passed=True,native_task_manifest_verified=True) | |
| (directory/'frozen.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n');await outputs.commit.aio() | |
| call=await train.with_options(timeout=2400,retries=0).spawn.aio(run_id,max_steps=1,rollout_concurrency=8,tiny=frozen) | |
| receipt.update(status='training_submitted',gpu_call_id=call.object_id) | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n');await outputs.commit.aio() | |
| return receipt | |
| @app.local_entrypoint() | |
| def tiny_train(run_id: str, launch: bool = False): | |
| import json | |
| frozen=tiny_training_config() | |
| if not launch: | |
| print(json.dumps(frozen,indent=2));return | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE,'Use --profile rl-next' | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| frozen_path=ROOT/'calibration'/(run_id+'-frozen.json') | |
| assert not path.exists() and not frozen_path.exists(),'Never duplicate-launch' | |
| frozen_path.write_text(json.dumps(frozen,indent=2)+'\n') | |
| call=tiny_training_controller.spawn(run_id,frozen) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'controller_call_id':call.object_id, | |
| 'status':'cpu_preflight_submitted','profile':ACTIVE_PROFILE,'workspace':ACTIVE_WORKSPACE, | |
| 'trainer_gpus':1,'inference_gpus':1,'updates':1,'batch_size':8,'group_size':8, | |
| 'output':'workspace-agent-training:/prime/'+run_id} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt,indent=2),flush=True) | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=1800,retries=0, | |
| secrets=[modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/harbor':task_cache}) | |
| async def final_training_controller(run_id: str, frozen: dict): | |
| """Verify all 103 task manifests and native schemas before submitting 3 GPUs.""" | |
| import asyncio,json,os,sys | |
| from copy import deepcopy | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,verify_runtime,digest | |
| validate(frozen) | |
| directory=Path('/outputs/prime')/(run_id+'-preflight') | |
| directory.mkdir(parents=True,exist_ok=False) # Never replay an ambiguous paid submission. | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'cpu_preflight', | |
| 'frozen_sha256':digest(frozen),'gpu_submissions':0,'dry_runs':[]} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| (directory/'frozen.json').write_text(json.dumps(frozen,indent=2)+'\n') | |
| await save() | |
| receipt['runtime']=verify_runtime(frozen) | |
| sources=deepcopy(frozen['training']['orchestrator']['train']['source']) | |
| sources += [source for shard in frozen['evaluation_shards'] for source in shard['evaluation']['source']] | |
| tasks=load_evaluation_tasks(sources,frozen['task_manifest']) | |
| assert len(tasks)==103 | |
| receipt['verified_task_count']=103 | |
| await task_cache.commit.aio() | |
| checks=[('training','rl',deepcopy(frozen['training']))] | |
| for index, shard in enumerate(frozen['evaluation_shards']): | |
| for arm in ('base','final'): | |
| config=deepcopy(shard['evaluation']) | |
| if arm=='final':config['model']='workspace-final-step10' | |
| checks.append((f'eval-{index}-{arm}','eval',config)) | |
| for label,command,config in checks: | |
| config['output_dir']=str(directory/label) | |
| path=directory/(label+'.json');path.write_text(json.dumps(config,indent=2)+'\n') | |
| with (directory/(label+'.log')).open('w') as log: | |
| process=await asyncio.create_subprocess_exec('/usr/bin/timeout','--signal=TERM','--kill-after=10s','180s', | |
| '/app/.venv/bin/'+command,'@',str(path),'--dry-run',cwd='/app', | |
| env={**os.environ,'WANDB_MODE':'disabled','VLLM_[REDACTED_CREDENTIAL_ASSIGNMENT]}, | |
| stdout=log,stderr=log,start_new_session=True) | |
| try: | |
| code=await asyncio.wait_for(process.wait(),195) | |
| finally: | |
| if process.returncode is None: | |
| from training_lifecycle import stop_launcher | |
| await stop_launcher(process) | |
| assert code==0,f'Native {label} CPU dry-run failed; no GPUs submitted' | |
| receipt['dry_runs'].append(label) | |
| await save() | |
| receipt.update(status='cpu_preflight_passed',native_cpu_dry_runs_passed=True,native_task_manifests_verified=True) | |
| await save() | |
| # Persist intent before spawn. On interrupted submission, inspect Modal rather than retrying. | |
| receipt['status']='training_submission_started';await save() | |
| call=await train.with_options(gpu='H100:3',timeout=frozen['function_timeout_seconds'],retries=0).spawn.aio( | |
| run_id,max_steps=10,rollout_concurrency=128,final=frozen) | |
| receipt.update(status='training_submitted',gpu_call_id=call.object_id,gpu_submissions=1) | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| await save() | |
| return receipt | |
| @app.function(image=evaluation_image,cpu=1,memory=2048,timeout=900,retries=0, | |
| volumes={'/outputs':outputs}) | |
| async def final_evaluation_handoff(run_id: str, frozen: dict, training_call_id: str): | |
| """Short continuation: start eval only after the training FunctionCall returned.""" | |
| import asyncio,json,sys | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,digest | |
| validate(frozen) | |
| directory=Path('/outputs/prime')/(run_id+'-heldout') | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'status':'waiting_for_training_return','training_call_id':training_call_id, | |
| 'frozen_sha256':digest(frozen),'evaluation_calls':[],'planned_attempts':368} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| result=await modal.FunctionCall.from_id(training_call_id).get.aio(timeout=300) | |
| assert result['status']=='completed' and result['launcher_stopped'] and result['checkpoint_metadata_verified'] | |
| # The trainer input is finished; its configured idle scale-down is two seconds. | |
| await asyncio.sleep(10) | |
| await outputs.reload.aio() | |
| for shard in (0,1): | |
| receipt.update(status='evaluation_submission_started',submitting_shard=shard) | |
| await save() | |
| call=await final_heldout_worker.spawn.aio(run_id,frozen,shard) | |
| receipt['evaluation_calls'].append({'shard':shard,'call_id':call.object_id}) | |
| await save() | |
| receipt.update(status='heldout_submitted',trainer_function_returned=True) | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| await save() | |
| return receipt | |
| @app.function(image=evaluation_image,gpu='H100',cpu=8,memory=65536,timeout=14400,retries=0, | |
| max_containers=2,scaledown_window=2, | |
| secrets=[modal.Secret.from_name('workspace-official-harbor-controller'), | |
| modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/huggingface':cache,'/root/.cache/harbor':task_cache}) | |
| async def final_heldout_worker(run_id: str, frozen: dict, shard: int): | |
| """Matched base/final arms per shard, after trainer GPU release.""" | |
| import asyncio,json,sys,time | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,audit_evaluation,digest | |
| validate(frozen);assert shard in (0,1) | |
| selected=frozen['evaluation_shards'][shard] | |
| directory=Path('/outputs/prime')/(run_id+'-heldout')/f'shard-{shard}' | |
| directory.mkdir(parents=True,exist_ok=False) | |
| receipt={'run_id':run_id,'shard':shard,'status':'starting','frozen_sha256':digest(frozen), | |
| 'started_unix':time.time(),'planned_attempts':selected['experiment']['total_attempts']*2,'arms':[]} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| for arm in ('base','final'): | |
| receipt['status']='running_'+arm;await save() | |
| arm_run=f'{run_id}-heldout-{shard}-{arm}' | |
| result=await evaluate.local(arm_run,adapter_run=run_id if arm=='final' else '', | |
| calibration=True,replica=0,validation=selected,adapter_step=10) | |
| assert result['eval_exit_code']==0 and result['processes_stopped'] | |
| assert result['authentication_verified'] and result['generation_verified'] | |
| assert result['adapter_loaded']==(arm=='final') | |
| audit=audit_evaluation(Path('/outputs/prime')/arm_run/'replica-0',selected['task_manifest']) | |
| receipt['arms'].append({'arm':arm,'run_id':arm_run,'result':result,'audit':audit}) | |
| await save() | |
| receipt['status']='completed_and_graded' | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| receipt['ended_unix']=time.time();await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def final_train(run_id: str, launch: bool=False): | |
| """Freeze the authorized run, then detach one CPU gate; no duplicate submission.""" | |
| import json | |
| from final_training import freeze,digest | |
| frozen=freeze() | |
| if not launch: | |
| print(json.dumps(frozen,indent=2));return | |
| assert Path(run_id).name==run_id and run_id not in ('','.','..') | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE,'Use --profile rl-next' | |
| path=ROOT/'calibration'/('launch-'+run_id+'.json') | |
| frozen_path=ROOT/'calibration'/(run_id+'-frozen.json') | |
| assert not path.exists() and not frozen_path.exists(),'Never duplicate-launch; inspect existing receipts' | |
| frozen_path.write_text(json.dumps(frozen,indent=2)+'\n') | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'controller_submission_started', | |
| 'profile':ACTIVE_PROFILE,'workspace':ACTIVE_WORKSPACE,'frozen_sha256':digest(frozen), | |
| 'trainer_gpus':1,'inference_gpus':2,'updates':10,'batch_size':64,'group_size':8, | |
| 'concurrency_per_inference_gpu':64,'global_episode_concurrency':128, | |
| 'checkpoint_steps':[5,10],'post_training_eval_attempts':368, | |
| 'output':'workspace-agent-training:/prime/'+run_id, | |
| 'preflight_output':'workspace-agent-training:/prime/'+run_id+'-preflight', | |
| 'heldout_output':'workspace-agent-training:/prime/'+run_id+'-heldout'} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| call=final_training_controller.spawn(run_id,frozen) | |
| receipt.update(status='cpu_preflight_submitted',controller_call_id=call.object_id) | |
| path.write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt,indent=2),flush=True) | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=900,retries=0, | |
| volumes={'/outputs':outputs}) | |
| async def final_checkpoint_continuation(run_id: str, frozen: dict): | |
| """Revalidate saved native state on CPU, then submit the authorized eval once.""" | |
| import asyncio,hashlib,json,sys,time | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,verify_runtime,digest | |
| validate(frozen) | |
| assert run_id=='final-b64-g8-u10-20261030-01' | |
| assert digest(frozen)=='93653ca95cd33b08f054cd0ddb2e9f1d860878f09b42a4af43b3d660ede1b99b' | |
| root=Path('/outputs/prime')/run_id | |
| directory=root.with_name(run_id+'-heldout') | |
| directory.mkdir(exist_ok=False) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'call_id':modal.current_function_call_id(), | |
| 'status':'cpu_checkpoint_verification','frozen_sha256':digest(frozen), | |
| 'evaluation_calls':[],'planned_attempts':368,'training_updates':0} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| prior=json.loads((root/'receipt.json').read_text()) | |
| assert prior['exit_code']==0 and prior['launcher_stopped'] and prior['max_steps']==10 | |
| assert prior['status']=='failed' and prior['error']=="AssertionError('Native checkpoint 5 validation failed')" | |
| assert prior['frozen_sha256']==digest(frozen) | |
| assert json.loads((root/'frozen.json').read_text())==frozen | |
| assert not any((root.with_name(f'{run_id}-heldout-{s}-{arm}')).exists() for s in (0,1) for arm in ('base','final')) | |
| receipt['runtime']=verify_runtime(frozen) | |
| script=r''' | |
| import sys,json,hashlib,inspect,random | |
| from pathlib import Path | |
| import torch | |
| sys.path.insert(0,'/workspace-smoke') | |
| from training_lifecycle import verify_checkpoint | |
| import prime_rl.orchestrator.orchestrator as orch | |
| from safetensors import safe_open | |
| root=Path(sys.argv[1]) | |
| checks=[verify_checkpoint(root/'training/checkpoints'/f'step_{step}',step,nextstep) for step,nextstep in ((5,6),(10,10))] | |
| source=Path(orch.__file__).read_text() | |
| assert hashlib.sha256(source.encode()).hexdigest()=='ae72a9c7f01888f01d1aff786e70aed6d7587e0a8eb12b64b64ebd1425c7f77d' | |
| assert 'self.progress.step += 1' in source and 'self.progress.step -= 1' in source | |
| assert 'self.progress.step = self.resume_step + 1' in source | |
| for step in (5,10): | |
| saved=torch.load(root/'training/checkpoints'/f'step_{step}'/'orchestrator/progress.pt',weights_only=False,map_location='cpu') | |
| assert set(saved['train_source'])=={'rng','envs'} | |
| assert set(saved['train_source']['envs'])=={'final-train-1','final-train-2'} | |
| random.Random().setstate(saved['train_source']['rng']) | |
| a=root/'training/broadcasts/step_10' | |
| assert (a/'.finished').is_file() | |
| cfg=json.loads((a/'adapter_config.json').read_text()) | |
| assert cfg['r']==16 and cfg['lora_alpha']==32 and cfg['peft_type']=='LORA' | |
| assert cfg['base_model_name_or_path'].endswith('/c202236235762e1c871ad0ccb60c8ee5ba337b9a') | |
| with safe_open(a/'adapter_model.safetensors',framework='pt',device='cpu') as tensors: | |
| keys=list(tensors.keys());assert keys | |
| assert len(keys)==256 | |
| assert all(torch.isfinite(tensors.get_tensor(k)).all().item() for k in keys) | |
| assert hashlib.sha256((a/'adapter_model.safetensors').read_bytes()).hexdigest()=='a737d31c098ccdcc945a3d7b437ec72418e1d2aa6eca8986c69dc56f3eeb63d0' | |
| print(json.dumps({'checkpoints':checks,'adapter_sha256':hashlib.sha256((a/'adapter_model.safetensors').read_bytes()).hexdigest(),'adapter_config':cfg,'adapter_tensor_count':len(keys),'adapter_finite':True,'source_sha256':hashlib.sha256(source.encode()).hexdigest(),'full_resume_tested':False})) | |
| ''' | |
| process=await asyncio.create_subprocess_exec('/app/.venv/bin/python','-c',script,str(root), | |
| stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE) | |
| stdout,stderr=await asyncio.wait_for(process.communicate(),600) | |
| (directory/'checkpoint-verification.log').write_bytes(stderr+stdout) | |
| assert process.returncode==0,'CPU checkpoint verification failed; no evaluation submitted' | |
| verified=json.loads(stdout.decode().splitlines()[-1]) | |
| verified.update(status='checkpoint_verified',frozen_sha256=digest(frozen), | |
| original_receipt_sha256=hashlib.sha256((root/'receipt.json').read_bytes()).hexdigest()) | |
| (directory/'verification.json').write_text(json.dumps(verified,indent=2)+'\n') | |
| receipt['status']='checkpoint_verified';await save() | |
| for shard in (0,1): | |
| receipt.update(status='evaluation_submission_started',submitting_shard=shard);await save() | |
| call=await final_heldout_worker.spawn.aio(run_id,frozen,shard) | |
| receipt['evaluation_calls'].append({'shard':shard,'call_id':call.object_id});await save() | |
| receipt.update(status='heldout_submitted',ended_unix=time.time()) | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def continue_final_checkpoint(run_id: str): | |
| import json | |
| assert run_id=='final-b64-g8-u10-20261030-01' | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE | |
| path=ROOT/'calibration'/('continue-'+run_id+'.json') | |
| assert not path.exists(),'Never repeat an ambiguous continuation submission' | |
| frozen=json.loads((ROOT/'calibration'/(run_id+'-frozen.json')).read_text()) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'status':'continuation_submission_started', | |
| 'output':'workspace-agent-training:/prime/'+run_id+'-heldout'} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| call=final_checkpoint_continuation.spawn(run_id,frozen) | |
| receipt.update(status='cpu_verification_submitted',call_id=call.object_id) | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| print(json.dumps(receipt),flush=True) | |
| def _final_only_base_fingerprint(run_id): | |
| """Provenance guard; read bytes only, including native logs and traces.""" | |
| import hashlib | |
| result={} | |
| for shard in (0,1): | |
| base=Path('/outputs/prime')/f'{run_id}-heldout-{shard}-base'/'replica-0' | |
| assert base.is_dir() | |
| for path in sorted(base.rglob('*')): | |
| if path.is_file(): | |
| h=hashlib.sha256() | |
| with path.open('rb') as f: | |
| for block in iter(lambda:f.read(1<<20),b''):h.update(block) | |
| result[str(path)]=h.hexdigest() | |
| return result | |
| @app.function(image=evaluation_image,cpu=2,memory=8192,timeout=1800,retries=0, | |
| volumes={'/outputs':outputs}) | |
| async def final_only_preflight(run_id: str, frozen: dict): | |
| import asyncio,json,sys,hashlib | |
| from copy import deepcopy | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,verify_runtime,digest,audit_evaluation | |
| validate(frozen) | |
| assert run_id=='final-b64-g8-u10-20261030-01' | |
| assert digest(frozen)=='93653ca95cd33b08f054cd0ddb2e9f1d860878f09b42a4af43b3d660ede1b99b' | |
| root=Path('/outputs/prime') | |
| directory=root/(run_id+'-final-only-preflight') | |
| directory.mkdir(exist_ok=False) | |
| receipt={'run_id':run_id,'status':'cpu_preflight','app_id':app.app_id, | |
| 'call_id':modal.current_function_call_id(),'frozen_sha256':digest(frozen), | |
| 'planned_final_attempts':184,'base_attempts_to_run':0,'training_updates':0,'gpu_submissions':0,'base_audits':[],'dry_runs':[]} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| receipt['runtime']=verify_runtime(frozen) | |
| before=await asyncio.to_thread(_final_only_base_fingerprint,run_id) | |
| for shard in (0,1): | |
| assert not (root/f'{run_id}-heldout-{shard}-final').exists(),'Final output already exists; do not duplicate' | |
| base=root/f'{run_id}-heldout-{shard}-base'/'replica-0' | |
| prior=json.loads((base/'receipt.json').read_text()) | |
| assert prior['eval_exit_code']==0 and prior['processes_stopped'] | |
| assert prior['authentication_verified'] and prior['generation_verified'] and not prior['adapter_loaded'] | |
| assert json.loads((base/'frozen-config.json').read_text())==frozen['evaluation_shards'][shard] | |
| audit=await asyncio.to_thread(audit_evaluation,base,frozen['evaluation_shards'][shard]['task_manifest']) | |
| assert audit['attempts']==(88,96)[shard] and audit['passed']==(37,54)[shard] | |
| receipt['base_audits'].append(audit);await save() | |
| config=deepcopy(frozen['evaluation_shards'][shard]['evaluation']) | |
| config['model']='workspace-final-step10';config['output_dir']=str(directory/f'dry-run-{shard}') | |
| path=directory/f'final-{shard}.json';path.write_text(json.dumps(config,indent=2)+'\n') | |
| with (directory/f'final-{shard}-dry-run.log').open('w') as log: | |
| process=await asyncio.create_subprocess_exec('/usr/bin/timeout','--signal=TERM','--kill-after=10s','180s', | |
| '/app/.venv/bin/eval','@',str(path),'--dry-run',cwd='/app',stdout=log,stderr=log,start_new_session=True) | |
| await asyncio.wait_for(process.wait(),195) | |
| assert process.returncode==0,'Native final eval dry-run failed' | |
| receipt['dry_runs'].append(shard);await save() | |
| adapter=root/run_id/'training/broadcasts/step_10' | |
| verify=json.loads((root/(run_id+'-heldout')/'verification.json').read_text()) | |
| assert verify['status']=='checkpoint_verified' and verify['frozen_sha256']==digest(frozen) | |
| assert (adapter/'.finished').is_file() | |
| receipt['adapter_sha256']=hashlib.sha256((adapter/'adapter_model.safetensors').read_bytes()).hexdigest() | |
| assert receipt['adapter_sha256']==verify['adapter_sha256']=='a737d31c098ccdcc945a3d7b437ec72418e1d2aa6eca8986c69dc56f3eeb63d0' | |
| receipt['base_files_sha256']=before | |
| assert before==await asyncio.to_thread(_final_only_base_fingerprint,run_id),'Base files changed' | |
| receipt.update(status='cpu_preflight_passed',base_attempts_preserved=184,base_files_unchanged=True) | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally:await save() | |
| return receipt | |
| @app.function(image=evaluation_image,gpu='H100',cpu=8,memory=65536,timeout=14400,retries=0, | |
| max_containers=2,scaledown_window=2, | |
| secrets=[modal.Secret.from_name('workspace-official-harbor-controller'),modal.Secret.from_name('workspace-task-registry-readonly')], | |
| volumes={'/outputs':outputs,'/root/.cache/huggingface':cache,'/root/.cache/harbor':task_cache}) | |
| async def final_only_worker(run_id: str, frozen: dict, shard: int): | |
| import asyncio,json,sys,time | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,audit_evaluation,digest | |
| validate(frozen);assert shard in (0,1) | |
| directory=Path('/outputs/prime')/(run_id+'-final-only')/f'shard-{shard}' | |
| directory.mkdir(exist_ok=False) | |
| receipt={'run_id':run_id,'shard':shard,'status':'running_final','call_id':modal.current_function_call_id(), | |
| 'frozen_sha256':digest(frozen),'planned_attempts':(88,96)[shard],'base_attempts_to_run':0,'training_updates':0} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| selected=frozen['evaluation_shards'][shard] | |
| result=await evaluate.local(f'{run_id}-heldout-{shard}-final',adapter_run=run_id, | |
| calibration=True,replica=0,validation=selected,adapter_step=10) | |
| receipt['result']=result;await save() | |
| assert result['eval_exit_code']==0 and result['processes_stopped'] | |
| assert result['authentication_verified'] and result['generation_verified'] and result['adapter_loaded'] | |
| receipt['audit']=await asyncio.to_thread(audit_evaluation, | |
| Path('/outputs/prime')/f'{run_id}-heldout-{shard}-final'/'replica-0',selected['task_manifest']) | |
| receipt['status']='completed_and_graded' | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally: | |
| receipt['ended_unix']=time.time();await save() | |
| return receipt | |
| @app.function(image=evaluation_image,cpu=1,memory=2048,timeout=900,retries=0,volumes={'/outputs':outputs}) | |
| async def final_only_submit(run_id: str, frozen: dict): | |
| import asyncio,json,sys | |
| sys.path.insert(0,'/workspace-smoke') | |
| from final_training import validate,digest | |
| validate(frozen) | |
| root=Path('/outputs/prime') | |
| gate=json.loads((root/(run_id+'-final-only-preflight')/'receipt.json').read_text()) | |
| assert gate['status']=='cpu_preflight_passed' and gate['frozen_sha256']==digest(frozen) | |
| assert gate['planned_final_attempts']==184 and gate['base_attempts_preserved']==184 | |
| assert gate['base_files_sha256']==await asyncio.to_thread(_final_only_base_fingerprint,run_id) | |
| assert all(not (root/f'{run_id}-heldout-{shard}-final').exists() for shard in (0,1)) | |
| directory=root/(run_id+'-final-only');directory.mkdir(exist_ok=False) | |
| receipt={'run_id':run_id,'status':'submission_started','app_id':app.app_id, | |
| 'call_id':modal.current_function_call_id(),'planned_attempts':184,'base_attempts_to_run':0, | |
| 'training_updates':0,'frozen_sha256':digest(frozen),'evaluation_calls':[]} | |
| async def save(): | |
| (directory/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n') | |
| await asyncio.wait_for(outputs.commit.aio(),90) | |
| try: | |
| await save() | |
| for shard in (0,1): | |
| receipt.update(status='evaluation_submission_started',submitting_shard=shard);await save() | |
| call=await final_only_worker.spawn.aio(run_id,frozen,shard) | |
| receipt['evaluation_calls'].append({'shard':shard,'call_id':call.object_id});await save() | |
| receipt['status']='final_only_submitted' | |
| except BaseException as error: | |
| receipt.update(status='failed',error=repr(error));raise | |
| finally:await save() | |
| return receipt | |
| @app.local_entrypoint() | |
| def final_only(run_id: str, submit: bool=False): | |
| import json | |
| assert run_id=='final-b64-g8-u10-20261030-01' | |
| assert modal.Workspace.from_context().hydrate().name==ACTIVE_WORKSPACE | |
| stage='submit' if submit else 'preflight' | |
| path=ROOT/'calibration'/f'{run_id}-final-only-{stage}.json' | |
| assert not path.exists(),'Do not repeat ambiguous submission' | |
| frozen=json.loads((ROOT/'calibration'/(run_id+'-frozen.json')).read_text()) | |
| receipt={'run_id':run_id,'app_id':app.app_id,'stage':stage,'status':'submission_started'} | |
| path.write_text(json.dumps(receipt,indent=2)+'\n') | |
| call=(final_only_submit if submit else final_only_preflight).spawn(run_id,frozen) | |
| receipt.update(status='submitted',call_id=call.object_id) | |
| path.write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt),flush=True) | |