infixspeed-cli 0.0.16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. infix_cli/__init__.py +5 -0
  2. infix_cli/__main__.py +6 -0
  3. infix_cli/agent-guide.txt +71 -0
  4. infix_cli/cli_framework.py +96 -0
  5. infix_cli/command_contract.py +157 -0
  6. infix_cli/commands/__init__.py +1 -0
  7. infix_cli/commands/_artifacts.py +142 -0
  8. infix_cli/commands/_comparison.py +443 -0
  9. infix_cli/commands/_confirm.py +26 -0
  10. infix_cli/commands/_control.py +290 -0
  11. infix_cli/commands/_create.py +351 -0
  12. infix_cli/commands/_create_output.py +139 -0
  13. infix_cli/commands/_delete.py +288 -0
  14. infix_cli/commands/_download.py +459 -0
  15. infix_cli/commands/_fusion_common.py +191 -0
  16. infix_cli/commands/_fusion_config.py +394 -0
  17. infix_cli/commands/_fusion_feedback.py +319 -0
  18. infix_cli/commands/_fusion_tasks.py +507 -0
  19. infix_cli/commands/_fusion_tensorboard.py +132 -0
  20. infix_cli/commands/_jobs.py +312 -0
  21. infix_cli/commands/_logs.py +210 -0
  22. infix_cli/commands/_publish.py +123 -0
  23. infix_cli/commands/_register.py +600 -0
  24. infix_cli/commands/_register_output.py +231 -0
  25. infix_cli/commands/_storage_tree.py +62 -0
  26. infix_cli/commands/admin.py +668 -0
  27. infix_cli/commands/asset.py +2012 -0
  28. infix_cli/commands/auth.py +246 -0
  29. infix_cli/commands/deploy.py +850 -0
  30. infix_cli/commands/evaluation.py +360 -0
  31. infix_cli/commands/examples.py +138 -0
  32. infix_cli/commands/fusion.py +1842 -0
  33. infix_cli/commands/merge.py +709 -0
  34. infix_cli/commands/resource.py +127 -0
  35. infix_cli/commands/spark.py +347 -0
  36. infix_cli/commands/storage.py +329 -0
  37. infix_cli/commands/training.py +748 -0
  38. infix_cli/config.py +311 -0
  39. infix_cli/config_input.py +217 -0
  40. infix_cli/context.py +84 -0
  41. infix_cli/discovery.py +459 -0
  42. infix_cli/domain/__init__.py +1 -0
  43. infix_cli/domain/dto/__init__.py +6 -0
  44. infix_cli/domain/dto/admin.py +413 -0
  45. infix_cli/domain/dto/asset.py +390 -0
  46. infix_cli/domain/dto/common.py +136 -0
  47. infix_cli/domain/dto/evaluation.py +296 -0
  48. infix_cli/domain/dto/logs.py +98 -0
  49. infix_cli/domain/dto/resource.py +108 -0
  50. infix_cli/domain/dto/serving.py +156 -0
  51. infix_cli/domain/dto/spark.py +241 -0
  52. infix_cli/domain/dto/storage.py +75 -0
  53. infix_cli/domain/dto/training.py +272 -0
  54. infix_cli/domain/enums.py +359 -0
  55. infix_cli/domain/hyperparams.py +190 -0
  56. infix_cli/domain/refs.py +108 -0
  57. infix_cli/domain/resolve.py +619 -0
  58. infix_cli/errors.py +158 -0
  59. infix_cli/example_data/__init__.py +1 -0
  60. infix_cli/example_data/fusion/README.md +128 -0
  61. infix_cli/example_data/fusion/fusion.json +149 -0
  62. infix_cli/example_data/fusion/prompts/code.jsonl +16 -0
  63. infix_cli/example_data/fusion/prompts/math.jsonl +16 -0
  64. infix_cli/example_data/fusion.zip +0 -0
  65. infix_cli/example_data/merge/README.md +89 -0
  66. infix_cli/example_data/merge/merge.json +26 -0
  67. infix_cli/example_data/merge.zip +0 -0
  68. infix_cli/http/__init__.py +1 -0
  69. infix_cli/http/browser_auth.py +160 -0
  70. infix_cli/http/client.py +575 -0
  71. infix_cli/http/pagination.py +84 -0
  72. infix_cli/http/upload.py +254 -0
  73. infix_cli/main.py +432 -0
  74. infix_cli/pipeline_config_schema.py +122 -0
  75. infix_cli/render/__init__.py +79 -0
  76. infix_cli/render/json_out.py +123 -0
  77. infix_cli/render/progress.py +62 -0
  78. infix_cli/render/text.py +233 -0
  79. infix_cli/update_check.py +177 -0
  80. infix_cli/waiter.py +93 -0
  81. infix_cli/workspace.py +158 -0
  82. infixspeed_cli-0.0.16.dist-info/METADATA +58 -0
  83. infixspeed_cli-0.0.16.dist-info/RECORD +85 -0
  84. infixspeed_cli-0.0.16.dist-info/WHEEL +4 -0
  85. infixspeed_cli-0.0.16.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,748 @@
1
+ """``infix training`` — training jobs (read-only in this phase)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Optional
7
+
8
+ import typer
9
+
10
+ from infix_cli import render
11
+ from infix_cli.commands import _control, _create, _delete, _jobs, _logs, _publish
12
+ from infix_cli.domain import enums, hyperparams, resolve
13
+ from infix_cli.domain.dto.training import TrainingJobDTO
14
+ from infix_cli.errors import CliError, ExitCode, UsageError
15
+ from infix_cli.http.pagination import fetch_page
16
+
17
+ app = typer.Typer(help="Model training jobs.", no_args_is_help=True)
18
+
19
+
20
+ @app.command("list")
21
+ def list_jobs(
22
+ ctx: typer.Context,
23
+ status: Optional[str] = typer.Option(None, "--status", help="Filter by job status."),
24
+ search: Optional[str] = typer.Option(None, "--search", help="Fuzzy name match."),
25
+ visibility: Optional[str] = typer.Option(
26
+ None, "--visibility", help="private | public",
27
+ ),
28
+ page: int = typer.Option(1, "--page", "-p", min=1),
29
+ page_size: int = typer.Option(None, "--page-size", min=1, max=50),
30
+ ) -> None:
31
+ """List training jobs in the current workspace."""
32
+ run = ctx.obj
33
+ client = run.client()
34
+ items, page_no, size, total = fetch_page(
35
+ client, "/training/jobs",
36
+ params={
37
+ "status": _jobs.validate_status("training", status),
38
+ "search": search,
39
+ "visibility": _jobs.validate_visibility(visibility),
40
+ },
41
+ page=page, page_size=run.default_page_size(page_size),
42
+ )
43
+ namer = resolve.HardwareNamer(client, "training")
44
+ dtos = [
45
+ TrainingJobDTO.from_api(raw, hardware=namer.by_summary(raw.get("resource")))
46
+ for raw in items
47
+ ]
48
+ render.render_list(
49
+ run, dtos, TrainingJobDTO.columns(),
50
+ page=page_no, page_size=size, total=total,
51
+ empty_message="No training jobs found.",
52
+ )
53
+
54
+
55
+ @app.command("get")
56
+ def get_job(
57
+ ctx: typer.Context,
58
+ name: str = typer.Argument(..., help="Job name (or id)."),
59
+ ) -> None:
60
+ """Show one training job in detail.
61
+
62
+ A successful query exits 0; the job outcome is in the status field.
63
+ """
64
+ run = ctx.obj
65
+ client = run.client()
66
+ job = resolve.find_job(client, "training", name)
67
+ detail = client.get(f"/training/jobs/{job['id']}")
68
+ raw = detail if isinstance(detail, dict) else job
69
+ namer = resolve.HardwareNamer(client, "training")
70
+ dto = TrainingJobDTO.from_api(
71
+ raw,
72
+ hardware=namer.resolve(
73
+ spec_id=raw.get("computing_spec_id"), summary=raw.get("resource_summary"),
74
+ ),
75
+ detail=True,
76
+ tensorboard_url=_tensorboard_url(run, client, str(raw.get("id"))),
77
+ )
78
+ render.render_detail(run, dto)
79
+
80
+
81
+ def _absolute_url(run, url: Any) -> str | None:
82
+ """Make the visualizer's path openable.
83
+
84
+ The backend returns a root-relative path (``/vis/<id>/``), which is what the
85
+ console's own router needs but leaves a terminal reader without a host to
86
+ put in front of it. Prefixed with the configured endpoint, as the PRD asks
87
+ for a link — the same assumption the Related Evaluation field makes, namely
88
+ that the console is served from the API host. An absolute URL from a future
89
+ backend is passed through untouched.
90
+ """
91
+ text = str(url or "").strip()
92
+ if not text:
93
+ return None
94
+ if text.startswith(("http://", "https://")):
95
+ return text
96
+ return f"{run.profile.api_url.rstrip('/')}/{text.lstrip('/')}"
97
+
98
+
99
+ def _tensorboard_url(run, client, job_id: str) -> str | None:
100
+ """Read the TensorBoard session without starting one.
101
+
102
+ The backend starts a real Pod on demand with a 30-minute TTL kept alive by
103
+ heartbeats; a one-shot ``get`` has no process to send them, so it only
104
+ reports a session that is already Ready (tech-design §4.14).
105
+ """
106
+ from infix_cli.errors import CliError
107
+
108
+ try:
109
+ status = client.get(f"/training/jobs/{job_id}/visualizer/status")
110
+ except CliError:
111
+ return None
112
+ if isinstance(status, dict) and str(status.get("phase")) == "Ready":
113
+ return _absolute_url(run, status.get("url"))
114
+ return None
115
+
116
+
117
+ @app.command("create")
118
+ def create_job(
119
+ ctx: typer.Context,
120
+ name: Optional[str] = typer.Option(None, "--name", "-n", help="Job name (3-50 chars: letters, digits, . _ -).", rich_help_panel="Required"),
121
+ base_model: Optional[str] = typer.Option(
122
+ None, "--base-model", help="official/<name> | workspace/<name>[:<version>] | storage/<path>", rich_help_panel="Required",
123
+ ),
124
+ dataset: Optional[str] = typer.Option(
125
+ None, "--dataset", help="workspace/<name>[:<version>] | official/<name> | storage/<path>", rich_help_panel="Required",
126
+ ),
127
+ code: Optional[str] = typer.Option(
128
+ None, "--code", help="Training script asset. Required with --method custom.", rich_help_panel="Required (conditional)",
129
+ ),
130
+ method: Optional[str] = typer.Option(None, "--method", "-m", help="fp8 | fp4-rl | custom", rich_help_panel="Required"),
131
+ task: Optional[str] = typer.Option(
132
+ None, "--task", help="cpt | sft | rl. Default sft; fp4-rl is always rl.",
133
+ ),
134
+ checkpoint_precision: Optional[str] = typer.Option(
135
+ None, "--checkpoint-precision",
136
+ help="Required for preset methods. fp8: fp8+bf16 | only-fp8 | only-bf16. "
137
+ "fp4-rl: fp4+bf16 | only-fp4 | only-bf16.",
138
+ ),
139
+ hardware: Optional[str] = typer.Option(
140
+ None, "--hardware", help='Hardware name from "infix resource list --task training".', rich_help_panel="Required",
141
+ ),
142
+ workers: Optional[int] = typer.Option(None, "--workers", min=1, help="Worker count. Default 1."),
143
+ image: Optional[str] = typer.Option(None, "--image", help="Container image. Custom method only.", rich_help_panel="Required (conditional)"),
144
+ startup_command: Optional[str] = typer.Option(
145
+ None, "--startup-command", help="Custom method only. Runs as: bash -c '<command>'.",
146
+ ),
147
+ tensorboard_log_path: Optional[str] = typer.Option(None, "--tensorboard-log-path"),
148
+ training_framework: Optional[str] = typer.Option(None, "--training-framework", help="pytorch"),
149
+ setting: list[str] = typer.Option(
150
+ [], "--set", help="Hyperparameter as key=value. Repeatable. Preset methods only.",
151
+ ),
152
+ visibility: Optional[str] = typer.Option(None, "--visibility", help="private | public"),
153
+ description: Optional[str] = typer.Option(None, "--description"),
154
+ config: Optional[str] = typer.Option(
155
+ None, "--config", help="JSON file of the same options. Task flags cannot be combined with --config. Use - for stdin.",
156
+ ),
157
+ wait: bool = typer.Option(False, "--wait", help="Block until the job reaches a terminal state."),
158
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h. Default: 30s."),
159
+ dry_run: bool = typer.Option(False, "--dry-run", help="Resolve and validate inputs without submitting a job."),
160
+ ) -> None:
161
+ """Submit a training job.
162
+
163
+ Hyperparameters available per task: cpt — train-iters, lr-warmup-iter;
164
+ sft — num-epoch, rollout-batch-size, global-batch-size; rl — save-interval,
165
+ num-rollout, rollout-batch-size, n-samples-per-prompt,
166
+ rollout-max-response-len, global-batch-size.
167
+
168
+ Shared SFT presets also accept learning-rate, warmup-updates, context-length,
169
+ enable-thinking, save-interval, updates, seed, topology and chat-template-kwargs.
170
+ They require an explicit checkpoint precision and canonical token/mask JSONL data.
171
+
172
+ Examples:
173
+
174
+ infix training create -n sft-qwen --base-model official/qwen2-7b-base
175
+ --dataset workspace/sft-dialogue:v1.0.0 -m fp8 --task sft
176
+ --checkpoint-precision fp8+bf16 --hardware 8x_nvidia_h200_141gb
177
+ --workers 2 --set num-epoch=5 --wait
178
+
179
+ infix training create --config job.json --wait
180
+ """
181
+ run = ctx.obj
182
+ cfg = _create.load_config(config)
183
+ pick = _create.pick
184
+
185
+ name = pick(name, cfg, "name", required=True, flag="--name")
186
+ method = pick(method, cfg, "method", default="fp8")
187
+ task = pick(task, cfg, "task", default=_default_task(method))
188
+ base_model_ref = pick(base_model, cfg, "base_model", required=True, flag="--base-model")
189
+ dataset_ref = pick(dataset, cfg, "dataset", required=True, flag="--dataset")
190
+ code_ref = pick(code, cfg, "code")
191
+ hardware = pick(hardware, cfg, "hardware", required=True, flag="--hardware")
192
+ workers = int(pick(workers, cfg, "workers", default=1))
193
+ visibility = pick(visibility, cfg, "visibility", default="private")
194
+ checkpoint_precision = pick(checkpoint_precision, cfg, "checkpoint_precision")
195
+ image = pick(image, cfg, "image")
196
+ startup_command = pick(startup_command, cfg, "startup_command")
197
+ tensorboard_log_path = pick(tensorboard_log_path, cfg, "tensorboard_log_path")
198
+ training_framework = pick(training_framework, cfg, "training_framework")
199
+ description = pick(description, cfg, "description")
200
+ # Same precedence as pick(): a config file describes the whole job, so it
201
+ # supersedes --set too. This line read `list(setting) or ...`, which
202
+ # inverted the rule for hyperparameters alone.
203
+ settings = _config_settings(cfg) if cfg else list(setting)
204
+
205
+ _validate_training_choices(method, task, checkpoint_precision, code_ref)
206
+ hyper = hyperparams.parse(settings, task=task, method=method)
207
+
208
+ client = run.client()
209
+ slots = {
210
+ "base_model": _create.resolve_slot(
211
+ client, base_model_ref, kind="model", flag="--base-model", check_storage=dry_run,
212
+ ),
213
+ "dataset": _create.resolve_slot(
214
+ client, dataset_ref, kind="dataset", flag="--dataset", check_storage=dry_run,
215
+ ),
216
+ }
217
+ code_slot = (
218
+ _create.resolve_slot(client, code_ref, kind="code", flag="--code", check_storage=dry_run)
219
+ if code_ref else None
220
+ )
221
+ spec = resolve.resolve_hardware(
222
+ client, hardware, task="training", workspace_id=run.profile.workspace_id,
223
+ )
224
+
225
+ if not image and method != "custom":
226
+ image = _preset_image(client, task=task, method=method)
227
+
228
+ payload = _create.training_payload(
229
+ name=name, base_model=slots["base_model"], dataset=slots["dataset"], code=code_slot,
230
+ method=method, task=task, checkpoint_precision=checkpoint_precision,
231
+ computing_spec_id=str(spec["id"]), workers=workers, image=image,
232
+ startup_command=startup_command, tensorboard_log_path=tensorboard_log_path,
233
+ framework=training_framework, hyperparameters=hyper, visibility=visibility,
234
+ description=description,
235
+ )
236
+ namer = resolve.HardwareNamer(client, "training")
237
+ _jobs.submit_and_report(
238
+ run, "training",
239
+ echo={"base_model": base_model_ref, "dataset": dataset_ref},
240
+ path="/training/jobs", payload=payload,
241
+ detail_path=lambda job_id: f"/training/jobs/{job_id}",
242
+ build_dto=lambda raw: TrainingJobDTO.from_api(
243
+ raw, detail=True,
244
+ hardware=namer.resolve(
245
+ spec_id=raw.get("computing_spec_id"), summary=raw.get("resource_summary"),
246
+ ),
247
+ ),
248
+ wait=wait, timeout=timeout, dry_run=dry_run,
249
+ )
250
+
251
+
252
+ def _config_settings(cfg: dict) -> list[str]:
253
+ """A config file carries hyperparameters as an object, not repeated flags."""
254
+ raw = cfg.get("set") or cfg.get("hyperparameters") or {}
255
+ if isinstance(raw, dict):
256
+ return [f"{key}={json.dumps(value, allow_nan=False) if isinstance(value, (bool, dict, list)) else value}" for key, value in raw.items()]
257
+ return list(raw)
258
+
259
+
260
+ def _preset_image(client, *, task: str, method: str) -> str | None:
261
+ """Send the image the preset itself declares, for preset methods.
262
+
263
+ ``container_image`` is optional on the API and the backend overwrites it
264
+ from the preset anyway, but its validator rejects ``None`` before that code
265
+ runs, turning every preset submission into a 503 (the pydantic error is
266
+ wrapped as an infrastructure failure, so the cause never reaches the
267
+ caller). The web console never hits this: it always submits the image it
268
+ displayed. Sending the same value the backend would have picked keeps
269
+ preset jobs submittable; it can be dropped once the validator accepts None.
270
+ """
271
+ task_value = enums.TASK_TYPE.to_backend(task)
272
+ method_value = enums.TRAINING_METHOD.to_backend(method)
273
+ try:
274
+ presets = client.get("/training/presets")
275
+ except CliError:
276
+ # A failed lookup must not turn into a worse error than the one it
277
+ # works around — let the submission proceed and report the real reply.
278
+ return None
279
+ items = list(presets.get("items") or []) if isinstance(presets, dict) else list(presets or [])
280
+ for item in items:
281
+ if item.get("task_type") == task_value and item.get("method") == method_value:
282
+ return item.get("image_url") or None
283
+
284
+ # No preset for this pair: submitting anyway hits the same 503 this function
285
+ # exists to avoid, and the backend's own "preset not found" never surfaces
286
+ # because the validator rejects the empty image first. Say it here, where
287
+ # the combination the user typed is still what we are talking about.
288
+ raise UsageError(
289
+ f'No training preset for --task {task} --method {method}.',
290
+ f"Available: {_preset_combinations(items)}.",
291
+ )
292
+
293
+
294
+ def _preset_combinations(items: list[dict]) -> str:
295
+ """The task/method pairs this platform has presets for, in CLI words.
296
+
297
+ Presets the CLI has no vocabulary for (the backend also ships MOCK and DPO)
298
+ are left out: naming a combination that --task would reject is worse than
299
+ naming none.
300
+ """
301
+ pairs = sorted({
302
+ (task, method)
303
+ for task, method in (
304
+ (enums.TASK_TYPE.to_cli(item.get("task_type")),
305
+ enums.TRAINING_METHOD.to_cli(item.get("method")))
306
+ for item in items
307
+ )
308
+ if task in enums.TASK_TYPE.cli_values and method in enums.TRAINING_METHOD.cli_values
309
+ })
310
+ if not pairs:
311
+ return "none on this platform — ask an administrator to configure one"
312
+ return ", ".join(f"--task {task} --method {method}" for task, method in pairs)
313
+
314
+
315
+ def _default_task(method: str) -> str:
316
+ """The task to assume when ``--task`` is absent.
317
+
318
+ A method that can run only one task states it already, so asking the user
319
+ to repeat it is busywork — and worse than busywork, because the blanket
320
+ "sft" default this replaces made ``--method fp4-rl`` fail on its own
321
+ default: "Method fp4-rl cannot run task sft", about a task nobody named.
322
+ The PRD says fp4-rl is fixed to rl and needs no --task, which is this rule.
323
+
324
+ Methods with a real choice (fp8, custom) keep sft, the PRD's default.
325
+ """
326
+ allowed = hyperparams.tasks_for_method(method)
327
+ return allowed[0] if len(allowed) == 1 else "sft"
328
+
329
+
330
+ def _validate_training_choices(
331
+ method: str, task: str, checkpoint_precision: str | None, code_ref: str | None,
332
+ ) -> None:
333
+ """Catch locally what the backend would reject, while it can still be explained.
334
+
335
+ Each of these is a 422 otherwise, worded in terms of backend enum values.
336
+ """
337
+ if method not in enums.TRAINING_METHOD.cli_values:
338
+ raise UsageError(
339
+ f'Invalid --method "{method}".',
340
+ f"Valid: {', '.join(enums.TRAINING_METHOD.cli_values)}.",
341
+ )
342
+ if task not in enums.TASK_TYPE.cli_values:
343
+ raise UsageError(
344
+ f'Invalid --task "{task}".', f"Valid: {', '.join(enums.TASK_TYPE.cli_values)}.",
345
+ )
346
+ allowed_tasks = hyperparams.tasks_for_method(method)
347
+ if task not in allowed_tasks:
348
+ raise UsageError(
349
+ f'Method "{method}" cannot run task "{task}".',
350
+ f"{method} supports: {', '.join(allowed_tasks)}.",
351
+ )
352
+ if method == "custom":
353
+ if not code_ref:
354
+ raise UsageError(
355
+ "--code is required with --method custom.",
356
+ "A custom job runs your own training script.",
357
+ )
358
+ if checkpoint_precision:
359
+ raise UsageError("--checkpoint-precision applies to preset methods only.")
360
+ return
361
+
362
+ valid_precisions = enums.CKPT_PRECISION_BY_METHOD.get(method, ())
363
+ if not checkpoint_precision:
364
+ raise UsageError(
365
+ f"--checkpoint-precision is required with --method {method}.",
366
+ f"Valid: {', '.join(valid_precisions)}.",
367
+ )
368
+ if checkpoint_precision not in valid_precisions:
369
+ raise UsageError(
370
+ f'--checkpoint-precision "{checkpoint_precision}" is not valid for method {method}.',
371
+ f"Valid: {', '.join(valid_precisions)}.",
372
+ )
373
+
374
+
375
+ @app.command("logs")
376
+ def job_logs(
377
+ ctx: typer.Context,
378
+ name: str = typer.Argument(..., help="Job name (or id)."),
379
+ worker: Optional[str] = typer.Option(
380
+ None, "--worker", help="Worker pod. Defaults to master, not all workers.",
381
+ ),
382
+ tail: int = typer.Option(500, "--tail", min=1, max=5000, help="Lines to read."),
383
+ keyword: Optional[str] = typer.Option(
384
+ None, "--keyword", help="Filter locally, within the --tail lines only.",
385
+ ),
386
+ follow: bool = typer.Option(False, "--follow", "-f", help="Stream until interrupted."),
387
+ download: Optional[str] = typer.Option(
388
+ None, "--download", help="Write the log to this file instead of printing it.",
389
+ ),
390
+ ) -> None:
391
+ """Read a training job's logs.
392
+
393
+ Without --worker only the master pod is read. --keyword filters the lines
394
+ --tail returned, so it cannot find anything older than those.
395
+
396
+ Examples:
397
+
398
+ infix training logs sft-qwen --tail 200 --keyword loss
399
+
400
+ infix training logs sft-qwen -f
401
+ """
402
+ run = ctx.obj
403
+ client = run.client()
404
+ job_id = str(resolve.find_job(client, "training", name)["id"])
405
+
406
+ if download:
407
+ _logs.download(run, "training", job_id, worker=worker, tail=tail, dest=download)
408
+ return
409
+ seed = _logs.fetch(client, "training", job_id, worker=worker, tail=tail)
410
+ if follow:
411
+ _logs.follow(
412
+ run,
413
+ lambda since: _logs.stream_once(
414
+ client, "training", job_id, worker=worker, since=since,
415
+ ),
416
+ keyword=keyword, seed=seed,
417
+ )
418
+ return
419
+ _logs.render(run, seed, keyword=keyword)
420
+
421
+
422
+ @app.command("stop")
423
+ def stop_job(
424
+ ctx: typer.Context,
425
+ name: str = typer.Argument(..., help="Job name (or id)."),
426
+ ) -> None:
427
+ """Stop a training job.
428
+
429
+ Queued jobs are cancelled (the workload is removed); running ones are
430
+ suspended, which keeps the workload so it can be resumed server-side.
431
+ """
432
+ run = ctx.obj
433
+ job = resolve.find_job(run.client(), "training", name)
434
+ updated = _control.stop(run, "training", job)
435
+ status = enums.status_to_cli(updated.get("status")) or "stopping"
436
+ render.message(run, f'Training job "{job.get("name")}" is now {status}.')
437
+
438
+
439
+ @app.command("restart")
440
+ def restart_job(
441
+ ctx: typer.Context,
442
+ name: str = typer.Argument(..., help="Job name (or id)."),
443
+ wait: bool = typer.Option(False, "--wait", help="Block until the job reaches a terminal state."),
444
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h."),
445
+ ) -> None:
446
+ """Resubmit a training job."""
447
+ run = ctx.obj
448
+ client = run.client()
449
+ job = resolve.find_job(client, "training", name)
450
+ _control.restart(run, "training", job)
451
+ job_id = str(job["id"])
452
+ namer = resolve.HardwareNamer(client, "training")
453
+ _jobs.report_existing(
454
+ run, "training", job_id=job_id, name=str(job.get("name") or job_id),
455
+ detail_path=lambda jid: f"/training/jobs/{jid}",
456
+ build_dto=lambda raw: TrainingJobDTO.from_api(
457
+ raw, detail=True,
458
+ hardware=namer.resolve(
459
+ spec_id=raw.get("computing_spec_id"), summary=raw.get("resource_summary"),
460
+ ),
461
+ ),
462
+ wait=wait, timeout=timeout,
463
+ )
464
+
465
+
466
+ @app.command("wait")
467
+ def wait_job(
468
+ ctx: typer.Context,
469
+ name: str = typer.Argument(..., help="Job name (or id)."),
470
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h. Default: 30s."),
471
+ ) -> None:
472
+ """Wait for a training job to finish; exit 0 on success, 7 on failure, 6 on timeout.
473
+
474
+ For re-attaching after an interrupted --wait. Ctrl-C stops waiting only;
475
+ the job keeps running.
476
+ """
477
+ run = ctx.obj
478
+ client = run.client()
479
+ job = resolve.find_job(client, "training", name)
480
+ job_id = str(job["id"])
481
+ namer = resolve.HardwareNamer(client, "training")
482
+ _jobs.wait_existing(
483
+ run, "training", job_id=job_id, name=str(job.get("name") or job_id),
484
+ detail_path=lambda jid: f"/training/jobs/{jid}",
485
+ build_dto=lambda raw: TrainingJobDTO.from_api(
486
+ raw, detail=True,
487
+ hardware=namer.resolve(
488
+ spec_id=raw.get("computing_spec_id"), summary=raw.get("resource_summary"),
489
+ ),
490
+ ),
491
+ timeout=timeout,
492
+ )
493
+
494
+
495
+ @app.command("artifacts")
496
+ def list_artifacts(
497
+ ctx: typer.Context,
498
+ name: str = typer.Argument(..., help="Job name (or id)."),
499
+ precision: Optional[str] = typer.Option(None, "--precision", help="Only this precision, e.g. bf16."),
500
+ page: int = typer.Option(1, "--page", min=1),
501
+ page_size: Optional[int] = typer.Option(None, "--page-size", min=1, max=100),
502
+ ) -> None:
503
+ """List a training job's checkpoints.
504
+
505
+ Download one with: infix training download <job> --checkpoint <step>
506
+ """
507
+ from infix_cli.commands._artifacts import CheckpointDTO
508
+
509
+ run = ctx.obj
510
+ client = run.client()
511
+ job = resolve.find_job(client, "training", name)
512
+ items, page_no, size, total = fetch_page(
513
+ client, f"/training/jobs/{job['id']}/artifacts",
514
+ params={"precision": precision.upper() if precision else None},
515
+ page=page, page_size=run.default_page_size(page_size),
516
+ )
517
+ render.render_list(
518
+ run, [CheckpointDTO.from_api(raw) for raw in items], CheckpointDTO.columns(),
519
+ page=page_no, page_size=size, total=total, quiet_field="step",
520
+ empty_message=f'Training job "{job.get("name")}" has no checkpoints yet.',
521
+ )
522
+
523
+
524
+ @app.command("download")
525
+ def download_output(
526
+ ctx: typer.Context,
527
+ name: str = typer.Argument(..., help="Job name (or id)."),
528
+ checkpoint: Optional[str] = typer.Option(
529
+ None, "--checkpoint", help="Only this checkpoint (its step). Default: the whole output.",
530
+ ),
531
+ dest: Optional[str] = typer.Option(
532
+ None, "--dest", "-d", help="Local directory to download into. Defaults to the current one.",
533
+ ),
534
+ concurrency: int = typer.Option(4, "--concurrency", min=1, max=8),
535
+ overwrite: bool = typer.Option(
536
+ False, "--overwrite", help="Download from the beginning without reusing local files or partial downloads.",
537
+ ),
538
+ ) -> None:
539
+ """Download a training job's output directory, or one checkpoint from it.
540
+
541
+ Files land under <dest>/<output folder>/. Re-running reuses completed files
542
+ and resumes partial files when the remote ETag and local metadata match.
543
+ """
544
+ from infix_cli.commands import _artifacts
545
+
546
+ _artifacts.download_output(
547
+ ctx.obj, name, step=checkpoint, dest=dest, overwrite=overwrite,
548
+ concurrency=concurrency,
549
+ )
550
+
551
+
552
+ @app.command("publish")
553
+ def publish_job(
554
+ ctx: typer.Context,
555
+ name: str = typer.Argument(..., help="Job name (or id)."),
556
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
557
+ ) -> None:
558
+ """Make a training job public to the workspace. This cannot be undone.
559
+
560
+ Its output directory is shared along with it.
561
+ """
562
+ _publish.publish_job(ctx.obj, "training", name, yes=yes)
563
+
564
+
565
+ @app.command("delete")
566
+ def delete_job(
567
+ ctx: typer.Context,
568
+ name: str = typer.Argument(..., help="Job name (or id)."),
569
+ force: bool = typer.Option(
570
+ False, "--force", help="Delete even if the job is still queued or running.",
571
+ ),
572
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
573
+ ) -> None:
574
+ """Delete a training job. This cannot be undone.
575
+
576
+ The output directory stays in Workspace Storage.
577
+ A job that has not finished is refused unless --force is given.
578
+ """
579
+ _delete.delete_job(ctx.obj, "training", name, force=force, yes=yes)
580
+
581
+
582
+ @app.command("clone")
583
+ def clone_job(
584
+ ctx: typer.Context,
585
+ name: str = typer.Argument(..., help="Job to copy the configuration from."),
586
+ new_name: Optional[str] = typer.Option(
587
+ None, "--name", help="Name for the new job. Default: <original>-clone-1.",
588
+ ),
589
+ save: Optional[str] = typer.Option(
590
+ None, "--save", help="Write the config to this file instead of printing it.",
591
+ ),
592
+ ) -> None:
593
+ """Print a job's configuration as a create --config file.
594
+
595
+ The cloned configuration includes a new job name and pins recorded
596
+ workspace asset versions. Use --name to customize the new job name.
597
+ """
598
+ run = ctx.obj
599
+ client = run.client()
600
+ job = resolve.find_job(client, "training", name)
601
+ detail = client.get(f"/training/jobs/{job['id']}")
602
+ namer = resolve.HardwareNamer(client, "training")
603
+ raw = detail if isinstance(detail, dict) else job
604
+ dto = TrainingJobDTO.from_api(
605
+ raw, detail=True,
606
+ hardware=namer.resolve(
607
+ spec_id=raw.get("computing_spec_id"), summary=raw.get("resource_summary"),
608
+ ),
609
+ )
610
+ _control.emit_clone(
611
+ run, _control.training_config(dto, _control.clone_name(dto, new_name), client=client),
612
+ save=save, module="training",
613
+ )
614
+
615
+
616
+ @app.command("tensorboard")
617
+ def tensorboard(
618
+ ctx: typer.Context,
619
+ name: str = typer.Argument(..., help="Job name (or id)."),
620
+ stop: bool = typer.Option(False, "--stop", help="Shut the session down instead of starting it."),
621
+ ttl: Optional[str] = typer.Option(
622
+ None, "--ttl", help="Session lifetime, 5m-2h. Default 30m.",
623
+ ),
624
+ logdir: Optional[str] = typer.Option(
625
+ None, "--logdir", help="Subdirectory under the job's output to read. Default: all of it.",
626
+ ),
627
+ size: str = typer.Option("small", "--size", help="small | medium | large"),
628
+ ) -> None:
629
+ """Start (or stop) a TensorBoard session for a training job.
630
+
631
+ The platform runs TensorBoard as an on-demand pod with a TTL, not as a
632
+ permanent link — so it is a command rather than a field on `get`. The
633
+ session is reclaimed when the TTL runs out; run this again to get a new one.
634
+ """
635
+ run = ctx.obj
636
+ client = run.client()
637
+ job = resolve.find_job(client, "training", name)
638
+ job_id = str(job["id"])
639
+ job_name = str(job.get("name") or job_id)
640
+
641
+ if stop:
642
+ client.delete(f"/training/jobs/{job_id}/visualizer/stop")
643
+ if run.output == "json":
644
+ render.json_out.print_raw({"id": job_id, "job": job_name, "stop_requested": True})
645
+ else:
646
+ render.message(run, f'Stopped the TensorBoard session for "{job_name}".')
647
+ return
648
+
649
+ ttl_seconds = _tensorboard_ttl(ttl)
650
+ _check_tensorboard_capacity(run, client, job_id, size)
651
+
652
+ body = {"size": size, "ttl_seconds": ttl_seconds}
653
+ if logdir:
654
+ body["logdir"] = logdir
655
+ session = client.post(f"/training/jobs/{job_id}/visualizer/start", json=body) or {}
656
+ session = _await_tensorboard(run, client, job_id, session)
657
+
658
+ # The session's url is root-relative; a terminal reader needs the host.
659
+ url = _absolute_url(run, session.get("url"))
660
+ payload = {
661
+ "job": job_name,
662
+ "phase": session.get("phase"),
663
+ "url": url,
664
+ "remaining_seconds": session.get("remaining_seconds"),
665
+ "size": session.get("size"),
666
+ }
667
+ rows = [
668
+ ("Job", job_name),
669
+ ("Phase", str(session.get("phase") or "--")),
670
+ ("URL", url or "--"),
671
+ ("Expires in", _remaining_text(session.get("remaining_seconds"))),
672
+ ]
673
+ render.render_object(run, payload, rows, quiet_value=url or "")
674
+
675
+ if str(session.get("phase")) != "Ready":
676
+ raise typer.Exit(run.resolve_exit(ExitCode.GENERAL))
677
+
678
+
679
+ def _tensorboard_ttl(ttl: str | None) -> int:
680
+ """Parse --ttl into the seconds the backend accepts (300-7200)."""
681
+ from infix_cli import waiter
682
+
683
+ if not ttl:
684
+ return 1800
685
+ seconds = int(waiter.parse_timeout(ttl) or 1800)
686
+ if not 300 <= seconds <= 7200:
687
+ raise UsageError(
688
+ f"--ttl must be between 5m and 2h, got {ttl}.",
689
+ )
690
+ return seconds
691
+
692
+
693
+ def _check_tensorboard_capacity(run, client, job_id: str, size: str) -> None:
694
+ """Ask preflight whether the requested size fits before starting a pod.
695
+
696
+ A failed start still costs a scheduling attempt; this turns "pod stuck
697
+ Pending" into a message naming the sizes that would fit.
698
+ """
699
+ from infix_cli.errors import CliError
700
+
701
+ try:
702
+ preflight = client.get(f"/training/jobs/{job_id}/visualizer/preflight")
703
+ except CliError:
704
+ return # advisory only — never block a start on the check itself
705
+ options = {
706
+ str(item.get("name")): bool(item.get("fits"))
707
+ for item in (preflight or {}).get("sizes") or []
708
+ if isinstance(item, dict)
709
+ }
710
+ if options.get(size) is False:
711
+ fitting = [name for name, fits in options.items() if fits]
712
+ raise UsageError(
713
+ f'The cluster cannot fit a "{size}" TensorBoard session right now.',
714
+ f"Sizes that fit: {', '.join(fitting)}." if fitting else
715
+ "No size fits at the moment; try again once the cluster frees up.",
716
+ )
717
+
718
+
719
+ def _await_tensorboard(run, client, job_id: str, session: dict) -> dict:
720
+ """Poll until the session is Ready (or gives up)."""
721
+ from infix_cli import waiter
722
+
723
+ if str(session.get("phase")) in ("Ready", "Failed"):
724
+ return session
725
+
726
+ def fetch() -> tuple[str, dict]:
727
+ current = client.get(f"/training/jobs/{job_id}/visualizer/status")
728
+ current = current if isinstance(current, dict) else {}
729
+ return str(current.get("phase") or "Starting"), current
730
+
731
+ _phase, latest = waiter.wait_until_terminal(
732
+ fetch,
733
+ terminal=frozenset({"Ready", "Failed", "NotFound"}),
734
+ ctx=run,
735
+ timeout=300.0,
736
+ label="TensorBoard session",
737
+ recheck_hint='Run "infix training tensorboard <job>" again to retry.',
738
+ )
739
+ return latest or session
740
+
741
+
742
+ def _remaining_text(seconds) -> str:
743
+ from infix_cli.domain.dto.common import format_duration
744
+
745
+ try:
746
+ return format_duration(int(seconds))
747
+ except (TypeError, ValueError):
748
+ return "--"