codemaivanngu commited on
Commit
ffe7353
·
verified ·
1 Parent(s): fa51c6b

Publish bounded Qwen3-32B six-GPU smoke 2312e1859361

Browse files
six-gpu-smoke-2312e1859361.py.txt ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run a two-step NeMo-RL spreadsheet smoke using the existing container runtime.
2
+
3
+ Writes only a fresh run directory and an explicitly declared short IPC root.
4
+ The training subprocess uses existing /opt actor venvs, offline local weights,
5
+ an inherited smoke YAML, and redacted logs. This is not a quality benchmark.
6
+ """
7
+
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import re
13
+ import signal
14
+ import socket
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ from pathlib import Path
20
+
21
+
22
+ ACTORS = (
23
+ "nemo_rl.algorithms.async_utils.AsyncTrajectoryCollector",
24
+ "nemo_rl.algorithms.async_utils.ReplayBuffer",
25
+ "nemo_rl.environments.nemo_gym.NemoGym",
26
+ "nemo_rl.models.generation.vllm.vllm_worker_async.VllmAsyncGenerationWorker",
27
+ "nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker",
28
+ )
29
+
30
+
31
+ def sha(path):
32
+ with path.open("rb") as stream:
33
+ return hashlib.file_digest(stream, "sha256").hexdigest()
34
+
35
+
36
+ def model_metadata(model):
37
+ config = json.loads((model / "config.json").read_text())
38
+ tokenizer = json.loads((model / "tokenizer_config.json").read_text())
39
+ template = tokenizer.get("chat_template", "")
40
+ if not isinstance(template, str):
41
+ raise ValueError("Review a non-string model chat template before running the smoke")
42
+ if "<function=" in template:
43
+ parser = "qwen3_coder"
44
+ elif "<tool_call>" in template and '"arguments"' in template:
45
+ parser = "hermes"
46
+ else:
47
+ raise ValueError("The model tool-call format is not covered by this smoke")
48
+ special = {value["content"]: int(key) for key, value in tokenizer.get("added_tokens_decoder", {}).items()}
49
+ eos = tokenizer.get("eos_token")
50
+ eos = eos.get("content") if isinstance(eos, dict) else eos
51
+ return {
52
+ "model_type": config.get("model_type"),
53
+ "tool_parser": parser,
54
+ "eos": special.get(eos, config.get("eos_token_id")),
55
+ "think_open": special.get("<think>"),
56
+ "think_close": special.get("</think>"),
57
+ "config_sha256": sha(model / "config.json"),
58
+ "tokenizer_config_sha256": sha(model / "tokenizer_config.json"),
59
+ }
60
+
61
+
62
+ def smoke_overrides(base, root, subset, metadata, six_gpu=False):
63
+ from omegaconf import OmegaConf
64
+
65
+ gym = OmegaConf.to_container(base.env.nemo_gym, resolve=False)
66
+ # The inherited template defines unrelated judges even when their config
67
+ # files are absent. Keep only the policy model servers used by this task.
68
+ for name, value in list(gym.items()):
69
+ if isinstance(value, dict) and any(
70
+ key in value for key in ("resources_servers", "responses_api_agents", "responses_api_models", "_copy")
71
+ ):
72
+ if name not in ("policy_model", "policy_model_reasoning_off"):
73
+ del gym[name]
74
+ gym["nemo_gym_log_dir"] = str(root / "nemo_gym")
75
+ gym["policy_model"]["responses_api_models"]["vllm_model"]["num_workers"] = 2
76
+ if "policy_model_reasoning_off" in gym:
77
+ gym["policy_model_reasoning_off"]["responses_api_models"]["vllm_model"]["num_workers"] = 1
78
+ gym["spreadsheet_agent"] = {"responses_api_agents": {"spreadsheet_agent": {"max_steps": 6}}}
79
+ overrides = {
80
+ "checkpointing": {"enabled": False, "checkpoint_dir": str(root / "ckpt")},
81
+ "grpo": {
82
+ "num_prompts_per_step": 2,
83
+ "num_generations_per_prompt": 2,
84
+ "max_num_steps": 2,
85
+ "val_at_start": False,
86
+ "val_at_end": False,
87
+ "val_period": -1,
88
+ },
89
+ "policy": {
90
+ "generation": {
91
+ "max_new_tokens": 4096,
92
+ "vllm_cfg": {
93
+ "gpu_memory_utilization": 0.65,
94
+ "http_server_serving_chat_kwargs": {"tool_parser": metadata["tool_parser"]},
95
+ },
96
+ "vllm_kwargs": {"max_num_seqs": 8, "max_num_batched_tokens": 32768},
97
+ },
98
+ "megatron_cfg": {"sequence_parallel": False, "scheduler": {"lr_warmup_iters": 1}},
99
+ },
100
+ "data": {"shuffle": False, "train": [{"data_path": str(subset)}]},
101
+ "env": {
102
+ "_override_": True,
103
+ "should_use_nemo_gym": True,
104
+ "should_log_nemo_gym_responses": True,
105
+ "should_log_hashed_nemo_gym_responses": False,
106
+ "nemo_gym": gym,
107
+ },
108
+ "logger": {
109
+ "log_dir": str(root / "logs"),
110
+ "wandb_enabled": False,
111
+ "tensorboard_enabled": True,
112
+ "mlflow_enabled": False,
113
+ "swanlab_enabled": False,
114
+ "monitor_gpus": False,
115
+ },
116
+ "token_ids": {key: metadata[key] for key in ("eos", "think_open", "think_close") if metadata[key] is not None},
117
+ }
118
+ if six_gpu:
119
+ overrides["cluster"] = {"num_nodes": 1, "gpus_per_node": 6}
120
+ overrides["data"]["max_input_seq_length"] = 4096
121
+ policy = overrides["policy"]
122
+ policy.update(
123
+ precision="bfloat16",
124
+ train_global_batch_size=4,
125
+ train_micro_batch_size=1,
126
+ logprob_batch_size=1,
127
+ logprob_chunk_size=4,
128
+ max_total_sequence_length=8192,
129
+ )
130
+ policy["megatron_cfg"].update(
131
+ tensor_model_parallel_size=4,
132
+ pipeline_model_parallel_size=1,
133
+ context_parallel_size=1,
134
+ sequence_parallel=True,
135
+ activation_checkpointing=True,
136
+ )
137
+ policy["megatron_cfg"]["optimizer"] = {"optimizer_cpu_offload": False, "optimizer_offload_fraction": 0.0}
138
+ generation = policy["generation"]
139
+ generation["colocated"] = {"enabled": False, "resources": {"gpus_per_node": 2, "num_nodes": 1}}
140
+ generation["vllm_cfg"].update(
141
+ tensor_parallel_size=2, pipeline_parallel_size=1, expert_parallel_size=1, max_model_len=8192
142
+ )
143
+ generation["vllm_kwargs"]["max_num_batched_tokens"] = 16384
144
+ return overrides
145
+
146
+
147
+ def clean_environment(root, ray_root, gym_root):
148
+ prefixes = ("CUDA_", "NVIDIA_", "NCCL_", "NRL_", "NEMO_", "NVTE_", "TORCH_", "OMP_", "MKL_")
149
+ keep = {
150
+ "PATH",
151
+ "PYTHONPATH",
152
+ "LD_LIBRARY_PATH",
153
+ "LIBRARY_PATH",
154
+ "HOME",
155
+ "USER",
156
+ "LOGNAME",
157
+ "SHELL",
158
+ "LANG",
159
+ "LC_ALL",
160
+ "TZ",
161
+ }
162
+ env = {
163
+ key: value
164
+ for key, value in os.environ.items()
165
+ if (key in keep or key.startswith(prefixes)) and not re.search(r"TOKEN|PASSWORD|SECRET|API_KEY", key)
166
+ }
167
+ paths = {
168
+ "NRL_MEGATRON_CHECKPOINT_DIR": "cache/nemo_rl",
169
+ "VLLM_CACHE_ROOT": "cache/vllm",
170
+ "HF_HOME": "cache/huggingface",
171
+ "HF_DATASETS_CACHE": "cache/huggingface/datasets",
172
+ "HUGGINGFACE_HUB_CACHE": "cache/huggingface/models",
173
+ "HF_MODULES_CACHE": "cache/hf_modules",
174
+ "TORCH_HOME": "cache/torch",
175
+ "TORCH_EXTENSIONS_DIR": "cache/torch_extensions",
176
+ "TORCHINDUCTOR_CACHE_DIR": "cache/torchinductor",
177
+ "TRITON_CACHE_DIR": "cache/triton",
178
+ "CUDA_CACHE_PATH": "cache/cuda",
179
+ "XDG_CACHE_HOME": "cache/xdg",
180
+ "UV_CACHE_DIR": "cache/uv",
181
+ }
182
+ for key, relative in paths.items():
183
+ path = root / relative
184
+ path.mkdir(parents=True, exist_ok=True)
185
+ env[key] = str(path)
186
+ # Include Ray's longest dashboard socket as well as its object store.
187
+ if len(str(ray_root / "session_9999-99-99_99-99-99_999999_9999999/sockets/dash_MetricsHead").encode()) > 107:
188
+ raise ValueError("Ray socket path is too long; select a shorter declared Ray root")
189
+ temp = ray_root / "tmp"
190
+ if len(str(temp / "99999999-9999-9999-9999-999999999999").encode()) > 107:
191
+ raise ValueError("vLLM IPC socket path is too long; select a shorter IPC root")
192
+ temp.mkdir(mode=0o700)
193
+ env["TMPDIR"] = str(temp)
194
+ env.update(
195
+ RAY_TMPDIR=str(ray_root),
196
+ PYTHONDONTWRITEBYTECODE="1",
197
+ TOKENIZERS_PARALLELISM="false",
198
+ HF_HUB_OFFLINE="1",
199
+ TRANSFORMERS_OFFLINE="1",
200
+ UV_OFFLINE="1",
201
+ PIP_NO_INDEX="1",
202
+ NRL_FORCE_REBUILD_VENVS="false",
203
+ NEMO_GYM_VENV_DIR=str(gym_root),
204
+ NO_PROXY="*",
205
+ no_proxy="*",
206
+ CUDA_DEVICE_MAX_CONNECTIONS="1",
207
+ OMP_NUM_THREADS="1",
208
+ MKL_NUM_THREADS="1",
209
+ OPENBLAS_NUM_THREADS="1",
210
+ WANDB_MODE="disabled",
211
+ NCCL_TIMEOUT="600",
212
+ RAY_DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES=str(8 * 1024**3),
213
+ )
214
+ return env
215
+
216
+
217
+ def redact(text, secrets):
218
+ for secret in secrets:
219
+ if secret:
220
+ text = text.replace(secret, "[REDACTED]")
221
+ return text
222
+
223
+
224
+ def gpu_snapshot():
225
+ result = subprocess.run(
226
+ ["nvidia-smi", "--query-gpu=index,uuid,memory.used,utilization.gpu", "--format=csv,noheader,nounits"],
227
+ capture_output=True,
228
+ text=True,
229
+ check=True,
230
+ )
231
+ return [
232
+ dict(zip(("index", "uuid", "memory_mb", "utilization"), (part.strip() for part in line.split(","))))
233
+ for line in result.stdout.splitlines()
234
+ ]
235
+
236
+
237
+ def redact_artifacts(roots, secrets):
238
+ changed = 0
239
+ for root in roots:
240
+ for path in root.rglob("*"):
241
+ if path.suffix not in {".log", ".out", ".err", ".json", ".jsonl", ".yaml"}:
242
+ continue
243
+ if (
244
+ path.is_symlink()
245
+ or not path.is_file()
246
+ or path.stat().st_nlink != 1
247
+ or path.stat().st_size > 16 * 1024**2
248
+ ):
249
+ continue
250
+ try:
251
+ text = path.read_text()
252
+ except UnicodeDecodeError:
253
+ continue
254
+ safe = redact(text, secrets)
255
+ if safe != text:
256
+ path.write_text(safe)
257
+ changed += 1
258
+ return changed
259
+
260
+
261
+ def existing_actor_root(trainer_root):
262
+ selected = os.environ.get("NEMO_RL_VENV_DIR")
263
+ candidates = [Path(selected)] if selected else [trainer_root / "venvs", Path("/opt/ray_venvs")]
264
+ for candidate in candidates:
265
+ if all((candidate / actor / "bin/python").is_file() for actor in ACTORS):
266
+ return candidate.resolve()
267
+ raise ValueError(
268
+ "Missing prebuilt actor venvs; refusing to bootstrap. Checked: " + ", ".join(map(str, candidates))
269
+ )
270
+
271
+
272
+ def main():
273
+ parser = argparse.ArgumentParser(description=__doc__)
274
+ for name in ("trainer-root", "base-config", "run-dir", "ipc-root", "private-config"):
275
+ parser.add_argument("--" + name, type=Path, required=True)
276
+ parser.add_argument("--expected-hostname", required=True)
277
+ parser.add_argument("--max-wall-seconds", type=int, default=1800)
278
+ parser.add_argument("--gpu-indices", help="Qwen3-32B six-GPU smoke profile, e.g. 0,1,2,3,4,5")
279
+ parser.add_argument("--helpers-root", type=Path, default=Path(__file__).resolve().parent)
280
+ parser.add_argument("--reuse-cache-root", type=Path, help="Existing launcher directory containing cache/")
281
+ args = parser.parse_args()
282
+ if socket.gethostname() != args.expected_hostname:
283
+ parser.error("Wrong training instance")
284
+ root, ipc_root = args.run_dir.resolve(), args.ipc_root.resolve()
285
+ ray_root = ipc_root
286
+ if root.exists() or ipc_root.exists():
287
+ parser.error("Run and IPC directories must both be fresh")
288
+ root.mkdir(mode=0o700)
289
+ ipc_root.mkdir(mode=0o700)
290
+ from nemo_rl.utils.config import load_config, register_omegaconf_resolvers
291
+ from omegaconf import OmegaConf
292
+
293
+ register_omegaconf_resolvers()
294
+ base = load_config(args.base_config)
295
+ if args.gpu_indices and Path(load_config.__code__.co_filename).resolve().parents[2] != args.trainer_root.resolve():
296
+ raise ValueError("Activation selected a different trainer checkout")
297
+ metadata = model_metadata(Path(base.policy.model_name))
298
+ six_gpu = args.gpu_indices is not None
299
+ scope = None
300
+ if six_gpu:
301
+ sys.path.insert(0, str(args.helpers_root))
302
+ from gpu_scope import inspect_selected, parse_indices
303
+
304
+ indices = parse_indices(args.gpu_indices)
305
+ if indices != list(range(6)) or int(base.cluster.num_nodes) != 1 or int(base.cluster.gpus_per_node) != 6:
306
+ raise ValueError("Require the assigned single-node GPU 0-5 layout")
307
+ if Path(base.policy.model_name).name != "Qwen3-32B" or metadata["model_type"] != "qwen3":
308
+ raise ValueError("This six-GPU profile requires the selected dense Qwen3-32B model")
309
+ if not OmegaConf.select(base, "policy.megatron_cfg.enabled") or base.policy.generation.backend != "vllm":
310
+ raise ValueError("The six-GPU profile requires the existing Megatron trainer and vLLM backend")
311
+ if (
312
+ base.get("on_policy_distillation", {}).get("enabled", False)
313
+ or base.grpo.get("adv_estimator", {}).get("name") == "opd"
314
+ ):
315
+ raise ValueError("This is an RLVR smoke, not an OPD run")
316
+ scope = inspect_selected(indices, args.expected_hostname)
317
+ capacity = subprocess.check_output(
318
+ ["nvidia-smi", "-i", args.gpu_indices, "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
319
+ text=True,
320
+ )
321
+ if len(capacity.splitlines()) != 6 or any(int(line.strip()) < 160000 for line in capacity.splitlines()):
322
+ raise ValueError("The six-GPU profile requires the assigned large-memory GPUs")
323
+ elif int(base.cluster.num_nodes) != 1 or int(base.cluster.gpus_per_node) != 2:
324
+ raise ValueError("Legacy smoke requires two GPUs; select --gpu-indices for the six-GPU profile")
325
+ actor_root = (
326
+ existing_actor_root(args.trainer_root)
327
+ if six_gpu
328
+ else Path(os.environ.get("NEMO_RL_VENV_DIR", "/opt/ray_venvs"))
329
+ )
330
+ for actor in ACTORS:
331
+ if not (actor_root / actor / "bin/python").is_file():
332
+ raise ValueError(f"Missing prebuilt actor venv; refusing to bootstrap: {actor}")
333
+ source = Path(base.data.train[0].data_path)
334
+ with source.open() as stream:
335
+ rows = [json.loads(next(stream)) for _ in range(4)]
336
+ if any(row.get("agent_ref", {}).get("name") != "spreadsheet_agent" for row in rows):
337
+ raise ValueError("Smoke rows must route to spreadsheet_agent")
338
+ subset = root / "train.jsonl"
339
+ subset.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows))
340
+ overrides = smoke_overrides(base, root, subset, metadata, six_gpu=six_gpu)
341
+ from nemo_gym import PARENT_DIR as gym_source
342
+
343
+ if six_gpu:
344
+ if Path(gym_source).resolve() != (args.trainer_root / "3rdparty/Gym-workspace/Gym").resolve():
345
+ raise ValueError("Activation selected a different Gym checkout")
346
+ from prepare_training_node import probe_venv, service_probe
347
+ import importlib.metadata as package_metadata
348
+
349
+ expected_versions = {name: package_metadata.version(name) for name in ("ray", "openai")}
350
+ cache = Path(base.env.nemo_gym.uv_venv_dir)
351
+ for relative, module in (
352
+ ("responses_api_models/vllm_model", None),
353
+ ("resources_servers/spreadsheet", "resources_servers.spreadsheet.app"),
354
+ ("responses_api_agents/spreadsheet_agent", "responses_api_agents.spreadsheet_agent.app"),
355
+ ):
356
+ result = probe_venv(cache / relative / ".venv", Path(gym_source), module)
357
+ if (
358
+ Path(result["prefix"]).resolve() != Path(result["venv_path"]).resolve()
359
+ or result["versions"] != expected_versions
360
+ ):
361
+ raise ValueError("Existing cache interpreter/version mismatch")
362
+ service_probe(args.private_config, "LibreOffice 24.2.7.2 420(Build:2)")
363
+
364
+ audit_agent = args.helpers_root / "audit_agent.py"
365
+ agent = overrides["env"]["nemo_gym"]["spreadsheet_agent"]["responses_api_agents"]["spreadsheet_agent"]
366
+ agent.update(
367
+ entrypoint=os.path.relpath(audit_agent, gym_source / "responses_api_agents/spreadsheet_agent"),
368
+ num_workers=1,
369
+ audit_path=str(root / "model_rollouts.jsonl"),
370
+ )
371
+ overrides = {"defaults": str(args.base_config.resolve()), **overrides}
372
+ config = root / "smoke.yaml"
373
+ config.write_text(OmegaConf.to_yaml(OmegaConf.create(overrides), resolve=False))
374
+ resolved = OmegaConf.to_container(load_config(config), resolve=True)
375
+ assert resolved["grpo"]["max_num_steps"] == 2
376
+ assert resolved["policy"]["train_global_batch_size"] == 4
377
+ if six_gpu:
378
+ assert resolved["policy"]["megatron_cfg"]["tensor_model_parallel_size"] == 4
379
+ assert resolved["policy"]["generation"]["vllm_cfg"]["tensor_parallel_size"] == 2
380
+ # Freeze the effective smoke config, avoiding a later reread of the
381
+ # user's YAML/defaults while this run is in flight.
382
+ config.write_text(OmegaConf.to_yaml(OmegaConf.create(resolved), resolve=True))
383
+ print(
384
+ json.dumps(
385
+ {
386
+ "event": "SIX_GPU_CONFIG_CHECKED",
387
+ "model": resolved["policy"]["model_name"],
388
+ "train_gpus": 4,
389
+ "train_tp": 4,
390
+ "train_dp": 1,
391
+ "rollout_gpus": 2,
392
+ "rollout_tp": 2,
393
+ "context": 8192,
394
+ "precision": "bfloat16",
395
+ "optimizer_cpu_offload": False,
396
+ "max_new_tokens": 4096,
397
+ "optimizer_steps": 2,
398
+ "prompts_per_step": 2,
399
+ "rollouts_per_prompt": 2,
400
+ "config": str(config),
401
+ }
402
+ ),
403
+ flush=True,
404
+ )
405
+ env = clean_environment(
406
+ args.reuse_cache_root.resolve() if args.reuse_cache_root else root,
407
+ ray_root,
408
+ Path(base.env.nemo_gym.uv_venv_dir),
409
+ )
410
+ before = scope["devices"] if scope else gpu_snapshot()
411
+ if not six_gpu and (len(before) != 2 or any(int(gpu["memory_mb"]) > 1024 for gpu in before)):
412
+ raise ValueError("The two allocated GPUs are no longer idle")
413
+ env["CUDA_VISIBLE_DEVICES"] = ",".join(scope["uuids"] if scope else [gpu["index"] for gpu in before])
414
+ env["NEMO_RL_VENV_DIR"] = str(actor_root)
415
+ private = OmegaConf.load(args.private_config).spreadsheet_resources.resources_servers.spreadsheet
416
+ secrets = [str(private.api_key), str(private.session_secret_key)]
417
+ entry = args.trainer_root / "examples/nemo_gym/run_grpo_nemo_gym.py"
418
+ driver = args.helpers_root / "smoke_driver.py"
419
+ if not driver.is_file() or not audit_agent.is_file():
420
+ raise ValueError("Pinned driver/audit helper is missing")
421
+ report = {
422
+ "status": "running",
423
+ "hostname": socket.gethostname(),
424
+ "model": metadata,
425
+ "base_config": str(args.base_config),
426
+ "base_config_sha256": sha(args.base_config),
427
+ "config": str(config),
428
+ "config_sha256": sha(config),
429
+ "data_sha256": sha(subset),
430
+ "source_data_sha256": sha(source),
431
+ "task_ids": [row["task_id"] for row in rows],
432
+ "entrypoint_sha256": sha(entry),
433
+ "driver_sha256": sha(driver),
434
+ "audit_agent_sha256": sha(audit_agent),
435
+ "gpus_before": before,
436
+ "actor_venv_root": str(actor_root),
437
+ "gpu_profile": "train_tp4_rollout_tp2" if six_gpu else "legacy_two_gpu",
438
+ "requested_optimizer_steps": 2,
439
+ "max_wall_seconds": args.max_wall_seconds,
440
+ "log": str(root / "train.log"),
441
+ "ipc_root": str(ipc_root),
442
+ }
443
+ (root / "run.json").write_text(json.dumps(report, indent=2) + "\n")
444
+ print(
445
+ json.dumps(
446
+ {
447
+ "event": "SPREADSHEET_TRAIN_SMOKE_START",
448
+ "run_dir": str(root),
449
+ "model": metadata,
450
+ "steps": 2,
451
+ "prompts_per_step": 2,
452
+ "rollouts_per_prompt": 2,
453
+ }
454
+ ),
455
+ flush=True,
456
+ )
457
+ start = time.monotonic()
458
+ command = [
459
+ sys.executable,
460
+ "-B",
461
+ str(driver),
462
+ "--entrypoint",
463
+ str(entry),
464
+ "--config",
465
+ str(config),
466
+ "--ray-root",
467
+ str(ray_root),
468
+ ]
469
+ if scope:
470
+ command.extend(
471
+ [
472
+ "--gpu-indices",
473
+ args.gpu_indices,
474
+ "--gpu-uuids",
475
+ ",".join(scope["uuids"]),
476
+ "--expected-hostname",
477
+ args.expected_hostname,
478
+ ]
479
+ )
480
+ process = subprocess.Popen(
481
+ command,
482
+ cwd=root,
483
+ env=env,
484
+ stdout=subprocess.PIPE,
485
+ stderr=subprocess.STDOUT,
486
+ stdin=subprocess.DEVNULL,
487
+ start_new_session=True,
488
+ )
489
+ report.update(driver_pid=process.pid, driver_pgid=process.pid)
490
+ (root / "run.json").write_text(json.dumps(report, indent=2) + "\n")
491
+ timed_out = threading.Event()
492
+
493
+ def stop_owned_run():
494
+ if process.poll() is None:
495
+ timed_out.set()
496
+ try:
497
+ os.killpg(process.pid, signal.SIGTERM)
498
+ except ProcessLookupError:
499
+ pass
500
+
501
+ timer = threading.Timer(args.max_wall_seconds, stop_owned_run)
502
+ timer.daemon = True
503
+ timer.start()
504
+ with (root / "train.log").open("w") as log:
505
+ for raw in iter(process.stdout.readline, b""):
506
+ line = redact(raw.decode("utf-8", errors="replace"), secrets)
507
+ log.write(line)
508
+ log.flush()
509
+ if re.search(r"Traceback|ERROR|Exception|\bstep\b|reward|training|RL INIT|local Ray", line, re.IGNORECASE):
510
+ print(line, end="", flush=True)
511
+ code = process.wait()
512
+ timer.cancel()
513
+ report.update(
514
+ status="exited" if code == 0 else "failed",
515
+ exit_code=code,
516
+ timed_out=timed_out.is_set(),
517
+ elapsed_seconds=time.monotonic() - start,
518
+ gpus_after=gpu_snapshot(),
519
+ redacted_artifacts=redact_artifacts((root, ipc_root), secrets),
520
+ base_config_unchanged=sha(args.base_config) == report["base_config_sha256"],
521
+ )
522
+ (root / "run.json").write_text(json.dumps(report, indent=2) + "\n")
523
+ print(
524
+ json.dumps(
525
+ {
526
+ "event": "SPREADSHEET_TRAIN_SMOKE_EXIT",
527
+ "exit_code": code,
528
+ "timed_out": timed_out.is_set(),
529
+ "receipt": str(root / "run.json"),
530
+ }
531
+ ),
532
+ flush=True,
533
+ )
534
+ if six_gpu:
535
+ if timed_out.is_set() and code == 0:
536
+ code = 124
537
+ if not report["base_config_unchanged"] and code == 0:
538
+ code = 1
539
+ try:
540
+ sys.path.insert(0, str(args.helpers_root))
541
+ from analyze_training_smoke import analyze
542
+
543
+ analysis = analyze(root)
544
+ (root / "analysis.json").write_text(json.dumps(analysis, indent=2) + "\n")
545
+ summary = {
546
+ key: analysis[key]
547
+ for key in (
548
+ "logged_steps",
549
+ "trajectory_count",
550
+ "model_tool_calls",
551
+ "reward_counts",
552
+ "advantages",
553
+ "environment_error_count",
554
+ "problems",
555
+ )
556
+ }
557
+ print(json.dumps({"event": "SIX_GPU_SMOKE_ANALYSIS", **summary}), flush=True)
558
+ if code == 0 and analysis["problems"]:
559
+ code = 1
560
+ except Exception as error:
561
+ print(json.dumps({"event": "SIX_GPU_ANALYSIS_FAILED", "error_type": type(error).__name__}), flush=True)
562
+ if code == 0:
563
+ code = 1
564
+ raise SystemExit(code if code >= 0 else 128 - code)
565
+
566
+
567
+ if __name__ == "__main__":
568
+ main()
six-gpu-smoke-2312e1859361.py.txt.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "source_commit": "2312e1859361d037a689afbe3d19f99eedf6a0ab",
3
+ "file": "six-gpu-smoke-2312e1859361.py.txt",
4
+ "sha256": "58dcdd57ffdafe13ecb8d513c5dc31b42cb3de0ce3b19e5a58ab3c43f6bdbb7d",
5
+ "bytes": 23400
6
+ }