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,359 @@
1
+ """Vocabulary mapping — contract #2.
2
+
3
+ CLI words are a promise to the user; backend enum values are an implementation
4
+ detail. Every translation between the two lives here, in both directions, and
5
+ unknown values pass through unchanged: a status the backend adds tomorrow must
6
+ not crash a CLI installed today.
7
+
8
+ Statuses are the deliberate exception to "mapping": CLI status words are the
9
+ backend values lowercased, 1:1. ``Stopped`` (suspended, CRD kept) and
10
+ ``Canceled`` (cancelled, CRD deleted) are genuinely different states that the
11
+ GUI shows separately, so collapsing them would lose information the user needs
12
+ (scope decision 20).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Iterable, Mapping
18
+
19
+ # ── statuses ────────────────────────────────────────────────────────────────
20
+
21
+ TRAINING_STATUSES = (
22
+ "created", "queued", "initializing", "running", "completed", "failed",
23
+ "timeout", "stopping", "stopped", "canceling", "canceled",
24
+ )
25
+ EVALUATION_STATUSES = (
26
+ "queued", "initializing", "running", "stopping", "stopped",
27
+ "canceling", "canceled", "completed", "failed",
28
+ )
29
+ # Spark has no Stopping/Canceling intermediate states.
30
+ SPARK_STATUSES = (
31
+ "queued", "initializing", "running", "completed", "failed", "stopped", "canceled",
32
+ )
33
+
34
+ STATUSES_BY_MODULE: Mapping[str, tuple[str, ...]] = {
35
+ "training": TRAINING_STATUSES,
36
+ "evaluation": EVALUATION_STATUSES,
37
+ "spark": SPARK_STATUSES,
38
+ }
39
+
40
+
41
+ def status_to_cli(value: str | None) -> str:
42
+ """``"Canceling"`` -> ``"canceling"``. Unknown values pass through."""
43
+ return (value or "").strip().lower()
44
+
45
+
46
+ def status_to_backend(value: str | None) -> str:
47
+ """``"canceling"`` -> ``"Canceling"`` for ``?status=`` filters."""
48
+ text = (value or "").strip()
49
+ if not text:
50
+ return ""
51
+ return text[:1].upper() + text[1:].lower()
52
+
53
+
54
+ # Model services are the exception to "lowercase 1:1". A service never finishes;
55
+ # the PRD and the GUI name its stages instead (Ready shows as "Available") and
56
+ # fold Pending / Creating into "deploying". The PRD's Draft does not exist: with
57
+ # too few resources the backend rejects the create (409) and keeps nothing.
58
+ SERVICE_STATUS_TO_CLI: Mapping[str, str] = {
59
+ "Pending": "deploying",
60
+ "Creating": "deploying",
61
+ "Ready": "available",
62
+ "Updating": "updating",
63
+ "Scaling": "scaling",
64
+ "Stopped": "stopped",
65
+ "Failed": "failed",
66
+ "Deleting": "deleting",
67
+ }
68
+ SERVICE_STATUSES = (
69
+ "deploying", "available", "updating", "scaling", "stopped", "failed", "deleting",
70
+ )
71
+
72
+
73
+ def service_status_to_cli(value: str | None) -> str:
74
+ """``"Ready"`` -> ``"available"``. Unknown values pass through lowercased."""
75
+ text = (value or "").strip()
76
+ return SERVICE_STATUS_TO_CLI.get(text, text.lower())
77
+
78
+
79
+ def service_status_to_backend(value: str) -> list[str]:
80
+ """``"deploying"`` -> ``["Pending", "Creating"]``, for ``?status=`` (comma-separated)."""
81
+ word = value.strip().lower()
82
+ return [backend for backend, cli in SERVICE_STATUS_TO_CLI.items() if cli == word]
83
+
84
+
85
+ # ── generic bidirectional map ───────────────────────────────────────────────
86
+
87
+
88
+ class Mapper:
89
+ """A CLI-word <-> backend-value map that never raises on unknown input.
90
+
91
+ ``aliases`` covers many-to-one CLI words (dataset stage has two words for
92
+ ``pretrain``); the first CLI word listed for a backend value is the one
93
+ used when converting back.
94
+ """
95
+
96
+ def __init__(self, pairs: Iterable[tuple[str, str]]) -> None:
97
+ self._to_backend: dict[str, str] = {}
98
+ self._to_cli: dict[str, str] = {}
99
+ for cli_word, backend_value in pairs:
100
+ self._to_backend[cli_word] = backend_value
101
+ self._to_cli.setdefault(backend_value, cli_word)
102
+
103
+ def to_backend(self, value: str | None) -> str:
104
+ if value is None:
105
+ return ""
106
+ return self._to_backend.get(value.strip().lower(), value)
107
+
108
+ def to_cli(self, value: str | None) -> str:
109
+ if value is None:
110
+ return ""
111
+ return self._to_cli.get(value.strip(), value.strip().lower())
112
+
113
+ @property
114
+ def cli_values(self) -> tuple[str, ...]:
115
+ return tuple(self._to_backend)
116
+
117
+
118
+ TASK_TYPE = Mapper([
119
+ ("cpt", "Pretrain"),
120
+ ("sft", "SFT"),
121
+ ("rl", "RL"),
122
+ ])
123
+
124
+ TRAINING_METHOD = Mapper([
125
+ ("fp8", "FP8"),
126
+ ("fp4-rl", "NV_FP4_RL"),
127
+ ("custom", "Custom"),
128
+ ])
129
+
130
+ CKPT_PRECISION = Mapper([
131
+ ("fp8+bf16", "FP8+BF16"),
132
+ ("only-fp8", "FP8"),
133
+ ("only-bf16", "BF16"),
134
+ ("fp4+bf16", "FP4+BF16"),
135
+ ("only-fp4", "FP4"),
136
+ ])
137
+
138
+ # Which checkpoint precisions each preset method accepts (tech-design §4.9).
139
+ CKPT_PRECISION_BY_METHOD: Mapping[str, tuple[str, ...]] = {
140
+ "fp8": ("fp8+bf16", "only-fp8", "only-bf16"),
141
+ "fp4-rl": ("fp4+bf16", "only-fp4", "only-bf16"),
142
+ }
143
+
144
+ # Asset *version* status. The PRD names only the first three; the rest are
145
+ # listed anyway so the mapping works in both directions — a caller comparing
146
+ # against backend values needs to_backend("deleted") to give "Deleted", which
147
+ # pass-through-unchanged cannot do.
148
+ ASSET_STATUS = Mapper([
149
+ ("registering", "Pending"),
150
+ ("available", "Active"),
151
+ ("failed", "Failed"),
152
+ ("deploying", "Deploying"),
153
+ ("deployed", "Deployed"),
154
+ ("archived", "Archived"),
155
+ ("deleted", "Deleted"),
156
+ ])
157
+
158
+ # Version states that will not change again — what a registration wait polls
159
+ # for. UNUSABLE is the subset that is terminal *and* not usable, which a caller
160
+ # must report as a failure whether or not it was waiting.
161
+ ASSET_VERSION_TERMINAL = frozenset({"available", "failed", "deleted"})
162
+ ASSET_VERSION_UNUSABLE = frozenset({"failed", "deleted"})
163
+
164
+ # Image registration is a sync from the source registry into the platform's own
165
+ # (app/application/image_service.py:create_image), reported on the image itself
166
+ # rather than on a version — images have no versions. POST /images returns as
167
+ # soon as the row exists, so a just-registered image is Pending and not yet
168
+ # usable; --wait polls this until it settles.
169
+ IMAGE_SYNC_STATUS = Mapper([
170
+ ("registering", "Pending"),
171
+ ("syncing", "Syncing"),
172
+ ("available", "Completed"),
173
+ ("failed", "Failed"),
174
+ ])
175
+ IMAGE_SYNC_TERMINAL = frozenset({"available", "failed"})
176
+
177
+ VISIBILITY = Mapper([
178
+ ("private", "Private"),
179
+ ("public", "Public"),
180
+ ])
181
+
182
+ # Scope as used by ``asset * list``. The backend also accepts public/manageable,
183
+ # which the CLI does not expose in this phase.
184
+ ASSET_SCOPE = Mapper([
185
+ ("workspace", "my"),
186
+ ("official", "official"),
187
+ ])
188
+
189
+ # Where an asset came from. Model uses ``source``, dataset ``data_source``,
190
+ # code ``code_source`` — three field names, one user-facing vocabulary.
191
+ ASSET_SOURCE = Mapper([
192
+ ("storage", "ImportFromMyStorage"),
193
+ ("local", "UploadFromLocal"),
194
+ ("third-party", "ImportFromThirdParty"),
195
+ ("manual", "Manual"),
196
+ ("training-job", "TrainingJob"),
197
+ ("official", "Official"),
198
+ ])
199
+
200
+ # Workspace roles as the PRD spells them in text output. JSON keeps the raw
201
+ # value, which is what a script matches on; only the human-facing rendering
202
+ # changes. Tenant owner reads as "Admin" and a workspace admin as "Sub-admin" —
203
+ # the two levels the admin commands gate on.
204
+ ROLE_DISPLAY = {
205
+ "owner": "Admin",
206
+ "admin": "Sub-admin",
207
+ "ml_engineer": "ML Engineer",
208
+ "mlops_engineer": "MLOps Engineer",
209
+ }
210
+
211
+
212
+ def role_display(role: str | None) -> str:
213
+ """Human-readable role name; unknown roles pass through unchanged."""
214
+ value = (role or "").strip()
215
+ return ROLE_DISPLAY.get(value, value)
216
+
217
+
218
+ # Usage as the PRD spells it in asset detail views ("Model Training", "Spark"),
219
+ # distinct from the CLI words used in flags (training, spark). JSON keeps the
220
+ # CLI word; only these detail blocks use the display form.
221
+ USAGE_DISPLAY = {
222
+ "Training": "Model Training",
223
+ "Evaluation": "Model Evaluation",
224
+ "ModelTraining": "Model Training",
225
+ "DataProcessing": "Spark",
226
+ "ModelDeployment": "Model Deployment",
227
+ }
228
+
229
+
230
+ def usage_display(backend_value: str | None) -> str:
231
+ value = (backend_value or "").strip()
232
+ return USAGE_DISPLAY.get(value, value)
233
+
234
+
235
+ # Dataset stage in the words of the console's "Model Stage" column.
236
+ STAGE_DISPLAY = {
237
+ "pretrain": "Pretrain",
238
+ "posttrain": "Posttrain",
239
+ "sft": "SFT",
240
+ "rl": "RL",
241
+ }
242
+
243
+
244
+ def stage_display(backend_value: str | None) -> str:
245
+ value = (backend_value or "").strip()
246
+ return STAGE_DISPLAY.get(value, value)
247
+
248
+
249
+ DATASET_USAGE = Mapper([
250
+ ("training", "Training"),
251
+ ("evaluation", "Evaluation"),
252
+ ])
253
+
254
+ # Many-to-one: cpt and pre-training both mean pretrain. Converting back yields
255
+ # the first word listed for each backend value.
256
+ DATASET_STAGE = Mapper([
257
+ ("cpt", "pretrain"),
258
+ ("pre-training", "pretrain"),
259
+ ("sft", "sft"),
260
+ ("rl", "rl"),
261
+ ("post-training", "posttrain"),
262
+ ])
263
+
264
+ # Image task and chip, in the exact strings the console's image form submits
265
+ # and its image picker filters on (studio-web modules/images/register.tsx).
266
+ # The backend stores both as free text and matches filters exactly, so an image
267
+ # registered as "training" / "cpu" was invisible wherever the console looked
268
+ # for "Model Training" / "CPU".
269
+ IMAGE_TASK = Mapper([
270
+ ("notebook", "Notebook"),
271
+ ("spark", "Spark"),
272
+ ("training", "Model Training"),
273
+ ("service", "Model Service"),
274
+ ])
275
+
276
+ CHIP_TYPE = Mapper([
277
+ ("cpu", "CPU"),
278
+ ("gpu", "GPU"),
279
+ ])
280
+
281
+ CODE_USAGE = Mapper([
282
+ ("spark", "DataProcessing"),
283
+ ("training", "ModelTraining"),
284
+ ("service", "ModelDeployment"),
285
+ ])
286
+
287
+ EVAL_TYPE = Mapper([
288
+ ("official", "official"),
289
+ ("single-choice", "single_choice"),
290
+ ("question-answering", "text_similarity"),
291
+ ])
292
+
293
+ # Four CLI words over three backend values: official and workspace both submit
294
+ # assets_models and differ only in the scope used to resolve the name.
295
+ MODEL_SOURCE_TO_BACKEND: Mapping[str, str] = {
296
+ "official": "assets_models",
297
+ "workspace": "assets_models",
298
+ "storage": "workspace_storage",
299
+ "endpoint": "model_services",
300
+ }
301
+
302
+
303
+ def model_source_to_cli(backend_value: str | None, *, official: bool = False) -> str:
304
+ """Backend model source -> CLI word.
305
+
306
+ ``assets_models`` is ambiguous on its own; pass ``official=True`` when the
307
+ referenced asset is known to live in the official namespace.
308
+ """
309
+ value = (backend_value or "").strip()
310
+ if value == "assets_models":
311
+ return "official" if official else "workspace"
312
+ if value == "workspace_storage":
313
+ return "storage"
314
+ if value == "model_services":
315
+ return "endpoint"
316
+ return value.lower()
317
+
318
+
319
+ DATASET_SOURCE = Mapper([
320
+ ("workspace", "assets_datasets"),
321
+ ("storage", "workspace_storage"),
322
+ ])
323
+
324
+ # ``resource list --task`` -> GET /computing/specs?scope=
325
+ RESOURCE_SCOPE = Mapper([
326
+ ("training", "training"),
327
+ ("spark", "data_processing"),
328
+ ("notebook", "notebook"),
329
+ ("serving", "model_serving"),
330
+ ])
331
+
332
+ # The same endpoint's `workload` parameter, which switches on the queue and
333
+ # capacity check. Note the values differ from the scope ones: data_proc, not
334
+ # data_processing.
335
+ RESOURCE_WORKLOAD = Mapper([
336
+ ("training", "training"),
337
+ ("spark", "data_proc"),
338
+ ("notebook", "notebook"),
339
+ ("serving", "serving"),
340
+ ])
341
+
342
+ # Asset registration sources, per asset kind (used by M3; kept here so the
343
+ # vocabulary stays in one file).
344
+ MODEL_SOURCE_KIND = Mapper([
345
+ ("storage", "Manual"),
346
+ ("huggingface", "Manual"),
347
+ ])
348
+
349
+ DATASET_REGISTER_SOURCE = Mapper([
350
+ ("storage", "ImportFromMyStorage"),
351
+ ("local", "UploadFromLocal"),
352
+ ("huggingface", "ImportFromThirdParty"),
353
+ ])
354
+
355
+ CODE_REGISTER_SOURCE = Mapper([
356
+ ("storage", "ImportFromMyStorage"),
357
+ ("local", "UploadFromLocal"),
358
+ ("git", "ImportFromThirdParty"),
359
+ ])
@@ -0,0 +1,190 @@
1
+ """Training hyperparameter schema — mirrors the backend's HYPERPARAMS_SCHEMA.
2
+
3
+ Keyed by *task type*, not by method: ``fp4-rl`` runs an RL job and therefore
4
+ accepts the RL parameters. (The PRD's table is headed "method=fp8", which would
5
+ list half of them.)
6
+
7
+ Validating locally is not redundant with the backend check — it is what lets
8
+ ``--help`` list the parameters for a task and what turns a 422 into a message
9
+ naming the parameter, its range and the value given.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Mapping
15
+ import json
16
+
17
+ from infix_cli.domain import enums
18
+ from infix_cli.errors import UsageError
19
+
20
+ # name -> (min, max, default)
21
+ SCHEMA: Mapping[str, Mapping[str, tuple[int, int, int]]] = {
22
+ "cpt": {
23
+ "train-iters": (1000, 1_000_000, 5000),
24
+ "lr-warmup-iter": (100, 2000, 500),
25
+ },
26
+ "sft": {
27
+ "num-epoch": (3, 5, 3),
28
+ "rollout-batch-size": (16, 256, 128),
29
+ "global-batch-size": (16, 256, 128),
30
+ },
31
+ "rl": {
32
+ "save-interval": (1, 20, 10),
33
+ "num-rollout": (10, 500, 100),
34
+ "rollout-batch-size": (32, 256, 32),
35
+ "n-samples-per-prompt": (8, 16, 8),
36
+ "rollout-max-response-len": (8192, 32768, 8192),
37
+ "global-batch-size": (128, 2048, 128),
38
+ },
39
+ }
40
+
41
+ # 仅共享 SFT 预设消费;旧预设由服务器在创建记录前明确拒绝扩展参数。
42
+ SHARED_SFT_KEYS = frozenset(
43
+ {
44
+ "num-epoch",
45
+ "epochs",
46
+ "global-batch-size",
47
+ "batch-size",
48
+ "rollout-batch-size",
49
+ "learning-rate",
50
+ "warmup-updates",
51
+ "warmup-init-lr",
52
+ "min-lr",
53
+ "lr-schedule",
54
+ "context-length",
55
+ "save-interval",
56
+ "checkpoint-interval",
57
+ "max-steps",
58
+ "updates",
59
+ "seed",
60
+ "enable-thinking",
61
+ "chat-template-kwargs",
62
+ "topology",
63
+ "training-precision",
64
+ }
65
+ )
66
+
67
+
68
+ def _parse_shared_sft(pairs):
69
+ result = {}
70
+ aliases = {
71
+ "epochs": "num-epoch",
72
+ "batch-size": "global-batch-size",
73
+ "checkpoint-interval": "save-interval",
74
+ "max-steps": "updates",
75
+ }
76
+ for pair in pairs:
77
+ key, separator, raw = pair.partition("=")
78
+ key = key.strip().replace("_", "-")
79
+ if not separator or key not in SHARED_SFT_KEYS or not raw.strip():
80
+ raise UsageError(
81
+ "Unknown hyperparameter or invalid shared SFT parameter: " + key,
82
+ "Available: " + ", ".join(sorted(SHARED_SFT_KEYS)),
83
+ )
84
+ key = aliases.get(key, key)
85
+ if key in result:
86
+ raise UsageError("Duplicate SFT parameter alias: " + key)
87
+ try:
88
+ try:
89
+ value = json.loads(
90
+ raw,
91
+ parse_constant=lambda value: (_ for _ in ()).throw(
92
+ ValueError("non-finite")
93
+ ),
94
+ )
95
+ except json.JSONDecodeError:
96
+ value = raw.strip()
97
+ json.dumps(value, allow_nan=False)
98
+ except (TypeError, ValueError, RecursionError) as exc:
99
+ raise UsageError(
100
+ "SFT parameter values must be finite JSON values."
101
+ ) from exc
102
+ result[key] = value
103
+ return result
104
+
105
+
106
+ def describe(task: str) -> str:
107
+ """One-line summary of what ``--set`` accepts for a task, for --help."""
108
+ schema = SCHEMA.get(task)
109
+ if not schema:
110
+ return "none"
111
+ description = ", ".join(
112
+ f"{name} ({lo}-{hi}, default {default})"
113
+ for name, (lo, hi, default) in schema.items()
114
+ )
115
+ if task == "sft":
116
+ description += "; shared SFT presets also accept: " + ", ".join(
117
+ sorted(SHARED_SFT_KEYS - SCHEMA["sft"].keys())
118
+ )
119
+ return description
120
+
121
+
122
+ def parse(pairs: list[str], *, task: str, method: str) -> dict[str, Any]:
123
+ """Turn repeated ``--set key=value`` flags into a validated payload.
124
+
125
+ Raises UsageError on an unknown key, a non-numeric value, or a value out of
126
+ range — each naming what is allowed instead.
127
+ """
128
+ if not pairs:
129
+ return {}
130
+ if method == "custom":
131
+ # The backend rejects this outright; failing here says why, and says it
132
+ # before the request is built.
133
+ raise UsageError(
134
+ "--set is not supported with --method custom.",
135
+ "Preset methods (fp8, fp4-rl) accept hyperparameters; a custom job "
136
+ "takes them through its own --startup-command.",
137
+ )
138
+
139
+ schema = SCHEMA.get(task)
140
+ if not schema:
141
+ raise UsageError(f'No hyperparameters are defined for task "{task}".')
142
+ if task == "sft" and any(
143
+ pair.partition("=")[0].strip() not in SCHEMA["sft"] for pair in pairs
144
+ ):
145
+ return _parse_shared_sft(pairs)
146
+
147
+ parsed: dict[str, int | float] = {}
148
+ for pair in pairs:
149
+ key, sep, raw = pair.partition("=")
150
+ key, raw = key.strip(), raw.strip()
151
+ if not sep or not key or not raw:
152
+ raise UsageError(
153
+ f'Invalid --set "{pair}".',
154
+ "Use --set key=value, for example --set num-epoch=5.",
155
+ )
156
+ if key not in schema:
157
+ raise UsageError(
158
+ f'Unknown hyperparameter "{key}" for task {task}.',
159
+ f"Available: {', '.join(schema)}.",
160
+ )
161
+ value = _number(key, raw)
162
+ low, high, _default = schema[key]
163
+ if not low <= value <= high:
164
+ raise UsageError(
165
+ f'Hyperparameter "{key}" must be between {low} and {high}, got {value}.',
166
+ )
167
+ parsed[key] = value
168
+ return parsed
169
+
170
+
171
+ def _number(key: str, raw: str) -> int | float:
172
+ try:
173
+ return int(raw)
174
+ except ValueError:
175
+ pass
176
+ try:
177
+ return float(raw)
178
+ except ValueError:
179
+ raise UsageError(
180
+ f'Hyperparameter "{key}" must be a number, got "{raw}".'
181
+ ) from None
182
+
183
+
184
+ def tasks_for_method(method: str) -> tuple[str, ...]:
185
+ """Which task types a method may run (backend VALID_METHODS_BY_TASK_TYPE)."""
186
+ if method == "fp4-rl":
187
+ return ("rl",)
188
+ if method == "fp8":
189
+ return ("cpt", "sft", "rl")
190
+ return tuple(enums.TASK_TYPE.cli_values)
@@ -0,0 +1,108 @@
1
+ """Resource reference parsing: ``official/`` , ``workspace/`` , ``storage/``.
2
+
3
+ Prefixes are mandatory and never inferred (PRD 3.4). ``official/`` and
4
+ ``workspace/`` are separate namespaces in which the same name can exist, so a
5
+ bare name would resolve to whichever the backend happened to return first.
6
+
7
+ The two asset namespaces are named after the scopes they map to, so
8
+ ``--scope workspace`` and the ``workspace/`` prefix stay the same word.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ from infix_cli.errors import UsageError
16
+
17
+ ASSET_KINDS = ("model", "dataset", "code")
18
+ _PREFIXES = ("official/", "workspace/", "storage/")
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class AssetRef:
23
+ """A registered asset: ``workspace/sft-dialogue:v1.0.0`` or ``official/qwen2-7b``."""
24
+
25
+ kind: str
26
+ scope: str # "my" for workspace/, "official" for official/
27
+ name: str
28
+ version: str | None # None means "latest Active version"; official is always None
29
+
30
+ @property
31
+ def is_official(self) -> bool:
32
+ return self.scope == "official"
33
+
34
+ def display(self) -> str:
35
+ prefix = "official" if self.is_official else "workspace"
36
+ suffix = f":{self.version}" if self.version else ""
37
+ return f"{prefix}/{self.name}{suffix}"
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class StorageRef:
42
+ """A raw Workspace Storage path: ``storage/Upload/datasets/train.jsonl``."""
43
+
44
+ path: str
45
+
46
+ def display(self) -> str:
47
+ return f"storage/{self.path}"
48
+
49
+
50
+ Ref = AssetRef | StorageRef
51
+
52
+
53
+ def parse_ref(value: str, *, kind: str, flag: str = "reference") -> Ref:
54
+ """Parse one user-supplied reference.
55
+
56
+ ``kind`` is the asset kind the flag expects (model / dataset / code) and is
57
+ carried into the returned ref so the resolver knows which endpoint to hit.
58
+ """
59
+ if kind not in ASSET_KINDS:
60
+ raise ValueError(f"unknown asset kind: {kind}")
61
+ text = (value or "").strip()
62
+ if not text:
63
+ raise UsageError(f"{flag} is empty.")
64
+
65
+ if not any(text.startswith(p) for p in _PREFIXES):
66
+ raise UsageError(
67
+ f'{flag} "{text}" is missing a prefix.',
68
+ "Use official/<name>, workspace/<name>[:<version>] or storage/<path>.",
69
+ )
70
+
71
+ prefix, _, rest = text.partition("/")
72
+ rest = rest.strip()
73
+ if not rest:
74
+ raise UsageError(f'{flag} "{text}" has an empty {prefix} reference.')
75
+
76
+ if prefix == "storage":
77
+ return StorageRef(path=rest.lstrip("/"))
78
+
79
+ name, sep, version = rest.partition(":")
80
+ name = name.strip()
81
+ version = version.strip()
82
+ if not name:
83
+ raise UsageError(f'{flag} "{text}" has an empty name.')
84
+
85
+ if prefix == "official":
86
+ if sep:
87
+ # Official assets expose only their latest version; silently
88
+ # dropping ":v1" would hide that the pin had no effect.
89
+ raise UsageError(
90
+ f'Official assets have no version selector: "{text}".',
91
+ f"Use official/{name} — the latest official version is always used.",
92
+ )
93
+ return AssetRef(kind=kind, scope="official", name=name, version=None)
94
+
95
+ if sep and not version:
96
+ raise UsageError(f'{flag} "{text}" ends with ":" but names no version.')
97
+ return AssetRef(kind=kind, scope="my", name=name, version=version or None)
98
+
99
+
100
+ def parse_asset_ref(value: str, *, kind: str, flag: str = "reference") -> AssetRef:
101
+ """Same as :func:`parse_ref` but rejects ``storage/`` references."""
102
+ ref = parse_ref(value, kind=kind, flag=flag)
103
+ if isinstance(ref, StorageRef):
104
+ raise UsageError(
105
+ f'{flag} "{value}" must reference a registered asset.',
106
+ "Use official/<name> or workspace/<name>[:<version>].",
107
+ )
108
+ return ref