mind-recursive 0.1.0__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.
- mind_recursive/__init__.py +191 -0
- mind_recursive/_config.py +317 -0
- mind_recursive/_console.py +72 -0
- mind_recursive/_errors.py +213 -0
- mind_recursive/_futures.py +277 -0
- mind_recursive/_proto/__init__.py +23 -0
- mind_recursive/_proto/codec.py +154 -0
- mind_recursive/_proto/decode.py +332 -0
- mind_recursive/_proto/encode.py +163 -0
- mind_recursive/_proto/schema.py +186 -0
- mind_recursive/_protocol.py +316 -0
- mind_recursive/_session.py +217 -0
- mind_recursive/_transport.py +433 -0
- mind_recursive/_version.py +26 -0
- mind_recursive/platform.py +1648 -0
- mind_recursive/reporter.py +335 -0
- mind_recursive/sampler.py +406 -0
- mind_recursive/service.py +1462 -0
- mind_recursive/tinker.py +170 -0
- mind_recursive/trainer.py +1178 -0
- mind_recursive/types.py +640 -0
- mind_recursive/user.py +289 -0
- mind_recursive-0.1.0.dist-info/METADATA +69 -0
- mind_recursive-0.1.0.dist-info/RECORD +26 -0
- mind_recursive-0.1.0.dist-info/WHEEL +4 -0
- mind_recursive-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1648 @@
|
|
|
1
|
+
"""Platform resources: datasets, managed training, executions, model versions.
|
|
2
|
+
|
|
3
|
+
Everything here hangs off :class:`~mind_recursive.user.UserClient` (``uc.datasets``,
|
|
4
|
+
``uc.training``, ...) because none of it needs a training session. The calls go
|
|
5
|
+
to the platform API at ``{origin}/api/mint/cli/v1``.
|
|
6
|
+
|
|
7
|
+
That contract differs from the training planes in three ways, all handled here
|
|
8
|
+
so callers never see them:
|
|
9
|
+
|
|
10
|
+
* **Envelope.** Success is HTTP 200 with ``{"code": 200, "metadata": ...}``;
|
|
11
|
+
a business error is also HTTP 200, with another ``code``. The relay's own
|
|
12
|
+
rejections are ``{"error": {"code", "message"}, "request_id"}`` on a 4xx.
|
|
13
|
+
* **int64 as strings.** protojson writes int64 as ``"123"``; the dataclasses
|
|
14
|
+
below convert them to ``int``.
|
|
15
|
+
* **Retries.** Only GETs and writes carrying an ``Idempotency-Key`` are
|
|
16
|
+
replayed. ``training.submit`` and ``datasets.upload`` generate a key per call
|
|
17
|
+
and reuse it across their own retries; other writes are sent once.
|
|
18
|
+
|
|
19
|
+
Presigned object URLs (dataset upload and download) are fetched with a clean
|
|
20
|
+
client: no ``X-API-Key``, no redirects, and never logged or put in an error.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import tempfile
|
|
29
|
+
import time
|
|
30
|
+
import uuid
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from typing import Any, Generic, Iterator, Mapping, Sequence, TypeVar
|
|
33
|
+
from urllib.parse import quote, urlsplit
|
|
34
|
+
|
|
35
|
+
import httpx
|
|
36
|
+
|
|
37
|
+
from ._config import Config
|
|
38
|
+
from ._errors import (
|
|
39
|
+
APIConnectionError,
|
|
40
|
+
APIError,
|
|
41
|
+
APITimeoutError,
|
|
42
|
+
AuthenticationError,
|
|
43
|
+
ConfigurationError,
|
|
44
|
+
ConflictError,
|
|
45
|
+
FutureTimeoutError,
|
|
46
|
+
MindRecursiveError,
|
|
47
|
+
NotFoundError,
|
|
48
|
+
PermissionDeniedError,
|
|
49
|
+
status_to_error,
|
|
50
|
+
)
|
|
51
|
+
from ._transport import JSON_CONTENT_TYPE, Transport
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"Account",
|
|
55
|
+
"PlatformCapabilities",
|
|
56
|
+
"Page",
|
|
57
|
+
"Dataset",
|
|
58
|
+
"DatasetFinding",
|
|
59
|
+
"ValidationReport",
|
|
60
|
+
"DatasetValidationError",
|
|
61
|
+
"Execution",
|
|
62
|
+
"ExecutionProgress",
|
|
63
|
+
"MetricPoint",
|
|
64
|
+
"MetricsPage",
|
|
65
|
+
"MetricKey",
|
|
66
|
+
"ExecutionArtifact",
|
|
67
|
+
"ExecutionResult",
|
|
68
|
+
"ExecutionEvent",
|
|
69
|
+
"ModelVersion",
|
|
70
|
+
"Deployment",
|
|
71
|
+
"DeploymentError",
|
|
72
|
+
"Datasets",
|
|
73
|
+
"Training",
|
|
74
|
+
"Models",
|
|
75
|
+
"Deployments",
|
|
76
|
+
"Chat",
|
|
77
|
+
"ChatCompletions",
|
|
78
|
+
"ResponseObject",
|
|
79
|
+
"TERMINAL_STATES",
|
|
80
|
+
"DEPLOYMENT_SETTLED_STATES",
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
log = logging.getLogger("mind_recursive.platform")
|
|
84
|
+
|
|
85
|
+
T = TypeVar("T")
|
|
86
|
+
|
|
87
|
+
#: Execution states after which nothing changes any more.
|
|
88
|
+
TERMINAL_STATES = frozenset({"succeeded", "failed", "cancelled"})
|
|
89
|
+
|
|
90
|
+
_CODE_OK = 200
|
|
91
|
+
_CODE_PERMISSION_DENIED = 100015
|
|
92
|
+
_CODE_DATASET_NOT_FOUND = 140056
|
|
93
|
+
_CODE_DATASET_REFERENCED = 140058
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# -- wire helpers -------------------------------------------------------------
|
|
97
|
+
def _int(value: Any) -> int | None:
|
|
98
|
+
"""protojson int64: a string, a number, or absent."""
|
|
99
|
+
if value is None or value == "":
|
|
100
|
+
return None
|
|
101
|
+
return int(value)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _str(value: Any) -> str | None:
|
|
105
|
+
return value if isinstance(value, str) and value != "" else None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _seg(value: str) -> str:
|
|
109
|
+
"""One escaped path segment; a ``/`` in an id must not change the route."""
|
|
110
|
+
if not isinstance(value, str) or not value:
|
|
111
|
+
raise ValueError("resource id must be a non-empty string")
|
|
112
|
+
return quote(value, safe="")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _business_error(code: int, message: str, path: str, status: int) -> APIError:
|
|
116
|
+
"""Map a server business code onto the SDK's exception classes."""
|
|
117
|
+
text = message or f"server error {code}"
|
|
118
|
+
kwargs: dict[str, Any] = {"status": status, "path": path, "code": code}
|
|
119
|
+
if code == _CODE_PERMISSION_DENIED or code == 403:
|
|
120
|
+
return PermissionDeniedError(text, **kwargs)
|
|
121
|
+
if 100000 <= code < 110000:
|
|
122
|
+
return AuthenticationError(text, **kwargs)
|
|
123
|
+
if code == _CODE_DATASET_NOT_FOUND:
|
|
124
|
+
return NotFoundError(text, **kwargs)
|
|
125
|
+
if code == _CODE_DATASET_REFERENCED:
|
|
126
|
+
return ConflictError(text, **kwargs)
|
|
127
|
+
return APIError(text, **kwargs)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# -- data types ---------------------------------------------------------------
|
|
131
|
+
@dataclass
|
|
132
|
+
class Page(Generic[T]):
|
|
133
|
+
"""One page of a list call. ``total`` counts every match, not this page."""
|
|
134
|
+
|
|
135
|
+
items: list[T] = field(default_factory=list)
|
|
136
|
+
total: int | None = None
|
|
137
|
+
|
|
138
|
+
def __iter__(self) -> Iterator[T]:
|
|
139
|
+
return iter(self.items)
|
|
140
|
+
|
|
141
|
+
def __len__(self) -> int:
|
|
142
|
+
return len(self.items)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass
|
|
146
|
+
class Account:
|
|
147
|
+
"""``GET /me``: who the key belongs to, as the server sees it."""
|
|
148
|
+
|
|
149
|
+
user_id: str | None = None
|
|
150
|
+
role: str | None = None
|
|
151
|
+
channel: str | None = None
|
|
152
|
+
admission_create: bool = False
|
|
153
|
+
admission_retry: bool = False
|
|
154
|
+
admission_continue: bool = False
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def from_wire(cls, d: Mapping[str, Any]) -> Account:
|
|
158
|
+
return cls(
|
|
159
|
+
user_id=_str(d.get("user_id")),
|
|
160
|
+
role=_str(d.get("role")),
|
|
161
|
+
channel=_str(d.get("channel")),
|
|
162
|
+
admission_create=bool(d.get("admission_create")),
|
|
163
|
+
admission_retry=bool(d.get("admission_retry")),
|
|
164
|
+
admission_continue=bool(d.get("admission_continue")),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass
|
|
169
|
+
class PlatformCapabilities:
|
|
170
|
+
"""``GET /capabilities``: which platform features this deployment enables."""
|
|
171
|
+
|
|
172
|
+
training: bool = False
|
|
173
|
+
retry: bool = False
|
|
174
|
+
deployment: bool = False
|
|
175
|
+
organization_sharing: bool = False
|
|
176
|
+
evaluate: bool = False
|
|
177
|
+
contract_version: str | None = None
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def from_wire(cls, d: Mapping[str, Any]) -> PlatformCapabilities:
|
|
181
|
+
return cls(
|
|
182
|
+
training=bool(d.get("training")),
|
|
183
|
+
retry=bool(d.get("retry")),
|
|
184
|
+
deployment=bool(d.get("deployment")),
|
|
185
|
+
organization_sharing=bool(d.get("organization_sharing")),
|
|
186
|
+
evaluate=bool(d.get("evaluate")),
|
|
187
|
+
contract_version=_str(d.get("contract_version")),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass
|
|
192
|
+
class Dataset:
|
|
193
|
+
"""One registered dataset version.
|
|
194
|
+
|
|
195
|
+
``status`` is ``uploading`` / ``building`` while the server validates, then
|
|
196
|
+
``available`` or ``failed`` (with ``failure_reason``).
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
dataset_version: str
|
|
200
|
+
type: str | None = None
|
|
201
|
+
status: str | None = None
|
|
202
|
+
failure_reason: str | None = None
|
|
203
|
+
owner_uid: str | None = None
|
|
204
|
+
digest: str | None = None
|
|
205
|
+
size_bytes: int | None = None
|
|
206
|
+
original_filename: str | None = None
|
|
207
|
+
note: str | None = None
|
|
208
|
+
rows: int | None = None
|
|
209
|
+
messages: int | None = None
|
|
210
|
+
assistant_messages: int | None = None
|
|
211
|
+
tool_calls: int | None = None
|
|
212
|
+
max_messages: int | None = None
|
|
213
|
+
#: Milliseconds since the epoch.
|
|
214
|
+
created_at: int | None = None
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def available(self) -> bool:
|
|
218
|
+
return self.status == "available"
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def from_wire(cls, d: Mapping[str, Any]) -> Dataset:
|
|
222
|
+
return cls(
|
|
223
|
+
dataset_version=d.get("dataset_version") or "",
|
|
224
|
+
type=_str(d.get("type")),
|
|
225
|
+
status=_str(d.get("status")),
|
|
226
|
+
failure_reason=_str(d.get("failure_reason")),
|
|
227
|
+
owner_uid=_str(d.get("owner_uid")),
|
|
228
|
+
digest=_str(d.get("digest")),
|
|
229
|
+
size_bytes=_int(d.get("size_bytes")),
|
|
230
|
+
original_filename=_str(d.get("original_filename")),
|
|
231
|
+
note=_str(d.get("note")),
|
|
232
|
+
rows=_int(d.get("rows")),
|
|
233
|
+
messages=_int(d.get("messages")),
|
|
234
|
+
assistant_messages=_int(d.get("assistant_messages")),
|
|
235
|
+
tool_calls=_int(d.get("tool_calls")),
|
|
236
|
+
max_messages=_int(d.get("max_messages")),
|
|
237
|
+
created_at=_int(d.get("created_at")),
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@dataclass
|
|
242
|
+
class DatasetFinding:
|
|
243
|
+
"""One validation finding. ``severity`` is ``fatal`` or ``warn``."""
|
|
244
|
+
|
|
245
|
+
severity: str | None = None
|
|
246
|
+
layer: str | None = None
|
|
247
|
+
rule: str | None = None
|
|
248
|
+
line: int | None = None
|
|
249
|
+
problem_id: str | None = None
|
|
250
|
+
detail: str | None = None
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def from_wire(cls, d: Mapping[str, Any]) -> DatasetFinding:
|
|
254
|
+
return cls(
|
|
255
|
+
severity=_str(d.get("severity")),
|
|
256
|
+
layer=_str(d.get("layer")),
|
|
257
|
+
rule=_str(d.get("rule")),
|
|
258
|
+
line=_int(d.get("line")),
|
|
259
|
+
problem_id=_str(d.get("problem_id")),
|
|
260
|
+
detail=_str(d.get("detail")),
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@dataclass
|
|
265
|
+
class ValidationReport:
|
|
266
|
+
"""The persisted validation report of a dataset, one page of findings."""
|
|
267
|
+
|
|
268
|
+
dataset_version: str
|
|
269
|
+
status: str | None = None
|
|
270
|
+
validator_revision: str | None = None
|
|
271
|
+
findings: list[DatasetFinding] = field(default_factory=list)
|
|
272
|
+
fatal_count: int = 0
|
|
273
|
+
warn_count: int = 0
|
|
274
|
+
total: int = 0
|
|
275
|
+
|
|
276
|
+
@classmethod
|
|
277
|
+
def from_wire(cls, d: Mapping[str, Any]) -> ValidationReport:
|
|
278
|
+
return cls(
|
|
279
|
+
dataset_version=d.get("dataset_version") or "",
|
|
280
|
+
status=_str(d.get("status")),
|
|
281
|
+
validator_revision=_str(d.get("validator_revision")),
|
|
282
|
+
findings=[DatasetFinding.from_wire(f) for f in d.get("findings") or []],
|
|
283
|
+
fatal_count=_int(d.get("fatal_count")) or 0,
|
|
284
|
+
warn_count=_int(d.get("warn_count")) or 0,
|
|
285
|
+
total=_int(d.get("total")) or 0,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class DatasetValidationError(MindRecursiveError):
|
|
290
|
+
"""An uploaded dataset finished validation as ``failed``.
|
|
291
|
+
|
|
292
|
+
``dataset`` carries the server's record, including ``failure_reason``. Use
|
|
293
|
+
``uc.datasets.validation_report(version)`` for the per-line findings.
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
def __init__(self, dataset: Dataset):
|
|
297
|
+
reason = dataset.failure_reason or "validation failed"
|
|
298
|
+
super().__init__(f"dataset {dataset.dataset_version} failed: {reason}")
|
|
299
|
+
self.dataset = dataset
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
@dataclass
|
|
303
|
+
class ExecutionProgress:
|
|
304
|
+
"""The latest progress snapshot embedded in an execution."""
|
|
305
|
+
|
|
306
|
+
step: int | None = None
|
|
307
|
+
total: int | None = None
|
|
308
|
+
loss: str | None = None
|
|
309
|
+
stage: str | None = None
|
|
310
|
+
updated_at: int | None = None
|
|
311
|
+
|
|
312
|
+
@classmethod
|
|
313
|
+
def from_wire(cls, d: Mapping[str, Any] | None) -> ExecutionProgress | None:
|
|
314
|
+
if not d:
|
|
315
|
+
return None
|
|
316
|
+
return cls(
|
|
317
|
+
step=_int(d.get("step")),
|
|
318
|
+
total=_int(d.get("total")),
|
|
319
|
+
loss=_str(d.get("loss")),
|
|
320
|
+
stage=_str(d.get("stage")),
|
|
321
|
+
updated_at=_int(d.get("updated_at")),
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
@dataclass
|
|
326
|
+
class Execution:
|
|
327
|
+
"""One managed job (training run). ``state`` is the scheduler's truth.
|
|
328
|
+
|
|
329
|
+
``version_id`` is set once a training run has registered its output model
|
|
330
|
+
version; pass it to ``uc.models.get`` or ``uc.deployments.create``.
|
|
331
|
+
"""
|
|
332
|
+
|
|
333
|
+
execution_id: str
|
|
334
|
+
kind: str | None = None
|
|
335
|
+
state: str | None = None
|
|
336
|
+
display_name: str | None = None
|
|
337
|
+
owner_uid: str | None = None
|
|
338
|
+
cancel_requested: bool = False
|
|
339
|
+
result_reason: str | None = None
|
|
340
|
+
result_exit_code: int | None = None
|
|
341
|
+
submitted_at: int | None = None
|
|
342
|
+
started_at: int | None = None
|
|
343
|
+
finished_at: int | None = None
|
|
344
|
+
updated_at: int | None = None
|
|
345
|
+
progress: ExecutionProgress | None = None
|
|
346
|
+
dataset_version: str | None = None
|
|
347
|
+
base_model: str | None = None
|
|
348
|
+
retry_of: str | None = None
|
|
349
|
+
output_registration: str | None = None
|
|
350
|
+
train_kind: str | None = None
|
|
351
|
+
package_version: str | None = None
|
|
352
|
+
version_id: str | None = None
|
|
353
|
+
base_version_id: str | None = None
|
|
354
|
+
admission_status: str | None = None
|
|
355
|
+
#: The full server record, for fields not named above (``history`` etc.).
|
|
356
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
357
|
+
|
|
358
|
+
@property
|
|
359
|
+
def terminal(self) -> bool:
|
|
360
|
+
return self.state in TERMINAL_STATES
|
|
361
|
+
|
|
362
|
+
@classmethod
|
|
363
|
+
def from_wire(cls, d: Mapping[str, Any]) -> Execution:
|
|
364
|
+
return cls(
|
|
365
|
+
execution_id=d.get("execution_id") or "",
|
|
366
|
+
kind=_str(d.get("kind")),
|
|
367
|
+
state=_str(d.get("state")),
|
|
368
|
+
display_name=_str(d.get("display_name")),
|
|
369
|
+
owner_uid=_str(d.get("owner_uid")),
|
|
370
|
+
cancel_requested=bool(d.get("cancel_requested")),
|
|
371
|
+
result_reason=_str(d.get("result_reason")),
|
|
372
|
+
result_exit_code=_int(d.get("result_exit_code")),
|
|
373
|
+
submitted_at=_int(d.get("submitted_at")),
|
|
374
|
+
started_at=_int(d.get("started_at")),
|
|
375
|
+
finished_at=_int(d.get("finished_at")),
|
|
376
|
+
updated_at=_int(d.get("updated_at")),
|
|
377
|
+
progress=ExecutionProgress.from_wire(d.get("progress")),
|
|
378
|
+
dataset_version=_str(d.get("dataset_version")),
|
|
379
|
+
base_model=_str(d.get("base_model")),
|
|
380
|
+
retry_of=_str(d.get("retry_of")),
|
|
381
|
+
output_registration=_str(d.get("output_registration")),
|
|
382
|
+
train_kind=_str(d.get("frozen_train_kind")),
|
|
383
|
+
package_version=_str(d.get("frozen_package_version")),
|
|
384
|
+
version_id=_str(d.get("version_id")),
|
|
385
|
+
base_version_id=_str(d.get("base_version_id")),
|
|
386
|
+
admission_status=_str(d.get("admission_status")),
|
|
387
|
+
raw=dict(d),
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@dataclass
|
|
392
|
+
class MetricPoint:
|
|
393
|
+
"""One reported metric row. ``metrics`` values are kept as sent."""
|
|
394
|
+
|
|
395
|
+
ts: int | None = None
|
|
396
|
+
stage: str | None = None
|
|
397
|
+
step: int | None = None
|
|
398
|
+
total: int | None = None
|
|
399
|
+
loss: str | None = None
|
|
400
|
+
metrics: dict[str, Any] = field(default_factory=dict)
|
|
401
|
+
|
|
402
|
+
@classmethod
|
|
403
|
+
def from_wire(cls, d: Mapping[str, Any]) -> MetricPoint:
|
|
404
|
+
return cls(
|
|
405
|
+
ts=_int(d.get("ts")),
|
|
406
|
+
stage=_str(d.get("stage")),
|
|
407
|
+
step=_int(d.get("step")),
|
|
408
|
+
total=_int(d.get("total")),
|
|
409
|
+
loss=_str(d.get("loss")),
|
|
410
|
+
metrics=dict(d.get("metrics") or {}),
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@dataclass
|
|
415
|
+
class MetricsPage:
|
|
416
|
+
"""One page of metrics.
|
|
417
|
+
|
|
418
|
+
``caught_up`` means "no more rows right now", not "the run has finished";
|
|
419
|
+
keep ``next_cursor`` and poll again while the execution is running.
|
|
420
|
+
"""
|
|
421
|
+
|
|
422
|
+
points: list[MetricPoint] = field(default_factory=list)
|
|
423
|
+
next_cursor: str | None = None
|
|
424
|
+
caught_up: bool = False
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@dataclass
|
|
428
|
+
class MetricKey:
|
|
429
|
+
key: str
|
|
430
|
+
type: str | None = None
|
|
431
|
+
kind: str | None = None
|
|
432
|
+
first_step: int | None = None
|
|
433
|
+
last_step: int | None = None
|
|
434
|
+
|
|
435
|
+
@classmethod
|
|
436
|
+
def from_wire(cls, d: Mapping[str, Any]) -> MetricKey:
|
|
437
|
+
return cls(
|
|
438
|
+
key=d.get("key") or "",
|
|
439
|
+
type=_str(d.get("type")),
|
|
440
|
+
kind=_str(d.get("kind")),
|
|
441
|
+
first_step=_int(d.get("first_step")),
|
|
442
|
+
last_step=_int(d.get("last_step")),
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
@dataclass
|
|
447
|
+
class ExecutionArtifact:
|
|
448
|
+
type: str | None = None
|
|
449
|
+
uri: str | None = None
|
|
450
|
+
name: str | None = None
|
|
451
|
+
version: str | None = None
|
|
452
|
+
description: str | None = None
|
|
453
|
+
metadata: Any = None
|
|
454
|
+
ts: int | None = None
|
|
455
|
+
|
|
456
|
+
@classmethod
|
|
457
|
+
def from_wire(cls, d: Mapping[str, Any]) -> ExecutionArtifact:
|
|
458
|
+
return cls(
|
|
459
|
+
type=_str(d.get("type")),
|
|
460
|
+
uri=_str(d.get("uri")),
|
|
461
|
+
name=_str(d.get("name")),
|
|
462
|
+
version=_str(d.get("version")),
|
|
463
|
+
description=_str(d.get("description")),
|
|
464
|
+
metadata=d.get("metadata"),
|
|
465
|
+
ts=_int(d.get("ts")),
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@dataclass
|
|
470
|
+
class ExecutionResult:
|
|
471
|
+
"""What the algorithm reported: artifacts, summary, error.
|
|
472
|
+
|
|
473
|
+
``status`` is the algorithm's own report and does not replace
|
|
474
|
+
:attr:`Execution.state`.
|
|
475
|
+
"""
|
|
476
|
+
|
|
477
|
+
status: str | None = None
|
|
478
|
+
artifacts: list[ExecutionArtifact] = field(default_factory=list)
|
|
479
|
+
data_summary: Any = None
|
|
480
|
+
error_code: str | None = None
|
|
481
|
+
error_message: str | None = None
|
|
482
|
+
sealed: bool = False
|
|
483
|
+
stage: str | None = None
|
|
484
|
+
step: int | None = None
|
|
485
|
+
total: int | None = None
|
|
486
|
+
last_event_at: int | None = None
|
|
487
|
+
source: str | None = None
|
|
488
|
+
|
|
489
|
+
@classmethod
|
|
490
|
+
def from_wire(cls, d: Mapping[str, Any]) -> ExecutionResult:
|
|
491
|
+
return cls(
|
|
492
|
+
status=_str(d.get("status")),
|
|
493
|
+
artifacts=[ExecutionArtifact.from_wire(a) for a in d.get("artifacts") or []],
|
|
494
|
+
data_summary=d.get("data_summary"),
|
|
495
|
+
error_code=_str(d.get("error_code")),
|
|
496
|
+
error_message=_str(d.get("error_message")),
|
|
497
|
+
sealed=bool(d.get("sealed")),
|
|
498
|
+
stage=_str(d.get("stage")),
|
|
499
|
+
step=_int(d.get("step")),
|
|
500
|
+
total=_int(d.get("total")),
|
|
501
|
+
last_event_at=_int(d.get("last_event_at")),
|
|
502
|
+
source=_str(d.get("source")),
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
@dataclass
|
|
507
|
+
class ExecutionEvent:
|
|
508
|
+
"""One structured event. ``data_json`` stays a JSON string, as sent."""
|
|
509
|
+
|
|
510
|
+
id: str | None = None
|
|
511
|
+
seq: int | None = None
|
|
512
|
+
ts: int | None = None
|
|
513
|
+
type: str | None = None
|
|
514
|
+
level: str | None = None
|
|
515
|
+
code: str | None = None
|
|
516
|
+
message: str | None = None
|
|
517
|
+
data_json: str | None = None
|
|
518
|
+
received_at: int | None = None
|
|
519
|
+
|
|
520
|
+
@classmethod
|
|
521
|
+
def from_wire(cls, d: Mapping[str, Any]) -> ExecutionEvent:
|
|
522
|
+
return cls(
|
|
523
|
+
id=_str(d.get("id")),
|
|
524
|
+
seq=_int(d.get("seq")),
|
|
525
|
+
ts=_int(d.get("ts")),
|
|
526
|
+
type=_str(d.get("type")),
|
|
527
|
+
level=_str(d.get("level")),
|
|
528
|
+
code=_str(d.get("code")),
|
|
529
|
+
message=_str(d.get("message")),
|
|
530
|
+
data_json=_str(d.get("data_json")),
|
|
531
|
+
received_at=_int(d.get("received_at")),
|
|
532
|
+
)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
@dataclass
|
|
536
|
+
class ModelVersion:
|
|
537
|
+
"""A registered model version (the output of a managed training run)."""
|
|
538
|
+
|
|
539
|
+
version_id: str
|
|
540
|
+
owner_uid: str | None = None
|
|
541
|
+
execution_id: str | None = None
|
|
542
|
+
train_kind: str | None = None
|
|
543
|
+
dataset_version: str | None = None
|
|
544
|
+
train_data_rows: int | None = None
|
|
545
|
+
package_version: str | None = None
|
|
546
|
+
parent_id: str | None = None
|
|
547
|
+
base_model: str | None = None
|
|
548
|
+
base_model_revision: str | None = None
|
|
549
|
+
#: Training upstream frozen on the version: ``mint`` or ``tinker``.
|
|
550
|
+
upstream: str | None = None
|
|
551
|
+
created_at: int | None = None
|
|
552
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
553
|
+
|
|
554
|
+
@classmethod
|
|
555
|
+
def from_wire(cls, d: Mapping[str, Any]) -> ModelVersion:
|
|
556
|
+
return cls(
|
|
557
|
+
version_id=d.get("version_id") or "",
|
|
558
|
+
owner_uid=_str(d.get("owner_uid")),
|
|
559
|
+
execution_id=_str(d.get("execution_id")),
|
|
560
|
+
train_kind=_str(d.get("train_kind")),
|
|
561
|
+
dataset_version=_str(d.get("dataset_version")),
|
|
562
|
+
train_data_rows=_int(d.get("train_data_rows")),
|
|
563
|
+
package_version=_str(d.get("package_version")),
|
|
564
|
+
parent_id=_str(d.get("parent_id")),
|
|
565
|
+
base_model=_str(d.get("base_model")),
|
|
566
|
+
base_model_revision=_str(d.get("base_model_revision")),
|
|
567
|
+
upstream=_str(d.get("upstream")),
|
|
568
|
+
created_at=_int(d.get("created_at")),
|
|
569
|
+
raw=dict(d),
|
|
570
|
+
)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
# -- request layer ------------------------------------------------------------
|
|
574
|
+
class _Platform:
|
|
575
|
+
"""Calls against the CLI entry: envelope unwrapping and error mapping.
|
|
576
|
+
|
|
577
|
+
Reuses the owning client's :class:`Transport` (same key header, pools and
|
|
578
|
+
connection-fault retries). HTTP status retries are left to the transport,
|
|
579
|
+
except that non-idempotent writes get ``max_retries=0`` so a lost response
|
|
580
|
+
cannot submit twice.
|
|
581
|
+
"""
|
|
582
|
+
|
|
583
|
+
def __init__(self, config: Config, transport: Transport, owner: Any = None) -> None:
|
|
584
|
+
self._config = config
|
|
585
|
+
self._transport = transport
|
|
586
|
+
self._owner = owner
|
|
587
|
+
|
|
588
|
+
@property
|
|
589
|
+
def base_url(self) -> str:
|
|
590
|
+
if not self._config.platform_base_url:
|
|
591
|
+
raise ConfigurationError(
|
|
592
|
+
"this Config has no platform_base_url; build it with build_config()"
|
|
593
|
+
)
|
|
594
|
+
return self._config.platform_base_url
|
|
595
|
+
|
|
596
|
+
def call(
|
|
597
|
+
self,
|
|
598
|
+
method: str,
|
|
599
|
+
path: str,
|
|
600
|
+
*,
|
|
601
|
+
params: Mapping[str, Any] | None = None,
|
|
602
|
+
json_body: Any | None = None,
|
|
603
|
+
idempotency_key: str | None = None,
|
|
604
|
+
timeout: float | None = None,
|
|
605
|
+
) -> Any:
|
|
606
|
+
"""Send one request and return the envelope's ``metadata``."""
|
|
607
|
+
if getattr(self._owner, "_closed", False):
|
|
608
|
+
raise ConfigurationError("this UserClient has been closed")
|
|
609
|
+
replayable = method == "GET" or idempotency_key is not None
|
|
610
|
+
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
|
|
611
|
+
query = {k: v for k, v in (params or {}).items() if v is not None and v != ""}
|
|
612
|
+
try:
|
|
613
|
+
response = self._transport.request(
|
|
614
|
+
method,
|
|
615
|
+
path,
|
|
616
|
+
base_url=self.base_url,
|
|
617
|
+
json_body=json_body,
|
|
618
|
+
params=query or None,
|
|
619
|
+
accept=JSON_CONTENT_TYPE,
|
|
620
|
+
extra_headers=headers,
|
|
621
|
+
timeout=timeout,
|
|
622
|
+
max_retries=None if replayable else 0,
|
|
623
|
+
)
|
|
624
|
+
except APIError as exc:
|
|
625
|
+
raise _entry_error(exc, path) from exc
|
|
626
|
+
return _unwrap(response, path)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _entry_error(exc: APIError, path: str) -> APIError:
|
|
630
|
+
"""Re-read a 4xx raised by the transport as a relay entry rejection.
|
|
631
|
+
|
|
632
|
+
The relay answers ``{"error": {"code": "...", "message": "..."}}``; the
|
|
633
|
+
transport only looks for a string ``error``, so the code would be lost.
|
|
634
|
+
"""
|
|
635
|
+
if not exc.body:
|
|
636
|
+
return exc
|
|
637
|
+
try:
|
|
638
|
+
payload = json.loads(exc.body.decode("utf-8"))
|
|
639
|
+
except (ValueError, UnicodeDecodeError):
|
|
640
|
+
return exc
|
|
641
|
+
if not isinstance(payload, dict):
|
|
642
|
+
return exc
|
|
643
|
+
err = payload.get("error")
|
|
644
|
+
if isinstance(err, dict) and isinstance(err.get("code"), str):
|
|
645
|
+
code = err["code"]
|
|
646
|
+
message = err.get("message") or code
|
|
647
|
+
cls = type(exc)
|
|
648
|
+
if code.startswith("credential_"):
|
|
649
|
+
cls = AuthenticationError
|
|
650
|
+
elif code in ("access_forbidden", "admission_denied"):
|
|
651
|
+
cls = PermissionDeniedError
|
|
652
|
+
elif code == "route_not_allowed":
|
|
653
|
+
message = (
|
|
654
|
+
f"{message} -- the relay CLI entry does not expose {path}"
|
|
655
|
+
)
|
|
656
|
+
return cls(
|
|
657
|
+
f"{code}: {message}",
|
|
658
|
+
status=exc.status,
|
|
659
|
+
path=path,
|
|
660
|
+
body=exc.body,
|
|
661
|
+
code=code,
|
|
662
|
+
request_id=_str(payload.get("request_id")),
|
|
663
|
+
)
|
|
664
|
+
if isinstance(payload.get("code"), int) and payload["code"] != _CODE_OK:
|
|
665
|
+
return _business_error(
|
|
666
|
+
payload["code"], str(payload.get("message") or ""), path, exc.status or 0
|
|
667
|
+
)
|
|
668
|
+
return exc
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _unwrap(response: httpx.Response, path: str) -> Any:
|
|
672
|
+
try:
|
|
673
|
+
payload = response.json()
|
|
674
|
+
except ValueError as exc:
|
|
675
|
+
raise APIError(
|
|
676
|
+
f"non-JSON response from the CLI entry (HTTP {response.status_code})",
|
|
677
|
+
status=response.status_code,
|
|
678
|
+
path=path,
|
|
679
|
+
) from exc
|
|
680
|
+
if not isinstance(payload, dict) or "code" not in payload:
|
|
681
|
+
raise APIError(
|
|
682
|
+
"response is not a {code, message, metadata} envelope; check that "
|
|
683
|
+
"base_url is the relay origin",
|
|
684
|
+
status=response.status_code,
|
|
685
|
+
path=path,
|
|
686
|
+
)
|
|
687
|
+
code = payload.get("code")
|
|
688
|
+
if code != _CODE_OK:
|
|
689
|
+
raise _business_error(
|
|
690
|
+
int(code) if isinstance(code, (int, str)) and str(code).isdigit() else -1,
|
|
691
|
+
str(payload.get("message") or ""),
|
|
692
|
+
path,
|
|
693
|
+
response.status_code,
|
|
694
|
+
)
|
|
695
|
+
return payload.get("metadata")
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _obj(value: Any, path: str) -> dict[str, Any]:
|
|
699
|
+
if value is None:
|
|
700
|
+
return {}
|
|
701
|
+
if not isinstance(value, dict):
|
|
702
|
+
raise APIError(f"expected an object in metadata, got {type(value).__name__}", path=path)
|
|
703
|
+
return value
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _clean_http(config: Config, *, timeout: float | None) -> httpx.Client:
|
|
707
|
+
"""A client for presigned object URLs: no credentials, no redirects."""
|
|
708
|
+
return httpx.Client(
|
|
709
|
+
timeout=httpx.Timeout(timeout, connect=config.connect_timeout),
|
|
710
|
+
trust_env=config.trust_env,
|
|
711
|
+
follow_redirects=False,
|
|
712
|
+
)
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _check_presigned(url: Any) -> str:
|
|
716
|
+
if not isinstance(url, str):
|
|
717
|
+
raise APIError("server returned no object URL")
|
|
718
|
+
parts = urlsplit(url)
|
|
719
|
+
if parts.scheme not in ("http", "https") or not parts.hostname or parts.username:
|
|
720
|
+
# Never echo the URL itself: it carries a signature.
|
|
721
|
+
raise APIError("server returned an invalid object URL")
|
|
722
|
+
return url
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
# -- resources ----------------------------------------------------------------
|
|
726
|
+
class Datasets:
|
|
727
|
+
"""``uc.datasets``: upload, inspect, download and delete datasets.
|
|
728
|
+
|
|
729
|
+
Example::
|
|
730
|
+
|
|
731
|
+
ds = uc.datasets.upload("train.jsonl", type="sft", note="v1")
|
|
732
|
+
print(ds.dataset_version, ds.rows)
|
|
733
|
+
uc.datasets.download(ds.dataset_version, "copy.jsonl")
|
|
734
|
+
"""
|
|
735
|
+
|
|
736
|
+
def __init__(self, api: _Platform) -> None:
|
|
737
|
+
self._api = api
|
|
738
|
+
|
|
739
|
+
def list(
|
|
740
|
+
self, *, type: str | None = None, page: int | None = None, page_size: int | None = None
|
|
741
|
+
) -> Page[Dataset]:
|
|
742
|
+
"""Your datasets, newest first. ``type`` filters to ``sft`` or ``grpo``."""
|
|
743
|
+
path = "/datasets"
|
|
744
|
+
d = _obj(
|
|
745
|
+
self._api.call("GET", path, params={"type": type, "page": page, "page_size": page_size}),
|
|
746
|
+
path,
|
|
747
|
+
)
|
|
748
|
+
return Page([Dataset.from_wire(x) for x in d.get("list") or []], _int(d.get("total")))
|
|
749
|
+
|
|
750
|
+
def get(self, dataset_version: str, *, owner_uid: str | None = None) -> Dataset:
|
|
751
|
+
"""One dataset. ``owner_uid`` reads a dataset shared with you."""
|
|
752
|
+
path = f"/datasets/{_seg(dataset_version)}"
|
|
753
|
+
return Dataset.from_wire(
|
|
754
|
+
_obj(self._api.call("GET", path, params={"owner_uid": owner_uid}), path)
|
|
755
|
+
)
|
|
756
|
+
|
|
757
|
+
def rows(
|
|
758
|
+
self,
|
|
759
|
+
dataset_version: str,
|
|
760
|
+
*,
|
|
761
|
+
offset: int | None = None,
|
|
762
|
+
limit: int | None = None,
|
|
763
|
+
owner_uid: str | None = None,
|
|
764
|
+
) -> list[Any]:
|
|
765
|
+
"""A slice of the dataset's rows, each as the decoded JSON object."""
|
|
766
|
+
path = f"/datasets/{_seg(dataset_version)}/rows"
|
|
767
|
+
d = _obj(
|
|
768
|
+
self._api.call(
|
|
769
|
+
"GET", path, params={"offset": offset, "limit": limit, "owner_uid": owner_uid}
|
|
770
|
+
),
|
|
771
|
+
path,
|
|
772
|
+
)
|
|
773
|
+
return list(d.get("rows") or [])
|
|
774
|
+
|
|
775
|
+
def validation_report(
|
|
776
|
+
self,
|
|
777
|
+
dataset_version: str,
|
|
778
|
+
*,
|
|
779
|
+
offset: int | None = None,
|
|
780
|
+
limit: int | None = None,
|
|
781
|
+
owner_uid: str | None = None,
|
|
782
|
+
) -> ValidationReport:
|
|
783
|
+
"""The persisted validation findings, one page at a time."""
|
|
784
|
+
path = f"/datasets/{_seg(dataset_version)}/validation-report"
|
|
785
|
+
d = _obj(
|
|
786
|
+
self._api.call(
|
|
787
|
+
"GET", path, params={"offset": offset, "limit": limit, "owner_uid": owner_uid}
|
|
788
|
+
),
|
|
789
|
+
path,
|
|
790
|
+
)
|
|
791
|
+
return ValidationReport.from_wire(d)
|
|
792
|
+
|
|
793
|
+
def update_note(self, dataset_version: str, note: str) -> Dataset:
|
|
794
|
+
"""Change the note (at most 80 characters). Nothing else is editable."""
|
|
795
|
+
path = f"/datasets/{_seg(dataset_version)}"
|
|
796
|
+
return Dataset.from_wire(
|
|
797
|
+
_obj(self._api.call("PATCH", path, json_body={"note": note}), path)
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
def delete(self, dataset_version: str) -> None:
|
|
801
|
+
"""Delete a dataset. Raises :class:`ConflictError` while a run uses it."""
|
|
802
|
+
self._api.call("DELETE", f"/datasets/{_seg(dataset_version)}")
|
|
803
|
+
|
|
804
|
+
def upload(
|
|
805
|
+
self,
|
|
806
|
+
file: str | os.PathLike[str],
|
|
807
|
+
*,
|
|
808
|
+
type: str = "sft",
|
|
809
|
+
dataset_version: str | None = None,
|
|
810
|
+
note: str | None = None,
|
|
811
|
+
idempotency_key: str | None = None,
|
|
812
|
+
wait: bool = True,
|
|
813
|
+
timeout: float = 600.0,
|
|
814
|
+
poll_interval: float = 1.0,
|
|
815
|
+
) -> Dataset:
|
|
816
|
+
"""Upload a local JSONL file and register it as a dataset.
|
|
817
|
+
|
|
818
|
+
Three steps, as the CLI does them: register the upload intent, PUT the
|
|
819
|
+
file straight to object storage with the returned presigned URL, then
|
|
820
|
+
tell the server it is in place. The server validates in the background;
|
|
821
|
+
with ``wait=True`` (the default) this polls until the dataset is
|
|
822
|
+
``available`` and raises :class:`DatasetValidationError` if it ends
|
|
823
|
+
``failed``.
|
|
824
|
+
|
|
825
|
+
Args:
|
|
826
|
+
file: local path.
|
|
827
|
+
type: ``sft`` or ``grpo``.
|
|
828
|
+
dataset_version: your own version name; the server picks one if omitted.
|
|
829
|
+
note: free-text note.
|
|
830
|
+
idempotency_key: reuse to retry the *same* upload safely. A fresh
|
|
831
|
+
key is generated per call when omitted.
|
|
832
|
+
wait: poll until validation finishes.
|
|
833
|
+
timeout: seconds to wait for validation.
|
|
834
|
+
poll_interval: initial poll interval; doubles up to 30s.
|
|
835
|
+
"""
|
|
836
|
+
path_str = os.fspath(file)
|
|
837
|
+
size = os.path.getsize(path_str)
|
|
838
|
+
key = idempotency_key or f"sdk-{uuid.uuid4()}"
|
|
839
|
+
intent_path = "/datasets/uploads"
|
|
840
|
+
intent = _obj(
|
|
841
|
+
self._api.call(
|
|
842
|
+
"POST",
|
|
843
|
+
intent_path,
|
|
844
|
+
json_body={
|
|
845
|
+
"type": type,
|
|
846
|
+
"dataset_version": dataset_version or "",
|
|
847
|
+
"note": note or "",
|
|
848
|
+
"original_filename": os.path.basename(path_str),
|
|
849
|
+
},
|
|
850
|
+
idempotency_key=key,
|
|
851
|
+
),
|
|
852
|
+
intent_path,
|
|
853
|
+
)
|
|
854
|
+
version = intent.get("dataset_version") or ""
|
|
855
|
+
if not version:
|
|
856
|
+
raise APIError("upload intent returned no dataset_version", path=intent_path)
|
|
857
|
+
target = intent.get("upload")
|
|
858
|
+
max_bytes = _int(intent.get("max_bytes"))
|
|
859
|
+
if target:
|
|
860
|
+
if max_bytes and size > max_bytes:
|
|
861
|
+
raise ConfigurationError(
|
|
862
|
+
f"{path_str} is {size} bytes; the server accepts at most {max_bytes}"
|
|
863
|
+
)
|
|
864
|
+
self._put_object(target, path_str, size)
|
|
865
|
+
complete = f"/datasets/{_seg(version)}/upload-complete"
|
|
866
|
+
self._api.call(
|
|
867
|
+
"POST",
|
|
868
|
+
complete,
|
|
869
|
+
json_body={"dataset_version": version, "size": size},
|
|
870
|
+
idempotency_key=f"{key}-complete",
|
|
871
|
+
)
|
|
872
|
+
# No target: this key's intent was already consumed (a retried upload);
|
|
873
|
+
# the dataset exists, so only its status is left to read.
|
|
874
|
+
if not wait:
|
|
875
|
+
return self.get(version)
|
|
876
|
+
return self.wait(version, timeout=timeout, poll_interval=poll_interval)
|
|
877
|
+
|
|
878
|
+
def wait(
|
|
879
|
+
self, dataset_version: str, *, timeout: float = 600.0, poll_interval: float = 1.0
|
|
880
|
+
) -> Dataset:
|
|
881
|
+
"""Poll until validation finishes. Raises on ``failed`` or timeout."""
|
|
882
|
+
deadline = time.monotonic() + timeout
|
|
883
|
+
delay = max(poll_interval, 0.05)
|
|
884
|
+
while True:
|
|
885
|
+
ds = self.get(dataset_version)
|
|
886
|
+
if ds.status == "available":
|
|
887
|
+
return ds
|
|
888
|
+
if ds.status == "failed":
|
|
889
|
+
raise DatasetValidationError(ds)
|
|
890
|
+
if time.monotonic() >= deadline:
|
|
891
|
+
raise FutureTimeoutError(dataset_version, timeout, ds.status)
|
|
892
|
+
time.sleep(min(delay, max(deadline - time.monotonic(), 0)))
|
|
893
|
+
delay = min(delay * 2, 30.0)
|
|
894
|
+
|
|
895
|
+
def download(
|
|
896
|
+
self, dataset_version: str, destination: str | os.PathLike[str], *, timeout: float = 600.0
|
|
897
|
+
) -> str:
|
|
898
|
+
"""Download an ``available`` dataset to a local file.
|
|
899
|
+
|
|
900
|
+
Refuses to overwrite an existing path. Writes to a temporary file in the
|
|
901
|
+
same directory and links it into place, so a failed transfer leaves
|
|
902
|
+
nothing behind. Returns the destination path.
|
|
903
|
+
"""
|
|
904
|
+
dest = os.fspath(destination)
|
|
905
|
+
if os.path.lexists(dest):
|
|
906
|
+
raise FileExistsError(f"download destination already exists: {dest}")
|
|
907
|
+
path = f"/datasets/{_seg(dataset_version)}/download-url"
|
|
908
|
+
d = _obj(self._api.call("GET", path), path)
|
|
909
|
+
url = _check_presigned(d.get("url"))
|
|
910
|
+
|
|
911
|
+
directory = os.path.dirname(os.path.abspath(dest))
|
|
912
|
+
fd, tmp = tempfile.mkstemp(prefix=".mind-recursive-dataset-", dir=directory)
|
|
913
|
+
try:
|
|
914
|
+
with os.fdopen(fd, "wb") as out, _clean_http(
|
|
915
|
+
self._api._config, timeout=timeout
|
|
916
|
+
) as http:
|
|
917
|
+
try:
|
|
918
|
+
with http.stream("GET", url) as resp:
|
|
919
|
+
if resp.status_code != 200:
|
|
920
|
+
raise APIError(
|
|
921
|
+
f"object download returned HTTP {resp.status_code}",
|
|
922
|
+
status=resp.status_code,
|
|
923
|
+
path=path,
|
|
924
|
+
)
|
|
925
|
+
expected = resp.headers.get("Content-Length")
|
|
926
|
+
written = 0
|
|
927
|
+
for chunk in resp.iter_raw():
|
|
928
|
+
out.write(chunk)
|
|
929
|
+
written += len(chunk)
|
|
930
|
+
except httpx.HTTPError as exc:
|
|
931
|
+
raise APIConnectionError("object download failed", path=path) from exc
|
|
932
|
+
if expected is not None and written != int(expected):
|
|
933
|
+
raise APIError("object download body length mismatch", path=path)
|
|
934
|
+
out.flush()
|
|
935
|
+
os.fsync(out.fileno())
|
|
936
|
+
# link() fails if dest appeared meanwhile; rename() would replace it.
|
|
937
|
+
os.link(tmp, dest)
|
|
938
|
+
finally:
|
|
939
|
+
try:
|
|
940
|
+
os.unlink(tmp)
|
|
941
|
+
except FileNotFoundError:
|
|
942
|
+
pass
|
|
943
|
+
return dest
|
|
944
|
+
|
|
945
|
+
def _put_object(self, target: Mapping[str, Any], file: str, size: int) -> None:
|
|
946
|
+
method = (target.get("method") or "PUT").upper()
|
|
947
|
+
if method != "PUT":
|
|
948
|
+
raise APIError(f"unsupported upload method {method!r}")
|
|
949
|
+
url = _check_presigned(target.get("url"))
|
|
950
|
+
# Only the headers the signature covers. Adding Content-Type breaks
|
|
951
|
+
# OSS V4 signatures, so it is deliberately not set.
|
|
952
|
+
headers = {str(k): str(v) for k, v in (target.get("headers") or {}).items()}
|
|
953
|
+
headers["Content-Length"] = str(size)
|
|
954
|
+
with open(file, "rb") as fh, _clean_http(self._api._config, timeout=None) as http:
|
|
955
|
+
try:
|
|
956
|
+
resp = http.request("PUT", url, content=_iter_file(fh), headers=headers)
|
|
957
|
+
except httpx.HTTPError as exc:
|
|
958
|
+
raise APIConnectionError("dataset object upload failed") from exc
|
|
959
|
+
if not 200 <= resp.status_code < 300:
|
|
960
|
+
raise APIError(
|
|
961
|
+
f"dataset object upload returned HTTP {resp.status_code}",
|
|
962
|
+
status=resp.status_code,
|
|
963
|
+
)
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def _iter_file(fh: Any, chunk: int = 1 << 20) -> Iterator[bytes]:
|
|
967
|
+
while True:
|
|
968
|
+
block = fh.read(chunk)
|
|
969
|
+
if not block:
|
|
970
|
+
return
|
|
971
|
+
yield block
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
class Training:
|
|
975
|
+
"""``uc.training``: managed training runs and their records.
|
|
976
|
+
|
|
977
|
+
A managed run executes on the platform: you give a dataset, a base model
|
|
978
|
+
and a config, and get back an :class:`Execution`. Everything about the run
|
|
979
|
+
afterwards -- listing your runs, waiting, cancelling, progress, metrics,
|
|
980
|
+
events -- is here too. The config is validated on the server against the
|
|
981
|
+
algorithm package's schema.
|
|
982
|
+
|
|
983
|
+
Example::
|
|
984
|
+
|
|
985
|
+
run = uc.training.submit(
|
|
986
|
+
dataset_version=ds.dataset_version,
|
|
987
|
+
base_model="Qwen/Qwen3.8-27B",
|
|
988
|
+
config={"learning_rate": 1e-4, "num_epochs": 1},
|
|
989
|
+
)
|
|
990
|
+
run = uc.training.wait(run.execution_id)
|
|
991
|
+
print(run.state, run.version_id)
|
|
992
|
+
|
|
993
|
+
for r in uc.training.list(state="running"):
|
|
994
|
+
print(r.execution_id, r.progress)
|
|
995
|
+
for p in uc.training.iter_metrics(run.execution_id, keys=["loss"]):
|
|
996
|
+
print(p.step, p.metrics)
|
|
997
|
+
"""
|
|
998
|
+
|
|
999
|
+
def __init__(self, api: _Platform) -> None:
|
|
1000
|
+
self._api = api
|
|
1001
|
+
|
|
1002
|
+
def submit(
|
|
1003
|
+
self,
|
|
1004
|
+
*,
|
|
1005
|
+
dataset_version: str | None = None,
|
|
1006
|
+
base_model: str | None = None,
|
|
1007
|
+
config: Mapping[str, Any] | None = None,
|
|
1008
|
+
kind: str = "sft",
|
|
1009
|
+
display_name: str | None = None,
|
|
1010
|
+
package_version: str | None = None,
|
|
1011
|
+
base_version_id: str | None = None,
|
|
1012
|
+
dataset_owner_uid: str | None = None,
|
|
1013
|
+
base_version_owner_uid: str | None = None,
|
|
1014
|
+
idempotency_key: str | None = None,
|
|
1015
|
+
) -> Execution:
|
|
1016
|
+
"""Start a managed training run.
|
|
1017
|
+
|
|
1018
|
+
Args:
|
|
1019
|
+
dataset_version: the dataset to train on.
|
|
1020
|
+
base_model: base model name; omit when continuing ``base_version_id``.
|
|
1021
|
+
config: hyperparameters, as the algorithm package's schema defines them.
|
|
1022
|
+
kind: training kind, ``sft`` or ``grpo``.
|
|
1023
|
+
display_name: shown in run lists.
|
|
1024
|
+
package_version: pin an algorithm package; default is the newest stable.
|
|
1025
|
+
base_version_id: continue training from this model version.
|
|
1026
|
+
dataset_owner_uid / base_version_owner_uid: use resources shared with you.
|
|
1027
|
+
idempotency_key: resubmitting with the same key returns the same run.
|
|
1028
|
+
Generated per call when omitted, and reused on network retries.
|
|
1029
|
+
"""
|
|
1030
|
+
body = {
|
|
1031
|
+
"dataset_version": dataset_version,
|
|
1032
|
+
"base_model": base_model,
|
|
1033
|
+
"config": dict(config) if config is not None else None,
|
|
1034
|
+
"display_name": display_name,
|
|
1035
|
+
"train_kind": kind,
|
|
1036
|
+
"base_version_id": base_version_id,
|
|
1037
|
+
"package_version": package_version,
|
|
1038
|
+
"dataset_owner_uid": dataset_owner_uid,
|
|
1039
|
+
"base_version_owner_uid": base_version_owner_uid,
|
|
1040
|
+
}
|
|
1041
|
+
path = "/training/runs"
|
|
1042
|
+
d = self._api.call(
|
|
1043
|
+
"POST",
|
|
1044
|
+
path,
|
|
1045
|
+
json_body={k: v for k, v in body.items() if v not in (None, "")},
|
|
1046
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
1047
|
+
)
|
|
1048
|
+
return Execution.from_wire(_obj(d, path))
|
|
1049
|
+
|
|
1050
|
+
def retry(
|
|
1051
|
+
self,
|
|
1052
|
+
execution_id: str,
|
|
1053
|
+
*,
|
|
1054
|
+
continue_training: bool = False,
|
|
1055
|
+
config: Mapping[str, Any] | None = None,
|
|
1056
|
+
display_name: str | None = None,
|
|
1057
|
+
idempotency_key: str | None = None,
|
|
1058
|
+
) -> Execution:
|
|
1059
|
+
"""Retry a finished run, as a new execution.
|
|
1060
|
+
|
|
1061
|
+
``continue_training=True`` resumes from the run's last checkpoint
|
|
1062
|
+
instead of starting over (the package must be resumable).
|
|
1063
|
+
"""
|
|
1064
|
+
body: dict[str, Any] = {}
|
|
1065
|
+
if continue_training:
|
|
1066
|
+
body["continue_training"] = True
|
|
1067
|
+
if config is not None:
|
|
1068
|
+
body["config"] = dict(config)
|
|
1069
|
+
if display_name:
|
|
1070
|
+
body["display_name"] = display_name
|
|
1071
|
+
path = f"/training/runs/{_seg(execution_id)}/retry"
|
|
1072
|
+
d = self._api.call(
|
|
1073
|
+
"POST", path, json_body=body, idempotency_key=idempotency_key or str(uuid.uuid4())
|
|
1074
|
+
)
|
|
1075
|
+
return Execution.from_wire(_obj(d, path))
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def list(
|
|
1079
|
+
self,
|
|
1080
|
+
*,
|
|
1081
|
+
state: str | None = None,
|
|
1082
|
+
updated_since: int | None = None,
|
|
1083
|
+
page: int | None = None,
|
|
1084
|
+
page_size: int | None = None,
|
|
1085
|
+
) -> Page[Execution]:
|
|
1086
|
+
"""Your training runs, newest first.
|
|
1087
|
+
|
|
1088
|
+
Args:
|
|
1089
|
+
state: ``pending`` / ``running`` / ``succeeded`` / ``failed`` / ``cancelled``.
|
|
1090
|
+
updated_since: milliseconds; only rows updated at or after it.
|
|
1091
|
+
page / page_size: 1-based page; the server defaults to 20 per page, max 500.
|
|
1092
|
+
"""
|
|
1093
|
+
path = "/executions"
|
|
1094
|
+
d = _obj(
|
|
1095
|
+
self._api.call(
|
|
1096
|
+
"GET",
|
|
1097
|
+
path,
|
|
1098
|
+
params={
|
|
1099
|
+
"kind": "training",
|
|
1100
|
+
"state": state,
|
|
1101
|
+
"updated_since": updated_since,
|
|
1102
|
+
"page": page,
|
|
1103
|
+
"page_size": page_size,
|
|
1104
|
+
},
|
|
1105
|
+
),
|
|
1106
|
+
path,
|
|
1107
|
+
)
|
|
1108
|
+
return Page([Execution.from_wire(x) for x in d.get("list") or []], _int(d.get("total")))
|
|
1109
|
+
|
|
1110
|
+
def get(self, execution_id: str) -> Execution:
|
|
1111
|
+
path = f"/executions/{_seg(execution_id)}"
|
|
1112
|
+
return Execution.from_wire(_obj(self._api.call("GET", path), path))
|
|
1113
|
+
|
|
1114
|
+
def cancel(self, execution_id: str) -> Execution:
|
|
1115
|
+
"""Request cancellation.
|
|
1116
|
+
|
|
1117
|
+
The returned execution may still be ``running`` with
|
|
1118
|
+
``cancel_requested=True``; the scheduler moves it to ``cancelled``.
|
|
1119
|
+
Use :meth:`wait` to see the end.
|
|
1120
|
+
"""
|
|
1121
|
+
path = f"/executions/{_seg(execution_id)}/cancel"
|
|
1122
|
+
d = self._api.call("POST", path, json_body={"execution_id": execution_id})
|
|
1123
|
+
return Execution.from_wire(_obj(d, path))
|
|
1124
|
+
|
|
1125
|
+
def rename(self, execution_id: str, display_name: str) -> Execution:
|
|
1126
|
+
"""Change the display name (1-60 visible characters)."""
|
|
1127
|
+
path = f"/executions/{_seg(execution_id)}/rename"
|
|
1128
|
+
d = self._api.call(
|
|
1129
|
+
"POST", path, json_body={"execution_id": execution_id, "display_name": display_name}
|
|
1130
|
+
)
|
|
1131
|
+
return Execution.from_wire(_obj(d, path))
|
|
1132
|
+
|
|
1133
|
+
def delete(self, execution_id: str) -> None:
|
|
1134
|
+
"""Delete a finished execution record."""
|
|
1135
|
+
self._api.call("DELETE", f"/executions/{_seg(execution_id)}")
|
|
1136
|
+
|
|
1137
|
+
def wait(
|
|
1138
|
+
self,
|
|
1139
|
+
execution_id: str,
|
|
1140
|
+
*,
|
|
1141
|
+
timeout: float | None = None,
|
|
1142
|
+
poll_interval: float = 10.0,
|
|
1143
|
+
) -> Execution:
|
|
1144
|
+
"""Poll until the execution reaches a terminal state and return it.
|
|
1145
|
+
|
|
1146
|
+
Does not raise on ``failed`` or ``cancelled``: check ``state`` (and
|
|
1147
|
+
``result_reason``) on the returned object. Raises
|
|
1148
|
+
:class:`FutureTimeoutError` if ``timeout`` seconds pass first.
|
|
1149
|
+
"""
|
|
1150
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
1151
|
+
while True:
|
|
1152
|
+
run = self.get(execution_id)
|
|
1153
|
+
if run.terminal:
|
|
1154
|
+
return run
|
|
1155
|
+
if deadline is not None:
|
|
1156
|
+
left = deadline - time.monotonic()
|
|
1157
|
+
if left <= 0:
|
|
1158
|
+
raise FutureTimeoutError(execution_id, timeout or 0.0, run.state)
|
|
1159
|
+
time.sleep(min(poll_interval, left))
|
|
1160
|
+
else:
|
|
1161
|
+
time.sleep(poll_interval)
|
|
1162
|
+
|
|
1163
|
+
def progress(self, execution_id: str, *, tail: int | None = None) -> list[str]:
|
|
1164
|
+
"""The last ``tail`` structured progress lines, oldest first.
|
|
1165
|
+
|
|
1166
|
+
These are reported progress rows, not the job's raw stdout/stderr.
|
|
1167
|
+
"""
|
|
1168
|
+
path = f"/executions/{_seg(execution_id)}/progress"
|
|
1169
|
+
d = _obj(self._api.call("GET", path, params={"tail": tail}), path)
|
|
1170
|
+
return [str(line) for line in d.get("lines") or []]
|
|
1171
|
+
|
|
1172
|
+
def metrics(
|
|
1173
|
+
self,
|
|
1174
|
+
execution_id: str,
|
|
1175
|
+
*,
|
|
1176
|
+
cursor: str | None = None,
|
|
1177
|
+
limit: int | None = None,
|
|
1178
|
+
keys: Sequence[str] | None = None,
|
|
1179
|
+
include_snapshots: bool = False,
|
|
1180
|
+
) -> MetricsPage:
|
|
1181
|
+
"""One page of reported metrics. Pass ``next_cursor`` back for the next."""
|
|
1182
|
+
path = f"/executions/{_seg(execution_id)}/metrics"
|
|
1183
|
+
params: dict[str, Any] = {"cursor": cursor, "limit": limit}
|
|
1184
|
+
if keys:
|
|
1185
|
+
params["keys"] = list(keys)
|
|
1186
|
+
if include_snapshots:
|
|
1187
|
+
params["include_snapshots"] = "true"
|
|
1188
|
+
d = _obj(self._api.call("GET", path, params=params), path)
|
|
1189
|
+
return MetricsPage(
|
|
1190
|
+
points=[MetricPoint.from_wire(p) for p in d.get("points") or []],
|
|
1191
|
+
next_cursor=_str(d.get("next_cursor")),
|
|
1192
|
+
caught_up=bool(d.get("caught_up")),
|
|
1193
|
+
)
|
|
1194
|
+
|
|
1195
|
+
def iter_metrics(
|
|
1196
|
+
self,
|
|
1197
|
+
execution_id: str,
|
|
1198
|
+
*,
|
|
1199
|
+
keys: Sequence[str] | None = None,
|
|
1200
|
+
limit: int | None = None,
|
|
1201
|
+
include_snapshots: bool = False,
|
|
1202
|
+
) -> Iterator[MetricPoint]:
|
|
1203
|
+
"""Every metric reported so far, following the cursor until caught up.
|
|
1204
|
+
|
|
1205
|
+
Stops at "caught up", which for a running execution only means "no
|
|
1206
|
+
newer rows yet".
|
|
1207
|
+
"""
|
|
1208
|
+
cursor: str | None = None
|
|
1209
|
+
while True:
|
|
1210
|
+
page = self.metrics(
|
|
1211
|
+
execution_id,
|
|
1212
|
+
cursor=cursor,
|
|
1213
|
+
limit=limit,
|
|
1214
|
+
keys=keys,
|
|
1215
|
+
include_snapshots=include_snapshots,
|
|
1216
|
+
)
|
|
1217
|
+
yield from page.points
|
|
1218
|
+
if page.caught_up or not page.next_cursor or page.next_cursor == cursor:
|
|
1219
|
+
return
|
|
1220
|
+
cursor = page.next_cursor
|
|
1221
|
+
|
|
1222
|
+
def metric_keys(self, execution_id: str) -> list[MetricKey]:
|
|
1223
|
+
"""Which metric keys the run reported, their type and step range."""
|
|
1224
|
+
path = f"/executions/{_seg(execution_id)}/metric-keys"
|
|
1225
|
+
d = _obj(self._api.call("GET", path), path)
|
|
1226
|
+
return [MetricKey.from_wire(k) for k in d.get("keys") or []]
|
|
1227
|
+
|
|
1228
|
+
def result(self, execution_id: str) -> ExecutionResult:
|
|
1229
|
+
"""What the algorithm reported: artifacts, data summary, error."""
|
|
1230
|
+
path = f"/executions/{_seg(execution_id)}/result"
|
|
1231
|
+
return ExecutionResult.from_wire(_obj(self._api.call("GET", path), path))
|
|
1232
|
+
|
|
1233
|
+
def events(
|
|
1234
|
+
self, execution_id: str, *, page: int | None = None, page_size: int | None = None
|
|
1235
|
+
) -> Page[ExecutionEvent]:
|
|
1236
|
+
"""Structured events, newest received first."""
|
|
1237
|
+
path = f"/executions/{_seg(execution_id)}/events"
|
|
1238
|
+
d = _obj(self._api.call("GET", path, params={"page": page, "page_size": page_size}), path)
|
|
1239
|
+
return Page(
|
|
1240
|
+
[ExecutionEvent.from_wire(e) for e in d.get("events") or []], _int(d.get("total"))
|
|
1241
|
+
)
|
|
1242
|
+
|
|
1243
|
+
|
|
1244
|
+
class Models:
|
|
1245
|
+
"""``uc.models``: your models, i.e. the model versions managed training produced.
|
|
1246
|
+
|
|
1247
|
+
Each successful run registers one, identified by ``version_id``: which
|
|
1248
|
+
dataset, base model and run (``execution_id``) made it, and which version
|
|
1249
|
+
it was continued from (``parent_id``). It is what ``uc.deployments.create``
|
|
1250
|
+
deploys and what ``uc.training.submit(base_version_id=...)`` continues.
|
|
1251
|
+
"""
|
|
1252
|
+
|
|
1253
|
+
def __init__(self, api: _Platform) -> None:
|
|
1254
|
+
self._api = api
|
|
1255
|
+
|
|
1256
|
+
def list(self, *, page: int | None = None, page_size: int | None = None) -> Page[ModelVersion]:
|
|
1257
|
+
path = "/versions"
|
|
1258
|
+
d = _obj(self._api.call("GET", path, params={"page": page, "page_size": page_size}), path)
|
|
1259
|
+
return Page([ModelVersion.from_wire(v) for v in d.get("list") or []], _int(d.get("total")))
|
|
1260
|
+
|
|
1261
|
+
def get(self, version_id: str, *, owner_uid: str | None = None) -> ModelVersion:
|
|
1262
|
+
path = f"/versions/{_seg(version_id)}"
|
|
1263
|
+
return ModelVersion.from_wire(
|
|
1264
|
+
_obj(self._api.call("GET", path, params={"owner_uid": owner_uid}), path)
|
|
1265
|
+
)
|
|
1266
|
+
|
|
1267
|
+
def lineage(self, version_id: str, *, owner_uid: str | None = None) -> list[ModelVersion]:
|
|
1268
|
+
"""The parent chain of a version, as the server orders it."""
|
|
1269
|
+
path = f"/versions/{_seg(version_id)}/lineage"
|
|
1270
|
+
d = _obj(self._api.call("GET", path, params={"owner_uid": owner_uid}), path)
|
|
1271
|
+
return [ModelVersion.from_wire(v) for v in d.get("chain") or []]
|
|
1272
|
+
|
|
1273
|
+
def delete(self, version_id: str) -> None:
|
|
1274
|
+
self._api.call("DELETE", f"/versions/{_seg(version_id)}")
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
# -- deployments --------------------------------------------------------------
|
|
1278
|
+
#: Deployment states after which polling stops.
|
|
1279
|
+
DEPLOYMENT_SETTLED_STATES = frozenset({"ready", "stopped", "unknown"})
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
@dataclass
|
|
1283
|
+
class Deployment:
|
|
1284
|
+
"""One dedicated deployment of a model version.
|
|
1285
|
+
|
|
1286
|
+
``state`` is ``pending`` / ``ready`` / ``stopped`` / ``unknown``. A
|
|
1287
|
+
deployment is only callable once ``state == "ready"``; then
|
|
1288
|
+
``public_model_id`` is the ``model`` name for the relay's inference API
|
|
1289
|
+
(``uc.chat.completions.create``).
|
|
1290
|
+
"""
|
|
1291
|
+
|
|
1292
|
+
deployment_id: str
|
|
1293
|
+
owner_uid: str | None = None
|
|
1294
|
+
version_id: str | None = None
|
|
1295
|
+
version_owner_uid: str | None = None
|
|
1296
|
+
display_name: str | None = None
|
|
1297
|
+
public_model_id: str | None = None
|
|
1298
|
+
base_model: str | None = None
|
|
1299
|
+
source: str | None = None
|
|
1300
|
+
train_kind: str | None = None
|
|
1301
|
+
#: ``active`` or ``stopped``: what was asked for.
|
|
1302
|
+
desired_state: str | None = None
|
|
1303
|
+
#: ``pending`` / ``ready`` / ``stopped`` / ``unknown``: what is observed.
|
|
1304
|
+
state: str | None = None
|
|
1305
|
+
loaded: bool = False
|
|
1306
|
+
healthy: bool = False
|
|
1307
|
+
route_ready: bool = False
|
|
1308
|
+
resources_released: bool = False
|
|
1309
|
+
route_removed: bool = False
|
|
1310
|
+
is_queued: bool = False
|
|
1311
|
+
created_at: int | None = None
|
|
1312
|
+
updated_at: int | None = None
|
|
1313
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
1314
|
+
|
|
1315
|
+
@property
|
|
1316
|
+
def ready(self) -> bool:
|
|
1317
|
+
return self.state == "ready"
|
|
1318
|
+
|
|
1319
|
+
@classmethod
|
|
1320
|
+
def from_wire(cls, d: Mapping[str, Any]) -> Deployment:
|
|
1321
|
+
return cls(
|
|
1322
|
+
deployment_id=d.get("deployment_id") or "",
|
|
1323
|
+
owner_uid=_str(d.get("owner_uid")),
|
|
1324
|
+
version_id=_str(d.get("version_id")),
|
|
1325
|
+
version_owner_uid=_str(d.get("version_owner_uid")),
|
|
1326
|
+
display_name=_str(d.get("display_name")),
|
|
1327
|
+
public_model_id=_str(d.get("public_model_id")),
|
|
1328
|
+
base_model=_str(d.get("base_model")),
|
|
1329
|
+
source=_str(d.get("source")),
|
|
1330
|
+
train_kind=_str(d.get("train_kind")),
|
|
1331
|
+
desired_state=_str(d.get("desired_state")),
|
|
1332
|
+
state=_str(d.get("state")),
|
|
1333
|
+
loaded=bool(d.get("loaded")),
|
|
1334
|
+
healthy=bool(d.get("healthy")),
|
|
1335
|
+
route_ready=bool(d.get("route_ready")),
|
|
1336
|
+
resources_released=bool(d.get("resources_released")),
|
|
1337
|
+
route_removed=bool(d.get("route_removed")),
|
|
1338
|
+
is_queued=bool(d.get("is_queued")),
|
|
1339
|
+
created_at=_int(d.get("created_at")),
|
|
1340
|
+
updated_at=_int(d.get("updated_at")),
|
|
1341
|
+
raw=dict(d),
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
class DeploymentError(MindRecursiveError):
|
|
1346
|
+
"""A deployment settled in a state other than the one waited for."""
|
|
1347
|
+
|
|
1348
|
+
def __init__(self, deployment: Deployment, wanted: str):
|
|
1349
|
+
super().__init__(
|
|
1350
|
+
f"deployment {deployment.deployment_id} is {deployment.state!r}, wanted {wanted!r}"
|
|
1351
|
+
)
|
|
1352
|
+
self.deployment = deployment
|
|
1353
|
+
|
|
1354
|
+
|
|
1355
|
+
class Deployments:
|
|
1356
|
+
"""``uc.deployments``: deploy model versions for inference.
|
|
1357
|
+
|
|
1358
|
+
Example::
|
|
1359
|
+
|
|
1360
|
+
dep = uc.deployments.create(version_id=run.version_id, display_name="sft-v1")
|
|
1361
|
+
dep = uc.deployments.wait(dep.deployment_id) # until ready
|
|
1362
|
+
reply = uc.chat.completions.create(
|
|
1363
|
+
model=dep.public_model_id, messages=[{"role": "user", "content": "hi"}]
|
|
1364
|
+
)
|
|
1365
|
+
uc.deployments.stop(dep.deployment_id) # releases the GPU
|
|
1366
|
+
"""
|
|
1367
|
+
|
|
1368
|
+
def __init__(self, api: _Platform) -> None:
|
|
1369
|
+
self._api = api
|
|
1370
|
+
|
|
1371
|
+
def create(
|
|
1372
|
+
self,
|
|
1373
|
+
*,
|
|
1374
|
+
version_id: str,
|
|
1375
|
+
display_name: str | None = None,
|
|
1376
|
+
version_owner_uid: str | None = None,
|
|
1377
|
+
source: str | None = None,
|
|
1378
|
+
) -> Deployment:
|
|
1379
|
+
"""Deploy a model version. Returns at once, usually ``pending``.
|
|
1380
|
+
|
|
1381
|
+
Args:
|
|
1382
|
+
version_id: a model version you own or that is shared with you.
|
|
1383
|
+
display_name: shown in lists.
|
|
1384
|
+
version_owner_uid: the version's owner, for a shared version.
|
|
1385
|
+
source: ``"lora"`` (default) or ``"tinker"``.
|
|
1386
|
+
|
|
1387
|
+
Sent once, never retried: a lost response could otherwise start two
|
|
1388
|
+
deployments. Check :meth:`list` before calling again.
|
|
1389
|
+
"""
|
|
1390
|
+
body = {
|
|
1391
|
+
"version_id": version_id,
|
|
1392
|
+
"display_name": display_name or "",
|
|
1393
|
+
"version_owner_uid": version_owner_uid,
|
|
1394
|
+
"source": source,
|
|
1395
|
+
}
|
|
1396
|
+
path = "/deployments"
|
|
1397
|
+
d = self._api.call(
|
|
1398
|
+
"POST", path, json_body={k: v for k, v in body.items() if v is not None}
|
|
1399
|
+
)
|
|
1400
|
+
return Deployment.from_wire(_obj(d, path))
|
|
1401
|
+
|
|
1402
|
+
def list(
|
|
1403
|
+
self, *, state: str | None = None, page: int | None = None, page_size: int | None = None
|
|
1404
|
+
) -> Page[Deployment]:
|
|
1405
|
+
"""Your deployments. ``state`` filters to pending/ready/stopped/unknown."""
|
|
1406
|
+
path = "/deployments"
|
|
1407
|
+
d = _obj(
|
|
1408
|
+
self._api.call(
|
|
1409
|
+
"GET", path, params={"state": state, "page": page, "page_size": page_size}
|
|
1410
|
+
),
|
|
1411
|
+
path,
|
|
1412
|
+
)
|
|
1413
|
+
return Page([Deployment.from_wire(x) for x in d.get("list") or []], _int(d.get("total")))
|
|
1414
|
+
|
|
1415
|
+
def get(self, deployment_id: str) -> Deployment:
|
|
1416
|
+
path = f"/deployments/{_seg(deployment_id)}"
|
|
1417
|
+
return Deployment.from_wire(_obj(self._api.call("GET", path), path))
|
|
1418
|
+
|
|
1419
|
+
def stop(self, deployment_id: str) -> Deployment:
|
|
1420
|
+
"""Stop: release resources and remove the route. Keeps the deployment id.
|
|
1421
|
+
|
|
1422
|
+
In-flight requests are not guaranteed to be cut off at once.
|
|
1423
|
+
"""
|
|
1424
|
+
path = f"/deployments/{_seg(deployment_id)}/stop"
|
|
1425
|
+
return Deployment.from_wire(_obj(self._api.call("POST", path, json_body={}), path))
|
|
1426
|
+
|
|
1427
|
+
def start(self, deployment_id: str) -> Deployment:
|
|
1428
|
+
"""Start a stopped deployment again, under the same id."""
|
|
1429
|
+
path = f"/deployments/{_seg(deployment_id)}/start"
|
|
1430
|
+
return Deployment.from_wire(_obj(self._api.call("POST", path, json_body={}), path))
|
|
1431
|
+
|
|
1432
|
+
def delete(self, deployment_id: str) -> Deployment:
|
|
1433
|
+
"""Delete the deployment record."""
|
|
1434
|
+
path = f"/deployments/{_seg(deployment_id)}"
|
|
1435
|
+
return Deployment.from_wire(_obj(self._api.call("DELETE", path), path))
|
|
1436
|
+
|
|
1437
|
+
def wait(
|
|
1438
|
+
self,
|
|
1439
|
+
deployment_id: str,
|
|
1440
|
+
*,
|
|
1441
|
+
until: str = "ready",
|
|
1442
|
+
timeout: float | None = 1800.0,
|
|
1443
|
+
poll_interval: float = 10.0,
|
|
1444
|
+
) -> Deployment:
|
|
1445
|
+
"""Poll until the deployment reaches ``until`` (``ready`` or ``stopped``).
|
|
1446
|
+
|
|
1447
|
+
Raises :class:`DeploymentError` on ``unknown`` (the server cannot prove
|
|
1448
|
+
either outcome) or when the deployment was switched the other way, and
|
|
1449
|
+
:class:`FutureTimeoutError` on timeout.
|
|
1450
|
+
"""
|
|
1451
|
+
if until not in ("ready", "stopped"):
|
|
1452
|
+
raise ValueError("until must be 'ready' or 'stopped'")
|
|
1453
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
1454
|
+
while True:
|
|
1455
|
+
dep = self.get(deployment_id)
|
|
1456
|
+
if dep.state == until:
|
|
1457
|
+
return dep
|
|
1458
|
+
# Settled the other way *and* that is what is now desired: waiting
|
|
1459
|
+
# longer cannot help. Right after start()/stop() the observed state
|
|
1460
|
+
# still lags the desired one, so a lagging state alone is not final.
|
|
1461
|
+
wanted_desired = "active" if until == "ready" else "stopped"
|
|
1462
|
+
if dep.state == "unknown" or (
|
|
1463
|
+
dep.state in DEPLOYMENT_SETTLED_STATES and dep.desired_state not in (None, wanted_desired)
|
|
1464
|
+
):
|
|
1465
|
+
raise DeploymentError(dep, until)
|
|
1466
|
+
if deadline is not None:
|
|
1467
|
+
left = deadline - time.monotonic()
|
|
1468
|
+
if left <= 0:
|
|
1469
|
+
raise FutureTimeoutError(deployment_id, timeout or 0.0, dep.state)
|
|
1470
|
+
time.sleep(min(poll_interval, left))
|
|
1471
|
+
else:
|
|
1472
|
+
time.sleep(poll_interval)
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
# -- inference ----------------------------------------------------------------
|
|
1476
|
+
class ResponseObject(dict):
|
|
1477
|
+
"""A decoded JSON object, readable like the OpenAI SDK's response objects.
|
|
1478
|
+
|
|
1479
|
+
``resp.choices[0].message.content`` and ``resp["choices"][0]["message"]
|
|
1480
|
+
["content"]`` both work; it is a plain ``dict`` underneath, so ``json.dumps``
|
|
1481
|
+
and ``==`` behave as expected. A missing key reads as ``None`` (as optional
|
|
1482
|
+
fields do in those SDKs, e.g. a final stream chunk's ``delta.content``).
|
|
1483
|
+
Keys that collide with ``dict`` methods (``items``, ``keys``, ``get``...)
|
|
1484
|
+
must be read with ``[]``.
|
|
1485
|
+
"""
|
|
1486
|
+
|
|
1487
|
+
__slots__ = ()
|
|
1488
|
+
|
|
1489
|
+
def __getattr__(self, name: str) -> Any:
|
|
1490
|
+
if name.startswith("_"):
|
|
1491
|
+
raise AttributeError(name)
|
|
1492
|
+
return self.get(name)
|
|
1493
|
+
|
|
1494
|
+
|
|
1495
|
+
class _InferenceHTTP:
|
|
1496
|
+
"""POSTs to the relay's public inference API at the origin root.
|
|
1497
|
+
|
|
1498
|
+
Not the CLI entry: the platform service answers 410 for inference arriving
|
|
1499
|
+
on the CLI entry. Never retried and never redirected, because a lost
|
|
1500
|
+
response may follow a billable generation.
|
|
1501
|
+
"""
|
|
1502
|
+
|
|
1503
|
+
def __init__(self, api: _Platform) -> None:
|
|
1504
|
+
self._api = api
|
|
1505
|
+
|
|
1506
|
+
def post(self, path: str, body: dict[str, Any], *, stream: bool, timeout: float) -> Any:
|
|
1507
|
+
if stream:
|
|
1508
|
+
body["stream"] = True
|
|
1509
|
+
# Headers are built here, not inside the generator, so a closed
|
|
1510
|
+
# client fails at the call rather than at the first iteration.
|
|
1511
|
+
return self._stream(path, body, timeout, self._headers("text/event-stream"))
|
|
1512
|
+
with self._client(timeout) as http:
|
|
1513
|
+
try:
|
|
1514
|
+
resp = http.post(path, json=body, headers=self._headers("application/json"))
|
|
1515
|
+
except httpx.TimeoutException as exc:
|
|
1516
|
+
raise APITimeoutError(f"POST {path} timed out", path=path) from exc
|
|
1517
|
+
except httpx.HTTPError as exc:
|
|
1518
|
+
raise APIConnectionError(f"POST {path} failed: {exc}", path=path) from exc
|
|
1519
|
+
if resp.status_code >= 300:
|
|
1520
|
+
raise _inference_error(resp.status_code, resp.content, path)
|
|
1521
|
+
try:
|
|
1522
|
+
return resp.json(object_hook=ResponseObject)
|
|
1523
|
+
except ValueError as exc:
|
|
1524
|
+
raise APIError("inference response is not JSON", path=path) from exc
|
|
1525
|
+
|
|
1526
|
+
def _stream(
|
|
1527
|
+
self, path: str, body: dict[str, Any], timeout: float, headers: dict[str, str]
|
|
1528
|
+
) -> Iterator[Any]:
|
|
1529
|
+
with self._client(timeout) as http:
|
|
1530
|
+
try:
|
|
1531
|
+
with http.stream("POST", path, json=body, headers=headers) as resp:
|
|
1532
|
+
if resp.status_code >= 300:
|
|
1533
|
+
raise _inference_error(resp.status_code, resp.read(), path)
|
|
1534
|
+
yield from _iter_sse(resp.iter_lines())
|
|
1535
|
+
except httpx.TimeoutException as exc:
|
|
1536
|
+
raise APITimeoutError(f"POST {path} timed out", path=path) from exc
|
|
1537
|
+
except httpx.HTTPError as exc:
|
|
1538
|
+
raise APIConnectionError(f"POST {path} failed: {exc}", path=path) from exc
|
|
1539
|
+
|
|
1540
|
+
def _headers(self, accept: str) -> dict[str, str]:
|
|
1541
|
+
if self._api._owner is not None and getattr(self._api._owner, "_closed", False):
|
|
1542
|
+
raise ConfigurationError("this UserClient has been closed")
|
|
1543
|
+
return {
|
|
1544
|
+
"X-API-Key": self._api._config.api_key,
|
|
1545
|
+
"Accept": accept,
|
|
1546
|
+
"User-Agent": "mind-recursive-python",
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
def _client(self, timeout: float) -> httpx.Client:
|
|
1550
|
+
cfg = self._api._config
|
|
1551
|
+
return httpx.Client(
|
|
1552
|
+
base_url=cfg.origin,
|
|
1553
|
+
timeout=httpx.Timeout(timeout, connect=cfg.connect_timeout),
|
|
1554
|
+
trust_env=cfg.trust_env,
|
|
1555
|
+
# A 307/308 would replay a billable POST.
|
|
1556
|
+
follow_redirects=False,
|
|
1557
|
+
)
|
|
1558
|
+
|
|
1559
|
+
|
|
1560
|
+
class ChatCompletions:
|
|
1561
|
+
"""``uc.chat.completions``: the OpenAI chat format."""
|
|
1562
|
+
|
|
1563
|
+
def __init__(self, http: _InferenceHTTP) -> None:
|
|
1564
|
+
self._http = http
|
|
1565
|
+
|
|
1566
|
+
def create(
|
|
1567
|
+
self,
|
|
1568
|
+
*,
|
|
1569
|
+
model: str,
|
|
1570
|
+
messages: Sequence[Mapping[str, Any]],
|
|
1571
|
+
stream: bool = False,
|
|
1572
|
+
timeout: float = 600.0,
|
|
1573
|
+
**params: Any,
|
|
1574
|
+
) -> Any:
|
|
1575
|
+
"""``POST {origin}/v1/chat/completions``, called like OpenAI's.
|
|
1576
|
+
|
|
1577
|
+
Args:
|
|
1578
|
+
model: the deployment's :attr:`Deployment.public_model_id`.
|
|
1579
|
+
messages: OpenAI chat messages.
|
|
1580
|
+
stream: return an iterator of chunks instead of one response.
|
|
1581
|
+
timeout: seconds for the whole request.
|
|
1582
|
+
**params: anything else OpenAI's ``create`` takes (``max_tokens``,
|
|
1583
|
+
``temperature``, ``tools``...), sent in the body as given.
|
|
1584
|
+
|
|
1585
|
+
Returns:
|
|
1586
|
+
A :class:`ResponseObject`, e.g. ``resp.choices[0].message.content``;
|
|
1587
|
+
with ``stream=True``, an iterator of chunk objects, e.g.
|
|
1588
|
+
``chunk.choices[0].delta.content``.
|
|
1589
|
+
"""
|
|
1590
|
+
body = {"model": model, "messages": [dict(m) for m in messages], **params}
|
|
1591
|
+
return self._http.post("/v1/chat/completions", body, stream=stream, timeout=timeout)
|
|
1592
|
+
|
|
1593
|
+
|
|
1594
|
+
class Chat:
|
|
1595
|
+
"""``uc.chat``: holds :attr:`completions`, as in the OpenAI SDK."""
|
|
1596
|
+
|
|
1597
|
+
def __init__(self, http: _InferenceHTTP) -> None:
|
|
1598
|
+
self.completions = ChatCompletions(http)
|
|
1599
|
+
|
|
1600
|
+
|
|
1601
|
+
def _iter_sse(lines: Iterator[str]) -> Iterator[Any]:
|
|
1602
|
+
"""Decode ``data:`` lines of an SSE stream into JSON objects.
|
|
1603
|
+
|
|
1604
|
+
Multi-line ``data`` fields are joined; ``[DONE]`` ends the stream; comment
|
|
1605
|
+
and ``event:`` lines are skipped (the event type is also inside the JSON
|
|
1606
|
+
in the OpenAI format).
|
|
1607
|
+
"""
|
|
1608
|
+
buf: list[str] = []
|
|
1609
|
+
for line in lines:
|
|
1610
|
+
if line == "":
|
|
1611
|
+
if buf:
|
|
1612
|
+
data = "\n".join(buf)
|
|
1613
|
+
buf = []
|
|
1614
|
+
if data.strip() == "[DONE]":
|
|
1615
|
+
return
|
|
1616
|
+
yield json.loads(data, object_hook=ResponseObject)
|
|
1617
|
+
continue
|
|
1618
|
+
if line.startswith("data:"):
|
|
1619
|
+
buf.append(line[5:].lstrip(" "))
|
|
1620
|
+
if buf:
|
|
1621
|
+
data = "\n".join(buf)
|
|
1622
|
+
if data.strip() != "[DONE]":
|
|
1623
|
+
yield json.loads(data, object_hook=ResponseObject)
|
|
1624
|
+
|
|
1625
|
+
|
|
1626
|
+
def _inference_error(status: int, raw: bytes, path: str) -> APIError:
|
|
1627
|
+
"""OpenAI-style ``{"error": {"message", "type", "code"}}`` or relay ``{"code", "message"}``."""
|
|
1628
|
+
message, code = "", None
|
|
1629
|
+
try:
|
|
1630
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
1631
|
+
except (ValueError, UnicodeDecodeError):
|
|
1632
|
+
payload = None
|
|
1633
|
+
if isinstance(payload, dict):
|
|
1634
|
+
err = payload.get("error")
|
|
1635
|
+
if isinstance(err, dict):
|
|
1636
|
+
message = str(err.get("message") or "")
|
|
1637
|
+
code = err.get("code") or err.get("type")
|
|
1638
|
+
elif isinstance(err, str):
|
|
1639
|
+
message = err
|
|
1640
|
+
if not message and isinstance(payload.get("message"), str):
|
|
1641
|
+
message = payload["message"]
|
|
1642
|
+
code = payload.get("code")
|
|
1643
|
+
if not message:
|
|
1644
|
+
message = raw[:200].decode("utf-8", "replace").strip() or f"HTTP {status}"
|
|
1645
|
+
return status_to_error(status)(
|
|
1646
|
+
message, status=status, path=path, body=raw, code=code,
|
|
1647
|
+
request_id=_str(payload.get("request_id")) if isinstance(payload, dict) else None,
|
|
1648
|
+
)
|