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,1462 @@
|
|
|
1
|
+
"""``ServiceClient``: one training session, created and owned.
|
|
2
|
+
|
|
3
|
+
Constructing one opens the session -- ``POST client/config`` followed by
|
|
4
|
+
``POST create_session`` -- and that is the class's whole definition: it exists
|
|
5
|
+
to create a session and hold it. There is no read-only mode. The trainer and
|
|
6
|
+
sampler are handles onto resources inside the session, not clients; a client
|
|
7
|
+
may create several trainers, each adding a model under the same session.
|
|
8
|
+
Reporting is not a handle either: a session has exactly one writer, so
|
|
9
|
+
``log`` / ``event`` / ``metric`` / ``artifact`` / ``summary`` live on the
|
|
10
|
+
client itself.
|
|
11
|
+
|
|
12
|
+
Anything that does not need a session is not here. Capabilities, health and
|
|
13
|
+
(when the platform serves them) ``whoami`` / ``list_sessions`` / billing live
|
|
14
|
+
on :class:`~mind_recursive.user.UserClient`, which creates nothing. Splitting them
|
|
15
|
+
means a connectivity check no longer leaves a session record behind, and this
|
|
16
|
+
class's arguments -- ``heartbeat_seconds``, ``tags`` -- are all about the
|
|
17
|
+
session it is opening, with no mode in which they mean nothing.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import logging
|
|
24
|
+
import threading
|
|
25
|
+
from typing import Any, Mapping
|
|
26
|
+
|
|
27
|
+
from . import _protocol as P
|
|
28
|
+
from ._config import Config, build_config, web_session_url
|
|
29
|
+
from ._console import emit
|
|
30
|
+
from ._errors import ConfigurationError, GoneError, SessionClosedError
|
|
31
|
+
from ._futures import APIFuture, AsyncFutureResolver, FutureResolver
|
|
32
|
+
from ._session import DEFAULT_HEARTBEAT_SECONDS, ClientConfig, Heartbeat
|
|
33
|
+
from ._transport import AsyncTransport, JSON_CONTENT_TYPE, Transport
|
|
34
|
+
from .reporter import Reporter
|
|
35
|
+
from .types import LoraConfig, SamplerKind, ServerCapabilities, SupportedModel
|
|
36
|
+
|
|
37
|
+
__all__ = ["ServiceClient", "SDK_VERSION"]
|
|
38
|
+
|
|
39
|
+
from mind_recursive._version import SDK_VERSION as _SDK_VERSION
|
|
40
|
+
|
|
41
|
+
log = logging.getLogger("mind_recursive.service")
|
|
42
|
+
|
|
43
|
+
#: Re-exported from ``mind_recursive._version`` so the literal lives in exactly one
|
|
44
|
+
#: place; the server reads it to resolve version-gated flags.
|
|
45
|
+
SDK_VERSION = _SDK_VERSION
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ServiceClient:
|
|
49
|
+
"""One training session on the Mind Recursive platform, opened on construction.
|
|
50
|
+
|
|
51
|
+
Trainers, samplers and the reporter are all created from here and none
|
|
52
|
+
hold a connection of their own. This client owns the transport, the
|
|
53
|
+
session and the billing identity, so closing it is the only cleanup a
|
|
54
|
+
caller has to perform.
|
|
55
|
+
|
|
56
|
+
Constructing one creates a server-side session, which is a billable
|
|
57
|
+
record. For questions that need no session -- which models are served, is
|
|
58
|
+
the backend up -- use :class:`~mind_recursive.user.UserClient` instead.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
api_key: user key (``sk-...``). Falls back to ``MIND_RECURSIVE_API_KEY``.
|
|
62
|
+
base_url: platform origin, with or without the fixed ``/api/mindrsi/v1``
|
|
63
|
+
suffix. Falls back to ``MIND_RECURSIVE_BASE_URL``, then the
|
|
64
|
+
production default.
|
|
65
|
+
timeout: per-request timeout in seconds for the data plane.
|
|
66
|
+
max_retries: retries for retryable failures (transport, 429, 5xx).
|
|
67
|
+
heartbeat_seconds: session keep-alive interval.
|
|
68
|
+
name: human-readable name for this session, shown as the title of
|
|
69
|
+
the run in the web console. Optional and free-form; it
|
|
70
|
+
is a label, not an id -- several sessions may share one.
|
|
71
|
+
client_id: opaque id correlating every session this process opens, so
|
|
72
|
+
the platform can group them. Recorded as a field on the session,
|
|
73
|
+
sent in ``create_session``. It is neither a credential nor a
|
|
74
|
+
routing key, so it is not a request header; free-form business
|
|
75
|
+
labels belong in ``tags`` or ``user_metadata`` on the same call.
|
|
76
|
+
tags: session tags, sent in ``create_session``.
|
|
77
|
+
user_metadata: session metadata, sent in ``create_session``.
|
|
78
|
+
|
|
79
|
+
Example::
|
|
80
|
+
|
|
81
|
+
import mind_recursive
|
|
82
|
+
|
|
83
|
+
sc = mind_recursive.ServiceClient(name="GRPO on GSM8K", client_id="grpo-exp-20261118")
|
|
84
|
+
trainer = sc.create_lora_trainer(base_model="Qwen/Qwen3.8-27B", rank=32)
|
|
85
|
+
sc.log("training starts")
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
*,
|
|
91
|
+
api_key: str | None = None,
|
|
92
|
+
base_url: str | None = None,
|
|
93
|
+
timeout: float = 600.0,
|
|
94
|
+
connect_timeout: float = 30.0,
|
|
95
|
+
max_retries: int = 3,
|
|
96
|
+
heartbeat_seconds: float = DEFAULT_HEARTBEAT_SECONDS,
|
|
97
|
+
name: str | None = None,
|
|
98
|
+
client_id: str | None = None,
|
|
99
|
+
trust_env: bool = False,
|
|
100
|
+
config: Config | None = None,
|
|
101
|
+
tags: list[str] | None = None,
|
|
102
|
+
user_metadata: dict[str, Any] | None = None,
|
|
103
|
+
) -> None:
|
|
104
|
+
self._config = config or build_config(
|
|
105
|
+
api_key=api_key,
|
|
106
|
+
base_url=base_url,
|
|
107
|
+
timeout=timeout,
|
|
108
|
+
connect_timeout=connect_timeout,
|
|
109
|
+
max_retries=max_retries,
|
|
110
|
+
trust_env=trust_env,
|
|
111
|
+
)
|
|
112
|
+
self._transport = Transport(self._config)
|
|
113
|
+
self._heartbeat_seconds = heartbeat_seconds
|
|
114
|
+
self._name = name
|
|
115
|
+
self._async_transport: AsyncTransport | None = None
|
|
116
|
+
self._async_lock = threading.Lock()
|
|
117
|
+
self._async_heartbeat_task: asyncio.Task[None] | None = None
|
|
118
|
+
self._client_id = client_id
|
|
119
|
+
|
|
120
|
+
self._lock = threading.RLock()
|
|
121
|
+
self._session_id: str | None = None
|
|
122
|
+
self._client_config: ClientConfig | None = None
|
|
123
|
+
self._heartbeat: Heartbeat | None = None
|
|
124
|
+
self._closed = False
|
|
125
|
+
# Staged here, then copied into the create_session body below.
|
|
126
|
+
self._pending_tags = list(tags or [])
|
|
127
|
+
self._pending_metadata: dict[str, Any] = dict(user_metadata or {})
|
|
128
|
+
self._model_seq = 0
|
|
129
|
+
self._sampling_seq = 0
|
|
130
|
+
#: One reporter per client, and it lives on the client: a session has
|
|
131
|
+
#: exactly one writer, so there is nothing to create or disambiguate.
|
|
132
|
+
self._reporter = Reporter(service=self)
|
|
133
|
+
|
|
134
|
+
# Constructing this class *is* creating the session; there is no mode
|
|
135
|
+
# in which it holds none. A failure here leaves nothing behind.
|
|
136
|
+
try:
|
|
137
|
+
self._open_session()
|
|
138
|
+
except Exception:
|
|
139
|
+
self._transport.close()
|
|
140
|
+
raise
|
|
141
|
+
|
|
142
|
+
# -- introspection --------------------------------------------------------
|
|
143
|
+
@property
|
|
144
|
+
def config(self) -> Config:
|
|
145
|
+
return self._config
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def session_id(self) -> str | None:
|
|
149
|
+
"""The upstream session id.
|
|
150
|
+
|
|
151
|
+
Set from construction onwards -- there is no window in which a live
|
|
152
|
+
client has no session -- and cleared by :meth:`close`.
|
|
153
|
+
"""
|
|
154
|
+
return self._session_id
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def name(self) -> str | None:
|
|
158
|
+
"""The session's display name, as passed to the constructor."""
|
|
159
|
+
return self._name
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def client_id(self) -> str | None:
|
|
163
|
+
"""The process-correlation id recorded on this session, if any."""
|
|
164
|
+
return self._client_id
|
|
165
|
+
|
|
166
|
+
def _headers(self, extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
167
|
+
"""Per-request headers on top of the transport's own.
|
|
168
|
+
|
|
169
|
+
The SDK sends no custom headers, so this is empty unless a caller
|
|
170
|
+
passes something. ``client_id`` is not one: it is neither a credential
|
|
171
|
+
nor a routing key -- just a label saying which sessions came from one
|
|
172
|
+
process -- so it belongs on the session resource, and
|
|
173
|
+
``create_session`` records it. Neither Tinker nor Fireworks declares
|
|
174
|
+
an attribution header either.
|
|
175
|
+
"""
|
|
176
|
+
return dict(extra or {})
|
|
177
|
+
|
|
178
|
+
# -- session --------------------------------------------------------------
|
|
179
|
+
def require_session(self) -> str:
|
|
180
|
+
"""The session id, for the trainer / sampler / reporter to address.
|
|
181
|
+
|
|
182
|
+
The session exists from construction, so this only has to rule out a
|
|
183
|
+
client that has since been closed.
|
|
184
|
+
"""
|
|
185
|
+
with self._lock:
|
|
186
|
+
if self._closed or self._session_id is None:
|
|
187
|
+
raise SessionClosedError("this ServiceClient has been closed")
|
|
188
|
+
return self._session_id
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def client_config(self) -> ClientConfig:
|
|
192
|
+
"""Server-negotiated flags, fetched on first access."""
|
|
193
|
+
with self._lock:
|
|
194
|
+
if self._client_config is None:
|
|
195
|
+
self._client_config = self._negotiate_config()
|
|
196
|
+
return self._client_config
|
|
197
|
+
|
|
198
|
+
def _negotiate_config(self) -> ClientConfig:
|
|
199
|
+
"""``POST client/config``.
|
|
200
|
+
|
|
201
|
+
A failure here is not fatal: we fall back to documented defaults rather
|
|
202
|
+
than refusing to train, but we say so, because the defaults are a guess
|
|
203
|
+
at someone else's policy.
|
|
204
|
+
"""
|
|
205
|
+
try:
|
|
206
|
+
payload = self._post_json(
|
|
207
|
+
P.PATH_CLIENT_CONFIG,
|
|
208
|
+
{"sdk_version": SDK_VERSION},
|
|
209
|
+
base_url=self._config.service_base_url,
|
|
210
|
+
)
|
|
211
|
+
except Exception as exc: # noqa: BLE001
|
|
212
|
+
log.warning(
|
|
213
|
+
"client/config negotiation failed (%s); falling back to defaults", exc
|
|
214
|
+
)
|
|
215
|
+
return ClientConfig()
|
|
216
|
+
return ClientConfig.from_wire(payload)
|
|
217
|
+
|
|
218
|
+
def _open_session(self) -> None:
|
|
219
|
+
"""``POST create_session`` and start the heartbeat.
|
|
220
|
+
|
|
221
|
+
Caller must hold ``self._lock``. Config is negotiated first because the
|
|
222
|
+
response governs how subsequent requests must behave.
|
|
223
|
+
"""
|
|
224
|
+
if self._client_config is None:
|
|
225
|
+
self._client_config = self._negotiate_config()
|
|
226
|
+
|
|
227
|
+
body: dict[str, Any] = {
|
|
228
|
+
"tags": list(self._pending_tags),
|
|
229
|
+
"sdk_version": SDK_VERSION,
|
|
230
|
+
}
|
|
231
|
+
# A field on the session, not a header: it identifies the process that
|
|
232
|
+
# opened the session, which is a property of the session.
|
|
233
|
+
if self._name:
|
|
234
|
+
body["name"] = self._name
|
|
235
|
+
if self._client_id:
|
|
236
|
+
body["client_id"] = self._client_id
|
|
237
|
+
if self._pending_metadata:
|
|
238
|
+
body["user_metadata"] = dict(self._pending_metadata)
|
|
239
|
+
|
|
240
|
+
payload = self._post_json(
|
|
241
|
+
P.PATH_CREATE_SESSION,
|
|
242
|
+
body,
|
|
243
|
+
base_url=self._config.session_base_url,
|
|
244
|
+
)
|
|
245
|
+
session_id = payload.get("session_id")
|
|
246
|
+
if not session_id:
|
|
247
|
+
raise ConfigurationError(
|
|
248
|
+
f"create_session returned no session_id: {payload!r}"
|
|
249
|
+
)
|
|
250
|
+
self._session_id = str(session_id)
|
|
251
|
+
|
|
252
|
+
for level, key in (("warning", "warning_message"), ("info", "info_message")):
|
|
253
|
+
message = payload.get(key)
|
|
254
|
+
if message:
|
|
255
|
+
getattr(log, level)("create_session: %s", message)
|
|
256
|
+
|
|
257
|
+
# The session is the thing the caller wants to look at in the browser,
|
|
258
|
+
# so hand them the link instead of making them assemble it from an id.
|
|
259
|
+
# Terminal only: a billing/console URL is not a training report.
|
|
260
|
+
emit(f"Session created: {self._session_id}")
|
|
261
|
+
emit(f"Web console: {web_session_url(self._config.web_url, self._session_id)}")
|
|
262
|
+
|
|
263
|
+
self._heartbeat = Heartbeat(
|
|
264
|
+
self._send_heartbeat,
|
|
265
|
+
interval=self._heartbeat_seconds,
|
|
266
|
+
# 410 means the server reclaimed the session. Retrying a beat for a
|
|
267
|
+
# resource that is gone only adds noise; the contract says stop.
|
|
268
|
+
stop_on=(GoneError,),
|
|
269
|
+
)
|
|
270
|
+
self._heartbeat.start()
|
|
271
|
+
log.debug("opened session %s", self._session_id)
|
|
272
|
+
|
|
273
|
+
def _send_heartbeat(self) -> None:
|
|
274
|
+
session_id = self._session_id
|
|
275
|
+
if session_id is None:
|
|
276
|
+
return
|
|
277
|
+
self._post_json(
|
|
278
|
+
P.PATH_HEARTBEAT.format(session_id=session_id),
|
|
279
|
+
{"session_id": session_id},
|
|
280
|
+
# A heartbeat that outlives its own interval is worthless.
|
|
281
|
+
timeout=min(self._heartbeat_seconds, 30.0),
|
|
282
|
+
max_retries=1,
|
|
283
|
+
base_url=self._config.session_base_url,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def next_model_seq(self) -> int:
|
|
287
|
+
"""Allocate the next model sequence number within this session."""
|
|
288
|
+
with self._lock:
|
|
289
|
+
seq = self._model_seq
|
|
290
|
+
self._model_seq += 1
|
|
291
|
+
return seq
|
|
292
|
+
|
|
293
|
+
def next_sampling_seq(self) -> int:
|
|
294
|
+
with self._lock:
|
|
295
|
+
seq = self._sampling_seq
|
|
296
|
+
self._sampling_seq += 1
|
|
297
|
+
return seq
|
|
298
|
+
|
|
299
|
+
# -- trainer --------------------------------------------------------------
|
|
300
|
+
def create_lora_trainer(
|
|
301
|
+
self,
|
|
302
|
+
base_model: str,
|
|
303
|
+
rank: int = 32,
|
|
304
|
+
seed: int | None = None,
|
|
305
|
+
train_mlp: bool = True,
|
|
306
|
+
train_attn: bool = True,
|
|
307
|
+
train_unembed: bool = False,
|
|
308
|
+
user_metadata: dict[str, Any] | None = None,
|
|
309
|
+
optimizer: Any | None = None,
|
|
310
|
+
) -> Any:
|
|
311
|
+
"""Create a LoRA training client.
|
|
312
|
+
|
|
313
|
+
The parameter order matches upstream, so ported positional calls land
|
|
314
|
+
on the right fields. ``train_unembed`` defaults to ``False``, unlike
|
|
315
|
+
the stock SDK's ``True``: training the LM head yields weights that fail
|
|
316
|
+
to deploy, so the safe value is the default here.
|
|
317
|
+
|
|
318
|
+
``optimizer`` accepts the AdamW configuration only; a non-Adam family
|
|
319
|
+
cannot be expressed on this wire and is rejected locally.
|
|
320
|
+
|
|
321
|
+
Returns:
|
|
322
|
+
A :class:`~mind_recursive.trainer.LoraTrainer`.
|
|
323
|
+
"""
|
|
324
|
+
from .trainer import LoraTrainer
|
|
325
|
+
|
|
326
|
+
if optimizer is not None:
|
|
327
|
+
opt_type = (
|
|
328
|
+
optimizer.get("type")
|
|
329
|
+
if isinstance(optimizer, Mapping)
|
|
330
|
+
else getattr(optimizer, "type", None)
|
|
331
|
+
)
|
|
332
|
+
if opt_type not in (None, "adamw"):
|
|
333
|
+
raise ConfigurationError(
|
|
334
|
+
f"only the AdamW optimizer is supported, got {opt_type!r}"
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
lora = LoraConfig(
|
|
338
|
+
rank=rank,
|
|
339
|
+
seed=seed,
|
|
340
|
+
train_unembed=train_unembed,
|
|
341
|
+
train_mlp=train_mlp,
|
|
342
|
+
train_attn=train_attn,
|
|
343
|
+
)
|
|
344
|
+
session_id = self.require_session()
|
|
345
|
+
model_seq = self.next_model_seq()
|
|
346
|
+
body: dict[str, Any] = {
|
|
347
|
+
"session_id": session_id,
|
|
348
|
+
"model_seq_id": model_seq,
|
|
349
|
+
"base_model": base_model,
|
|
350
|
+
"lora_config": lora.to_wire(),
|
|
351
|
+
"optimizer_config": {"type": "adamw"},
|
|
352
|
+
"type": "create_model",
|
|
353
|
+
}
|
|
354
|
+
if user_metadata:
|
|
355
|
+
body["user_metadata"] = user_metadata
|
|
356
|
+
|
|
357
|
+
model_id = self._create_trainer(P.PATH_CREATE_MODEL, body)
|
|
358
|
+
return LoraTrainer(
|
|
359
|
+
service=self, model_id=model_id, base_model=base_model, lora_config=lora
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
def create_lora_trainer_from_state(
|
|
363
|
+
self,
|
|
364
|
+
path: str,
|
|
365
|
+
*,
|
|
366
|
+
base_model: str,
|
|
367
|
+
rank: int | None = None,
|
|
368
|
+
train_mlp: bool | None = None,
|
|
369
|
+
train_attn: bool | None = None,
|
|
370
|
+
load_optimizer: bool | None = None,
|
|
371
|
+
user_metadata: dict[str, Any] | None = None,
|
|
372
|
+
) -> Any:
|
|
373
|
+
"""Create a LoRA training client from a saved training state.
|
|
374
|
+
|
|
375
|
+
One submission does what ``create_lora_trainer`` + ``load_weights``
|
|
376
|
+
does in two: the server creates the model and loads the checkpoint
|
|
377
|
+
together, so a freshly initialized adapter is never produced only to
|
|
378
|
+
be overwritten.
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
path: a training-state checkpoint path returned by
|
|
382
|
+
``save_state`` (``mint://.../checkpoints/...``).
|
|
383
|
+
Weights-only sampler exports (``adapters/...``) are not
|
|
384
|
+
training states; the server rejects them.
|
|
385
|
+
base_model: which served model to train. Required in this release:
|
|
386
|
+
the server does not infer it from the artifact yet.
|
|
387
|
+
rank / train_mlp / train_attn: leave ``None`` to use what the
|
|
388
|
+
checkpoint was saved with. Only the values you pass are sent;
|
|
389
|
+
the rest are the server's to resolve.
|
|
390
|
+
load_optimizer: leave ``None`` to follow the checkpoint (restore
|
|
391
|
+
the optimizer state when it has one). ``False`` forces a
|
|
392
|
+
weights-only resume; ``True`` on a weights-only checkpoint is
|
|
393
|
+
rejected by the server.
|
|
394
|
+
user_metadata: free-form labels recorded on the resource.
|
|
395
|
+
|
|
396
|
+
Returns:
|
|
397
|
+
A :class:`~mind_recursive.LoraTrainer`. ``trainer.lora_config`` is
|
|
398
|
+
``None`` unless ``rank``, ``train_mlp`` and ``train_attn`` were all
|
|
399
|
+
passed: the effective structure lives on the server and this
|
|
400
|
+
release has no read-back for it (``get_info()`` returns the rank).
|
|
401
|
+
"""
|
|
402
|
+
from .trainer import LoraTrainer
|
|
403
|
+
|
|
404
|
+
if not isinstance(path, str) or not path:
|
|
405
|
+
raise ConfigurationError(
|
|
406
|
+
"create_lora_trainer_from_state requires a non-empty checkpoint path"
|
|
407
|
+
)
|
|
408
|
+
if not isinstance(base_model, str) or not base_model:
|
|
409
|
+
raise ConfigurationError(
|
|
410
|
+
"create_lora_trainer_from_state requires a non-empty base_model"
|
|
411
|
+
)
|
|
412
|
+
if rank is not None and (
|
|
413
|
+
isinstance(rank, bool) or not isinstance(rank, int) or rank <= 0
|
|
414
|
+
):
|
|
415
|
+
raise ConfigurationError(
|
|
416
|
+
f"rank must be a positive integer or None, got {rank!r}"
|
|
417
|
+
)
|
|
418
|
+
for name, value in (
|
|
419
|
+
("train_mlp", train_mlp),
|
|
420
|
+
("train_attn", train_attn),
|
|
421
|
+
("load_optimizer", load_optimizer),
|
|
422
|
+
):
|
|
423
|
+
if value is not None and not isinstance(value, bool):
|
|
424
|
+
raise ConfigurationError(f"{name} must be a bool or None, got {value!r}")
|
|
425
|
+
|
|
426
|
+
# Only what the caller actually asked for goes on the wire; an absent
|
|
427
|
+
# key is how this API says "let the artifact decide".
|
|
428
|
+
lora: dict[str, Any] = {}
|
|
429
|
+
if rank is not None:
|
|
430
|
+
lora["rank"] = rank
|
|
431
|
+
if train_mlp is not None:
|
|
432
|
+
lora["train_mlp"] = train_mlp
|
|
433
|
+
if train_attn is not None:
|
|
434
|
+
lora["train_attn"] = train_attn
|
|
435
|
+
|
|
436
|
+
body: dict[str, Any] = {
|
|
437
|
+
"session_id": self.require_session(),
|
|
438
|
+
"model_seq_id": self.next_model_seq(),
|
|
439
|
+
"state_path": path,
|
|
440
|
+
"base_model": base_model,
|
|
441
|
+
"type": "create_model_from_state",
|
|
442
|
+
}
|
|
443
|
+
if lora:
|
|
444
|
+
body["lora_config"] = lora
|
|
445
|
+
if load_optimizer is not None:
|
|
446
|
+
body["load_optimizer"] = load_optimizer
|
|
447
|
+
if user_metadata:
|
|
448
|
+
body["user_metadata"] = dict(user_metadata)
|
|
449
|
+
|
|
450
|
+
model_id = self._create_trainer(P.PATH_CREATE_MODEL_FROM_STATE, body)
|
|
451
|
+
config = (
|
|
452
|
+
LoraConfig(rank=rank, train_mlp=train_mlp, train_attn=train_attn)
|
|
453
|
+
if rank is not None and train_mlp is not None and train_attn is not None
|
|
454
|
+
else None
|
|
455
|
+
)
|
|
456
|
+
return LoraTrainer(
|
|
457
|
+
service=self, model_id=model_id, base_model=base_model, lora_config=config
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
def create_training_client_from_state(
|
|
461
|
+
self,
|
|
462
|
+
path: str,
|
|
463
|
+
base_model: str | None = None,
|
|
464
|
+
user_metadata: dict[str, str] | None = None,
|
|
465
|
+
weights_access_token: str | None = None,
|
|
466
|
+
optimizer: Any | None = None,
|
|
467
|
+
) -> Any:
|
|
468
|
+
"""Tinker-named shell for :meth:`create_lora_trainer_from_state`.
|
|
469
|
+
|
|
470
|
+
Loads weights only, matching upstream's ``create_training_client_from_state``.
|
|
471
|
+
This SDK's server does not infer ``base_model`` from the checkpoint, so
|
|
472
|
+
it is required here even though upstream treats it as optional.
|
|
473
|
+
``weights_access_token`` and non-Adam optimizers are rejected rather
|
|
474
|
+
than silently ignored.
|
|
475
|
+
"""
|
|
476
|
+
return self._create_from_state_compat(
|
|
477
|
+
path,
|
|
478
|
+
base_model=base_model,
|
|
479
|
+
user_metadata=user_metadata,
|
|
480
|
+
weights_access_token=weights_access_token,
|
|
481
|
+
optimizer=optimizer,
|
|
482
|
+
load_optimizer=False,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
def create_training_client_from_state_with_optimizer(
|
|
486
|
+
self,
|
|
487
|
+
path: str,
|
|
488
|
+
base_model: str | None = None,
|
|
489
|
+
user_metadata: dict[str, str] | None = None,
|
|
490
|
+
weights_access_token: str | None = None,
|
|
491
|
+
) -> Any:
|
|
492
|
+
"""Tinker-named shell for a resume that restores optimizer state."""
|
|
493
|
+
return self._create_from_state_compat(
|
|
494
|
+
path,
|
|
495
|
+
base_model=base_model,
|
|
496
|
+
user_metadata=user_metadata,
|
|
497
|
+
weights_access_token=weights_access_token,
|
|
498
|
+
optimizer=None,
|
|
499
|
+
load_optimizer=True,
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
def _create_from_state_compat(
|
|
503
|
+
self,
|
|
504
|
+
path: str,
|
|
505
|
+
*,
|
|
506
|
+
base_model: str | None,
|
|
507
|
+
user_metadata: dict[str, str] | None,
|
|
508
|
+
weights_access_token: str | None,
|
|
509
|
+
optimizer: Any | None,
|
|
510
|
+
load_optimizer: bool,
|
|
511
|
+
) -> Any:
|
|
512
|
+
"""Shared body of the two Tinker-named state creation shells."""
|
|
513
|
+
if base_model is None:
|
|
514
|
+
raise ConfigurationError(
|
|
515
|
+
"base_model is required in this release: the server does not "
|
|
516
|
+
"infer it from the checkpoint yet; pass base_model=..."
|
|
517
|
+
)
|
|
518
|
+
if weights_access_token is not None:
|
|
519
|
+
raise ConfigurationError(
|
|
520
|
+
"weights_access_token is not supported by this relay"
|
|
521
|
+
)
|
|
522
|
+
if optimizer is not None:
|
|
523
|
+
opt_type = (
|
|
524
|
+
optimizer.get("type")
|
|
525
|
+
if isinstance(optimizer, Mapping)
|
|
526
|
+
else getattr(optimizer, "type", None)
|
|
527
|
+
)
|
|
528
|
+
if opt_type not in (None, "adamw"):
|
|
529
|
+
raise ConfigurationError(
|
|
530
|
+
f"only the AdamW optimizer is supported, got {opt_type!r}"
|
|
531
|
+
)
|
|
532
|
+
return self.create_lora_trainer_from_state(
|
|
533
|
+
path,
|
|
534
|
+
base_model=base_model,
|
|
535
|
+
user_metadata=user_metadata,
|
|
536
|
+
load_optimizer=load_optimizer,
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
def create_sampler(
|
|
540
|
+
self,
|
|
541
|
+
model_path: str | None = None,
|
|
542
|
+
*,
|
|
543
|
+
base_model: str | None = None,
|
|
544
|
+
model_id: str | None = None,
|
|
545
|
+
kind: SamplerKind = "snapshot",
|
|
546
|
+
record_stability_info: bool = False,
|
|
547
|
+
deploy_base_model: str | None = None,
|
|
548
|
+
training_model_id: str | None = None,
|
|
549
|
+
) -> Any:
|
|
550
|
+
"""Create a token-level sampling client.
|
|
551
|
+
|
|
552
|
+
Args:
|
|
553
|
+
base_model: sample the base model.
|
|
554
|
+
model_path: a ``mint://`` path to sample trained weights.
|
|
555
|
+
model_id: a live training model to sample from, required by
|
|
556
|
+
``kind="inflight"`` and ignored otherwise.
|
|
557
|
+
kind: ``"snapshot"`` samples fixed weights -- a saved path or a base
|
|
558
|
+
model -- and is what evaluation wants. ``"inflight"`` samples
|
|
559
|
+
the training model's *current* weights, which move as training
|
|
560
|
+
steps, so an on-policy loop does not have to save a checkpoint
|
|
561
|
+
per step. Prefer :meth:`mind_recursive.LoraTrainer.create_sampler`,
|
|
562
|
+
which fills ``model_id`` in for you.
|
|
563
|
+
record_stability_info: record per-sequence stability information
|
|
564
|
+
for every sample from this client, referenced from training
|
|
565
|
+
requests by ``sequence_id`` (``stable_reinforce``). The
|
|
566
|
+
per-call parameter on :meth:`mind_recursive.Sampler.sample` sets it
|
|
567
|
+
for one request instead.
|
|
568
|
+
deploy_base_model: base model the trained weights were trained
|
|
569
|
+
from. Weights have to be deployed before they can be sampled,
|
|
570
|
+
and the deployment needs it. :meth:`mind_recursive.LoraTrainer.create_sampler`
|
|
571
|
+
fills it in; pass it yourself when sampling a ``model_path``
|
|
572
|
+
from a ``ServiceClient``.
|
|
573
|
+
training_model_id: the training model the weights belong to. Each
|
|
574
|
+
new sampler on it releases the previous temporary deployment.
|
|
575
|
+
Filled in by the trainer.
|
|
576
|
+
|
|
577
|
+
Returns:
|
|
578
|
+
A :class:`~mind_recursive.sampler.Sampler`.
|
|
579
|
+
"""
|
|
580
|
+
from .sampler import Sampler
|
|
581
|
+
|
|
582
|
+
if kind not in P.SAMPLER_KINDS:
|
|
583
|
+
raise ValueError(f"kind must be one of {P.SAMPLER_KINDS}")
|
|
584
|
+
if kind == "inflight":
|
|
585
|
+
if not model_id:
|
|
586
|
+
raise ValueError(
|
|
587
|
+
"kind='inflight' samples a live training model, so it needs "
|
|
588
|
+
"model_id -- use LoraTrainer.create_sampler() to pass it"
|
|
589
|
+
)
|
|
590
|
+
if base_model or model_path:
|
|
591
|
+
raise ValueError(
|
|
592
|
+
"kind='inflight' takes its weights from model_id; "
|
|
593
|
+
"base_model and model_path describe fixed weights"
|
|
594
|
+
)
|
|
595
|
+
elif not base_model and not model_path:
|
|
596
|
+
raise ValueError("pass base_model or model_path")
|
|
597
|
+
|
|
598
|
+
session_id = self.require_session()
|
|
599
|
+
body: dict[str, Any] = {
|
|
600
|
+
"session_id": session_id,
|
|
601
|
+
"sampling_session_seq_id": self.next_sampling_seq(),
|
|
602
|
+
"type": "create_sampling_session",
|
|
603
|
+
}
|
|
604
|
+
if kind != "snapshot":
|
|
605
|
+
body["kind"] = kind
|
|
606
|
+
if model_id:
|
|
607
|
+
body["model_id"] = model_id
|
|
608
|
+
if record_stability_info:
|
|
609
|
+
body["record_stability_info"] = True
|
|
610
|
+
if base_model:
|
|
611
|
+
body["base_model"] = base_model
|
|
612
|
+
if model_path:
|
|
613
|
+
body["model_path"] = model_path
|
|
614
|
+
|
|
615
|
+
# Every sampler is created through the platform service
|
|
616
|
+
# (``/service/sample``). The inference service only opens a sampler under an
|
|
617
|
+
# session of its own; the platform service creates that session for
|
|
618
|
+
# this Service Session, keeps it alive and finishes it when the
|
|
619
|
+
# session ends. A public ``base_model`` names an already-deployed
|
|
620
|
+
# model and resolves at once; trained weights (``model_path``) are
|
|
621
|
+
# deployed first, so that future stays pending while the deployment
|
|
622
|
+
# comes up. Sampling itself (``asample``) stays relay-direct.
|
|
623
|
+
if model_path or kind == "inflight":
|
|
624
|
+
# Deploying trained weights needs the base they were trained from.
|
|
625
|
+
if deploy_base_model and "base_model" not in body:
|
|
626
|
+
body["base_model"] = deploy_base_model
|
|
627
|
+
if training_model_id:
|
|
628
|
+
body["training_model_id"] = training_model_id
|
|
629
|
+
request_id = self._submit_on(
|
|
630
|
+
P.PATH_SERVICE_CREATE_SAMPLING_SESSION,
|
|
631
|
+
body,
|
|
632
|
+
base_url=self._config.service_sample_base_url,
|
|
633
|
+
)
|
|
634
|
+
sampling_session_id = APIFuture(
|
|
635
|
+
request_id,
|
|
636
|
+
self.resolver(base_url=self._config.service_base_url),
|
|
637
|
+
P.parse_sampling_session_id,
|
|
638
|
+
).result()
|
|
639
|
+
return Sampler(
|
|
640
|
+
service=self,
|
|
641
|
+
sampling_session_id=str(sampling_session_id),
|
|
642
|
+
base_model=base_model,
|
|
643
|
+
model_path=model_path,
|
|
644
|
+
kind=kind,
|
|
645
|
+
record_stability_info=record_stability_info,
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
#: Tinker's spelling of the LoRA creation call. Kept as an alias so the
|
|
649
|
+
#: safe ``train_unembed=False`` default cannot drift away from it.
|
|
650
|
+
create_lora_training_client = create_lora_trainer
|
|
651
|
+
|
|
652
|
+
def create_sampling_client(
|
|
653
|
+
self,
|
|
654
|
+
model_path: str | None = None,
|
|
655
|
+
base_model: str | None = None,
|
|
656
|
+
retry_config: object | None = None,
|
|
657
|
+
record_stability_info: bool = False,
|
|
658
|
+
*,
|
|
659
|
+
model_id: str | None = None,
|
|
660
|
+
kind: SamplerKind = "snapshot",
|
|
661
|
+
) -> Any:
|
|
662
|
+
"""Tinker spelling for :meth:`create_sampler`.
|
|
663
|
+
|
|
664
|
+
The first four parameters are positional, matching upstream.
|
|
665
|
+
``retry_config`` is rejected rather than ignored: retry policy lives on
|
|
666
|
+
this client's ``max_retries`` argument, and silently dropping it would
|
|
667
|
+
change failure behaviour.
|
|
668
|
+
"""
|
|
669
|
+
if retry_config is not None:
|
|
670
|
+
raise TypeError(
|
|
671
|
+
"retry_config is not supported; set max_retries on ServiceClient"
|
|
672
|
+
)
|
|
673
|
+
return self.create_sampler(
|
|
674
|
+
model_path=model_path,
|
|
675
|
+
base_model=base_model,
|
|
676
|
+
model_id=model_id,
|
|
677
|
+
kind=kind,
|
|
678
|
+
record_stability_info=record_stability_info,
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
# -- async creation -------------------------------------------------------
|
|
682
|
+
async def create_lora_trainer_async(
|
|
683
|
+
self,
|
|
684
|
+
base_model: str,
|
|
685
|
+
rank: int = 32,
|
|
686
|
+
seed: int | None = None,
|
|
687
|
+
train_mlp: bool = True,
|
|
688
|
+
train_attn: bool = True,
|
|
689
|
+
train_unembed: bool = False,
|
|
690
|
+
user_metadata: dict[str, Any] | None = None,
|
|
691
|
+
optimizer: Any | None = None,
|
|
692
|
+
) -> Any:
|
|
693
|
+
"""Async twin of :meth:`create_lora_trainer`."""
|
|
694
|
+
from .trainer import LoraTrainer
|
|
695
|
+
|
|
696
|
+
if optimizer is not None:
|
|
697
|
+
opt_type = (
|
|
698
|
+
optimizer.get("type")
|
|
699
|
+
if isinstance(optimizer, Mapping)
|
|
700
|
+
else getattr(optimizer, "type", None)
|
|
701
|
+
)
|
|
702
|
+
if opt_type not in (None, "adamw"):
|
|
703
|
+
raise ConfigurationError(
|
|
704
|
+
f"only the AdamW optimizer is supported, got {opt_type!r}"
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
lora = LoraConfig(
|
|
708
|
+
rank=rank,
|
|
709
|
+
seed=seed,
|
|
710
|
+
train_unembed=train_unembed,
|
|
711
|
+
train_mlp=train_mlp,
|
|
712
|
+
train_attn=train_attn,
|
|
713
|
+
)
|
|
714
|
+
body: dict[str, Any] = {
|
|
715
|
+
"session_id": self.require_session(),
|
|
716
|
+
"model_seq_id": self.next_model_seq(),
|
|
717
|
+
"base_model": base_model,
|
|
718
|
+
"lora_config": lora.to_wire(),
|
|
719
|
+
"optimizer_config": {"type": "adamw"},
|
|
720
|
+
"type": "create_model",
|
|
721
|
+
}
|
|
722
|
+
if user_metadata:
|
|
723
|
+
body["user_metadata"] = user_metadata
|
|
724
|
+
request_id = await self._asubmit_on(
|
|
725
|
+
P.PATH_CREATE_MODEL, body, base_url=self._config.service_train_base_url
|
|
726
|
+
)
|
|
727
|
+
model_id = await self.async_resolver(
|
|
728
|
+
base_url=self._config.service_base_url
|
|
729
|
+
).resolve(request_id, timeout=None, parse=P.parse_model_id)
|
|
730
|
+
return LoraTrainer(
|
|
731
|
+
service=self, model_id=model_id, base_model=base_model, lora_config=lora
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
create_lora_training_client_async = create_lora_trainer_async
|
|
735
|
+
|
|
736
|
+
async def create_lora_trainer_from_state_async(
|
|
737
|
+
self,
|
|
738
|
+
path: str,
|
|
739
|
+
*,
|
|
740
|
+
base_model: str,
|
|
741
|
+
rank: int | None = None,
|
|
742
|
+
train_mlp: bool | None = None,
|
|
743
|
+
train_attn: bool | None = None,
|
|
744
|
+
load_optimizer: bool | None = None,
|
|
745
|
+
user_metadata: dict[str, Any] | None = None,
|
|
746
|
+
) -> Any:
|
|
747
|
+
"""Async twin of :meth:`create_lora_trainer_from_state`."""
|
|
748
|
+
from .trainer import LoraTrainer
|
|
749
|
+
|
|
750
|
+
if not isinstance(path, str) or not path:
|
|
751
|
+
raise ConfigurationError(
|
|
752
|
+
"create_lora_trainer_from_state requires a non-empty checkpoint path"
|
|
753
|
+
)
|
|
754
|
+
if not isinstance(base_model, str) or not base_model:
|
|
755
|
+
raise ConfigurationError(
|
|
756
|
+
"create_lora_trainer_from_state requires a non-empty base_model"
|
|
757
|
+
)
|
|
758
|
+
if rank is not None and (
|
|
759
|
+
isinstance(rank, bool) or not isinstance(rank, int) or rank <= 0
|
|
760
|
+
):
|
|
761
|
+
raise ConfigurationError(
|
|
762
|
+
f"rank must be a positive integer or None, got {rank!r}"
|
|
763
|
+
)
|
|
764
|
+
for name, value in (
|
|
765
|
+
("train_mlp", train_mlp),
|
|
766
|
+
("train_attn", train_attn),
|
|
767
|
+
("load_optimizer", load_optimizer),
|
|
768
|
+
):
|
|
769
|
+
if value is not None and not isinstance(value, bool):
|
|
770
|
+
raise ConfigurationError(f"{name} must be a bool or None, got {value!r}")
|
|
771
|
+
|
|
772
|
+
lora: dict[str, Any] = {}
|
|
773
|
+
if rank is not None:
|
|
774
|
+
lora["rank"] = rank
|
|
775
|
+
if train_mlp is not None:
|
|
776
|
+
lora["train_mlp"] = train_mlp
|
|
777
|
+
if train_attn is not None:
|
|
778
|
+
lora["train_attn"] = train_attn
|
|
779
|
+
body: dict[str, Any] = {
|
|
780
|
+
"session_id": self.require_session(),
|
|
781
|
+
"model_seq_id": self.next_model_seq(),
|
|
782
|
+
"state_path": path,
|
|
783
|
+
"base_model": base_model,
|
|
784
|
+
"type": "create_model_from_state",
|
|
785
|
+
}
|
|
786
|
+
if lora:
|
|
787
|
+
body["lora_config"] = lora
|
|
788
|
+
if load_optimizer is not None:
|
|
789
|
+
body["load_optimizer"] = load_optimizer
|
|
790
|
+
if user_metadata:
|
|
791
|
+
body["user_metadata"] = dict(user_metadata)
|
|
792
|
+
request_id = await self._asubmit_on(
|
|
793
|
+
P.PATH_CREATE_MODEL_FROM_STATE,
|
|
794
|
+
body,
|
|
795
|
+
base_url=self._config.service_train_base_url,
|
|
796
|
+
)
|
|
797
|
+
model_id = await self.async_resolver(
|
|
798
|
+
base_url=self._config.service_base_url
|
|
799
|
+
).resolve(request_id, timeout=None, parse=P.parse_model_id)
|
|
800
|
+
config = (
|
|
801
|
+
LoraConfig(rank=rank, train_mlp=train_mlp, train_attn=train_attn)
|
|
802
|
+
if rank is not None and train_mlp is not None and train_attn is not None
|
|
803
|
+
else None
|
|
804
|
+
)
|
|
805
|
+
return LoraTrainer(
|
|
806
|
+
service=self, model_id=model_id, base_model=base_model, lora_config=config
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
async def create_training_client_from_state_async(
|
|
810
|
+
self,
|
|
811
|
+
path: str,
|
|
812
|
+
base_model: str | None = None,
|
|
813
|
+
user_metadata: dict[str, str] | None = None,
|
|
814
|
+
weights_access_token: str | None = None,
|
|
815
|
+
optimizer: Any | None = None,
|
|
816
|
+
) -> Any:
|
|
817
|
+
"""Async twin of :meth:`create_training_client_from_state`."""
|
|
818
|
+
if base_model is None:
|
|
819
|
+
raise ConfigurationError(
|
|
820
|
+
"base_model is required in this release: the server does not "
|
|
821
|
+
"infer it from the checkpoint yet; pass base_model=..."
|
|
822
|
+
)
|
|
823
|
+
if weights_access_token is not None:
|
|
824
|
+
raise ConfigurationError("weights_access_token is not supported by this relay")
|
|
825
|
+
if optimizer is not None:
|
|
826
|
+
opt_type = (
|
|
827
|
+
optimizer.get("type")
|
|
828
|
+
if isinstance(optimizer, Mapping)
|
|
829
|
+
else getattr(optimizer, "type", None)
|
|
830
|
+
)
|
|
831
|
+
if opt_type not in (None, "adamw"):
|
|
832
|
+
raise ConfigurationError(
|
|
833
|
+
f"only the AdamW optimizer is supported, got {opt_type!r}"
|
|
834
|
+
)
|
|
835
|
+
return await self.create_lora_trainer_from_state_async(
|
|
836
|
+
path,
|
|
837
|
+
base_model=base_model,
|
|
838
|
+
user_metadata=user_metadata,
|
|
839
|
+
load_optimizer=False,
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
async def create_training_client_from_state_with_optimizer_async(
|
|
843
|
+
self,
|
|
844
|
+
path: str,
|
|
845
|
+
base_model: str | None = None,
|
|
846
|
+
user_metadata: dict[str, str] | None = None,
|
|
847
|
+
weights_access_token: str | None = None,
|
|
848
|
+
) -> Any:
|
|
849
|
+
"""Async twin of :meth:`create_training_client_from_state_with_optimizer`."""
|
|
850
|
+
if base_model is None:
|
|
851
|
+
raise ConfigurationError(
|
|
852
|
+
"base_model is required in this release: the server does not "
|
|
853
|
+
"infer it from the checkpoint yet; pass base_model=..."
|
|
854
|
+
)
|
|
855
|
+
if weights_access_token is not None:
|
|
856
|
+
raise ConfigurationError("weights_access_token is not supported by this relay")
|
|
857
|
+
return await self.create_lora_trainer_from_state_async(
|
|
858
|
+
path,
|
|
859
|
+
base_model=base_model,
|
|
860
|
+
user_metadata=user_metadata,
|
|
861
|
+
load_optimizer=True,
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
async def create_sampler_async(
|
|
865
|
+
self,
|
|
866
|
+
model_path: str | None = None,
|
|
867
|
+
*,
|
|
868
|
+
base_model: str | None = None,
|
|
869
|
+
model_id: str | None = None,
|
|
870
|
+
kind: SamplerKind = "snapshot",
|
|
871
|
+
record_stability_info: bool = False,
|
|
872
|
+
deploy_base_model: str | None = None,
|
|
873
|
+
training_model_id: str | None = None,
|
|
874
|
+
) -> Any:
|
|
875
|
+
"""Async twin of :meth:`create_sampler`."""
|
|
876
|
+
from .sampler import Sampler
|
|
877
|
+
|
|
878
|
+
if kind not in P.SAMPLER_KINDS:
|
|
879
|
+
raise ValueError(f"kind must be one of {P.SAMPLER_KINDS}")
|
|
880
|
+
if kind == "inflight":
|
|
881
|
+
if not model_id:
|
|
882
|
+
raise ValueError(
|
|
883
|
+
"kind='inflight' samples a live training model, so it needs "
|
|
884
|
+
"model_id -- use LoraTrainer.create_sampler() to pass it"
|
|
885
|
+
)
|
|
886
|
+
if base_model or model_path:
|
|
887
|
+
raise ValueError(
|
|
888
|
+
"kind='inflight' takes its weights from model_id; "
|
|
889
|
+
"base_model and model_path describe fixed weights"
|
|
890
|
+
)
|
|
891
|
+
elif not base_model and not model_path:
|
|
892
|
+
raise ValueError("pass base_model or model_path")
|
|
893
|
+
|
|
894
|
+
body: dict[str, Any] = {
|
|
895
|
+
"session_id": self.require_session(),
|
|
896
|
+
"sampling_session_seq_id": self.next_sampling_seq(),
|
|
897
|
+
"type": "create_sampling_session",
|
|
898
|
+
}
|
|
899
|
+
if kind != "snapshot":
|
|
900
|
+
body["kind"] = kind
|
|
901
|
+
if model_id:
|
|
902
|
+
body["model_id"] = model_id
|
|
903
|
+
if record_stability_info:
|
|
904
|
+
body["record_stability_info"] = True
|
|
905
|
+
if base_model:
|
|
906
|
+
body["base_model"] = base_model
|
|
907
|
+
if model_path:
|
|
908
|
+
body["model_path"] = model_path
|
|
909
|
+
if model_path or kind == "inflight":
|
|
910
|
+
if deploy_base_model and "base_model" not in body:
|
|
911
|
+
body["base_model"] = deploy_base_model
|
|
912
|
+
if training_model_id:
|
|
913
|
+
body["training_model_id"] = training_model_id
|
|
914
|
+
request_id = await self._asubmit_on(
|
|
915
|
+
P.PATH_SERVICE_CREATE_SAMPLING_SESSION,
|
|
916
|
+
body,
|
|
917
|
+
base_url=self._config.service_sample_base_url,
|
|
918
|
+
)
|
|
919
|
+
sampling_session_id = await self.async_resolver(
|
|
920
|
+
base_url=self._config.service_base_url
|
|
921
|
+
).resolve(request_id, timeout=None, parse=P.parse_sampling_session_id)
|
|
922
|
+
return Sampler(
|
|
923
|
+
service=self,
|
|
924
|
+
sampling_session_id=str(sampling_session_id),
|
|
925
|
+
base_model=base_model,
|
|
926
|
+
model_path=model_path,
|
|
927
|
+
kind=kind,
|
|
928
|
+
record_stability_info=record_stability_info,
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
async def create_sampling_client_async(
|
|
932
|
+
self,
|
|
933
|
+
model_path: str | None = None,
|
|
934
|
+
base_model: str | None = None,
|
|
935
|
+
retry_config: object | None = None,
|
|
936
|
+
record_stability_info: bool = False,
|
|
937
|
+
*,
|
|
938
|
+
model_id: str | None = None,
|
|
939
|
+
kind: SamplerKind = "snapshot",
|
|
940
|
+
) -> Any:
|
|
941
|
+
"""Async twin of :meth:`create_sampling_client`."""
|
|
942
|
+
if retry_config is not None:
|
|
943
|
+
raise TypeError(
|
|
944
|
+
"retry_config is not supported; set max_retries on ServiceClient"
|
|
945
|
+
)
|
|
946
|
+
return await self.create_sampler_async(
|
|
947
|
+
model_path=model_path,
|
|
948
|
+
base_model=base_model,
|
|
949
|
+
model_id=model_id,
|
|
950
|
+
kind=kind,
|
|
951
|
+
record_stability_info=record_stability_info,
|
|
952
|
+
)
|
|
953
|
+
|
|
954
|
+
# -- reporting ------------------------------------------------------------
|
|
955
|
+
# -- reporting ------------------------------------------------------------
|
|
956
|
+
# One reporter per client, and it lives here: a session has exactly one
|
|
957
|
+
# writer, and every metric, log and artifact belongs to the client that
|
|
958
|
+
# owns the session. The five methods POST through the client's own
|
|
959
|
+
# transport (:mod:`mind_recursive.reporter`), are best-effort, and never raise --
|
|
960
|
+
# reporting must not break training.
|
|
961
|
+
|
|
962
|
+
def log(
|
|
963
|
+
self,
|
|
964
|
+
message: str,
|
|
965
|
+
*,
|
|
966
|
+
level: str = "info",
|
|
967
|
+
step: int | None = None,
|
|
968
|
+
) -> None:
|
|
969
|
+
"""Record one runtime log line. Sugar over :meth:`event` with ``type="log"``.
|
|
970
|
+
|
|
971
|
+
Args:
|
|
972
|
+
message: human-readable text.
|
|
973
|
+
level: ``debug`` | ``info`` | ``warning`` | ``error``.
|
|
974
|
+
step: optional step number, to line the log up with metrics.
|
|
975
|
+
"""
|
|
976
|
+
self._reporter.log(message, level=level, step=step)
|
|
977
|
+
|
|
978
|
+
def event(
|
|
979
|
+
self,
|
|
980
|
+
type: str, # noqa: A002 - the contract field is named "type"
|
|
981
|
+
*,
|
|
982
|
+
level: str = "info",
|
|
983
|
+
code: str | None = None,
|
|
984
|
+
message: str | None = None,
|
|
985
|
+
data: dict[str, Any] | None = None,
|
|
986
|
+
step: int | None = None,
|
|
987
|
+
) -> None:
|
|
988
|
+
"""Record a structured timeline event.
|
|
989
|
+
|
|
990
|
+
``log`` is a special case: ``log(text)`` is ``event("log", message=text)``.
|
|
991
|
+
|
|
992
|
+
Args:
|
|
993
|
+
type: dotted open-set name, e.g. ``upstream.retrying``. Upstream
|
|
994
|
+
requires ``^[a-z0-9_.]+$``, at most 128 bytes.
|
|
995
|
+
level: ``debug`` | ``info`` | ``warning`` | ``error``.
|
|
996
|
+
code: machine-readable reason code, e.g. ``429``.
|
|
997
|
+
message: human-readable text.
|
|
998
|
+
data: structured extras (must be a JSON object, not a list).
|
|
999
|
+
step: optional step number, to line the event up with metrics.
|
|
1000
|
+
"""
|
|
1001
|
+
self._reporter.event(
|
|
1002
|
+
type, level=level, code=code, message=message, data=data, step=step
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
def metric(
|
|
1006
|
+
self,
|
|
1007
|
+
metrics: dict[str, Any],
|
|
1008
|
+
*,
|
|
1009
|
+
step: int,
|
|
1010
|
+
stage: str | None = None,
|
|
1011
|
+
total: int | None = None,
|
|
1012
|
+
timings: dict[str, float] | None = None,
|
|
1013
|
+
counters: dict[str, int] | None = None,
|
|
1014
|
+
) -> None:
|
|
1015
|
+
"""Record one step's metrics. Values follow the server's metric types.
|
|
1016
|
+
|
|
1017
|
+
Args:
|
|
1018
|
+
metrics: this step's values. ``None`` values are dropped rather
|
|
1019
|
+
than sent, since a null would occupy a key without locking it.
|
|
1020
|
+
step: the step number. Points are upserted by step.
|
|
1021
|
+
stage: optional label such as ``training`` or ``evaling``.
|
|
1022
|
+
total: revised total step count, for progress display.
|
|
1023
|
+
timings: named durations for this step, emitted as
|
|
1024
|
+
``sys.step_seconds``.
|
|
1025
|
+
counters: named counters for this step, emitted as ``sys.<name>``.
|
|
1026
|
+
"""
|
|
1027
|
+
self._reporter.metric(
|
|
1028
|
+
metrics, step=step, stage=stage, total=total,
|
|
1029
|
+
timings=timings, counters=counters,
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
def artifact(
|
|
1033
|
+
self,
|
|
1034
|
+
uri: str,
|
|
1035
|
+
*,
|
|
1036
|
+
type: str, # noqa: A002 - the contract field is named "type"
|
|
1037
|
+
name: str | None = None,
|
|
1038
|
+
version: str | None = None,
|
|
1039
|
+
description: str | None = None,
|
|
1040
|
+
metadata: dict[str, Any] | None = None,
|
|
1041
|
+
) -> None:
|
|
1042
|
+
"""Record a produced artefact by reference. Append-only.
|
|
1043
|
+
|
|
1044
|
+
Only the pointer is kept; the bytes are never fetched. ``uri`` must
|
|
1045
|
+
carry a scheme -- ``mint://``, ``oss://``, ``hf://``, ``https://``.
|
|
1046
|
+
"""
|
|
1047
|
+
self._reporter.artifact(
|
|
1048
|
+
uri, type=type, name=name, version=version,
|
|
1049
|
+
description=description, metadata=metadata,
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
def summary(self, mapping: dict[str, Any] | None = None, /, **kwargs: Any) -> None:
|
|
1053
|
+
"""Record terminal scalars. Merged by key, last write wins.
|
|
1054
|
+
|
|
1055
|
+
``sc.summary(final_loss=0.4)`` and ``sc.summary({"final_loss": 0.4})``
|
|
1056
|
+
are equivalent and may be mixed.
|
|
1057
|
+
"""
|
|
1058
|
+
self._reporter.summary(mapping, **kwargs)
|
|
1059
|
+
|
|
1060
|
+
# -- plumbing used by the client classes ----------------------------------
|
|
1061
|
+
def resolver(self, *, base_url: str | None = None) -> FutureResolver:
|
|
1062
|
+
"""A resolver bound to one plane's ``retrieve_future``.
|
|
1063
|
+
|
|
1064
|
+
Training calls default to the train plane. A sampling call passes the
|
|
1065
|
+
sample base so its future is polled on the plane that produced it; the
|
|
1066
|
+
wire path is the same, the base is the distinction.
|
|
1067
|
+
"""
|
|
1068
|
+
base = base_url or self._config.train_base_url
|
|
1069
|
+
if base == self._config.sample_base_url:
|
|
1070
|
+
path = P.PATH_SAMPLE_RETRIEVE_FUTURE
|
|
1071
|
+
elif base == self._config.service_base_url:
|
|
1072
|
+
path = P.PATH_SERVICE_RETRIEVE_FUTURE
|
|
1073
|
+
else:
|
|
1074
|
+
path = P.PATH_RETRIEVE_FUTURE
|
|
1075
|
+
return FutureResolver(
|
|
1076
|
+
lambda request_id: self._poll_future(request_id, base_url=base, path=path)
|
|
1077
|
+
)
|
|
1078
|
+
|
|
1079
|
+
def _poll_future(
|
|
1080
|
+
self, request_id: str, *, base_url: str, path: str
|
|
1081
|
+
) -> dict[str, Any] | bytes:
|
|
1082
|
+
"""One ``retrieve_future`` round trip.
|
|
1083
|
+
|
|
1084
|
+
``Accept`` offers protobuf as well as JSON because a
|
|
1085
|
+
``forward_backward`` result arrives binary. The response's own
|
|
1086
|
+
``Content-Type`` decides how it is read; we never assume.
|
|
1087
|
+
"""
|
|
1088
|
+
response = self._transport.request(
|
|
1089
|
+
"POST",
|
|
1090
|
+
path,
|
|
1091
|
+
base_url=base_url,
|
|
1092
|
+
pool="train",
|
|
1093
|
+
json_body={"request_id": request_id, "allow_metadata_only": True},
|
|
1094
|
+
accept=P.ACCEPT_PROTO_OR_JSON,
|
|
1095
|
+
extra_headers=self._headers(),
|
|
1096
|
+
# 408 is this endpoint's normal "still pending" signal, not a
|
|
1097
|
+
# retryable failure; the resolver consumes the try_again body.
|
|
1098
|
+
allow_statuses=frozenset({408}),
|
|
1099
|
+
)
|
|
1100
|
+
content_type = (response.headers.get("Content-Type") or "").lower()
|
|
1101
|
+
if "protobuf" in content_type or "octet-stream" in content_type:
|
|
1102
|
+
return response.content
|
|
1103
|
+
return response.json()
|
|
1104
|
+
|
|
1105
|
+
# -- async transport -------------------------------------------------------
|
|
1106
|
+
@property
|
|
1107
|
+
def async_transport(self) -> AsyncTransport:
|
|
1108
|
+
"""The lazy async twin of :attr:`transport`.
|
|
1109
|
+
|
|
1110
|
+
Created on first async call inside the running event loop; the session
|
|
1111
|
+
itself was opened by the constructor over the sync transport.
|
|
1112
|
+
"""
|
|
1113
|
+
if self._closed:
|
|
1114
|
+
raise SessionClosedError("this ServiceClient has been closed")
|
|
1115
|
+
with self._async_lock:
|
|
1116
|
+
if self._async_transport is None:
|
|
1117
|
+
self._async_transport = AsyncTransport(self._config)
|
|
1118
|
+
if self._async_heartbeat_task is None and self._heartbeat is not None:
|
|
1119
|
+
# From the first async call on, the heartbeat belongs to the
|
|
1120
|
+
# event loop instead of a background thread.
|
|
1121
|
+
try:
|
|
1122
|
+
loop = asyncio.get_running_loop()
|
|
1123
|
+
except RuntimeError: # pragma: no cover - async methods run in a loop
|
|
1124
|
+
pass
|
|
1125
|
+
else:
|
|
1126
|
+
self._heartbeat.stop()
|
|
1127
|
+
self._heartbeat = None
|
|
1128
|
+
self._async_heartbeat_task = loop.create_task(
|
|
1129
|
+
self._async_heartbeat_loop()
|
|
1130
|
+
)
|
|
1131
|
+
return self._async_transport
|
|
1132
|
+
|
|
1133
|
+
async def _async_heartbeat_loop(self) -> None:
|
|
1134
|
+
try:
|
|
1135
|
+
while not self._closed:
|
|
1136
|
+
await asyncio.sleep(self._heartbeat_seconds)
|
|
1137
|
+
session_id = self._session_id
|
|
1138
|
+
if session_id is None:
|
|
1139
|
+
return
|
|
1140
|
+
try:
|
|
1141
|
+
await self.async_transport.request(
|
|
1142
|
+
"POST",
|
|
1143
|
+
P.PATH_HEARTBEAT.format(session_id=session_id),
|
|
1144
|
+
base_url=self._config.session_base_url,
|
|
1145
|
+
json_body={"session_id": session_id},
|
|
1146
|
+
timeout=min(self._heartbeat_seconds, 30.0),
|
|
1147
|
+
max_retries=1,
|
|
1148
|
+
extra_headers=self._headers(),
|
|
1149
|
+
)
|
|
1150
|
+
except GoneError:
|
|
1151
|
+
return
|
|
1152
|
+
except Exception as exc: # noqa: BLE001 - a heartbeat must not crash
|
|
1153
|
+
log.warning("async session heartbeat failed: %s", exc)
|
|
1154
|
+
except asyncio.CancelledError: # pragma: no cover - normal shutdown
|
|
1155
|
+
return
|
|
1156
|
+
|
|
1157
|
+
def async_resolver(self, *, base_url: str | None = None) -> AsyncFutureResolver:
|
|
1158
|
+
"""Async twin of :meth:`resolver`."""
|
|
1159
|
+
base = base_url or self._config.train_base_url
|
|
1160
|
+
if base == self._config.sample_base_url:
|
|
1161
|
+
path = P.PATH_SAMPLE_RETRIEVE_FUTURE
|
|
1162
|
+
elif base == self._config.service_base_url:
|
|
1163
|
+
path = P.PATH_SERVICE_RETRIEVE_FUTURE
|
|
1164
|
+
else:
|
|
1165
|
+
path = P.PATH_RETRIEVE_FUTURE
|
|
1166
|
+
return AsyncFutureResolver(
|
|
1167
|
+
lambda request_id: self._apoll_future(request_id, base_url=base, path=path)
|
|
1168
|
+
)
|
|
1169
|
+
|
|
1170
|
+
async def _apoll_future(
|
|
1171
|
+
self, request_id: str, *, base_url: str, path: str
|
|
1172
|
+
) -> dict[str, Any] | bytes:
|
|
1173
|
+
response = await self.async_transport.request(
|
|
1174
|
+
"POST",
|
|
1175
|
+
path,
|
|
1176
|
+
base_url=base_url,
|
|
1177
|
+
pool="train",
|
|
1178
|
+
json_body={"request_id": request_id, "allow_metadata_only": True},
|
|
1179
|
+
accept=P.ACCEPT_PROTO_OR_JSON,
|
|
1180
|
+
extra_headers=self._headers(),
|
|
1181
|
+
allow_statuses=frozenset({408}),
|
|
1182
|
+
)
|
|
1183
|
+
content_type = (response.headers.get("Content-Type") or "").lower()
|
|
1184
|
+
if "protobuf" in content_type or "octet-stream" in content_type:
|
|
1185
|
+
return response.content
|
|
1186
|
+
return response.json()
|
|
1187
|
+
|
|
1188
|
+
async def _apost_json(
|
|
1189
|
+
self,
|
|
1190
|
+
path: str,
|
|
1191
|
+
body: dict[str, Any],
|
|
1192
|
+
*,
|
|
1193
|
+
timeout: float | None = None,
|
|
1194
|
+
max_retries: int | None = None,
|
|
1195
|
+
pool: str = "control",
|
|
1196
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
1197
|
+
base_url: str | None = None,
|
|
1198
|
+
) -> dict[str, Any]:
|
|
1199
|
+
response = await self.async_transport.request(
|
|
1200
|
+
"POST",
|
|
1201
|
+
path,
|
|
1202
|
+
base_url=base_url or self._config.train_base_url,
|
|
1203
|
+
pool=pool,
|
|
1204
|
+
json_body=body,
|
|
1205
|
+
accept=JSON_CONTENT_TYPE,
|
|
1206
|
+
extra_headers=self._headers(extra_headers),
|
|
1207
|
+
timeout=timeout,
|
|
1208
|
+
max_retries=max_retries,
|
|
1209
|
+
)
|
|
1210
|
+
return _json_object(response)
|
|
1211
|
+
|
|
1212
|
+
async def _asubmit_on(
|
|
1213
|
+
self, path: str, body: dict[str, Any], *, base_url: str | None = None
|
|
1214
|
+
) -> str:
|
|
1215
|
+
payload = await self._apost_json(path, body, base_url=base_url)
|
|
1216
|
+
request_id = payload.get("request_id")
|
|
1217
|
+
if not request_id:
|
|
1218
|
+
raise ConfigurationError(f"{path} returned no request_id: {payload!r}")
|
|
1219
|
+
return str(request_id)
|
|
1220
|
+
|
|
1221
|
+
async def _asubmit(self, path: str, body: dict[str, Any]) -> str:
|
|
1222
|
+
return await self._asubmit_on(path, body)
|
|
1223
|
+
|
|
1224
|
+
async def post_proto_async(
|
|
1225
|
+
self,
|
|
1226
|
+
path: str,
|
|
1227
|
+
body: bytes,
|
|
1228
|
+
*,
|
|
1229
|
+
content_encoding: str | None = None,
|
|
1230
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
1231
|
+
) -> dict[str, Any]:
|
|
1232
|
+
"""Async twin of :meth:`post_proto`."""
|
|
1233
|
+
headers = self._headers(extra_headers)
|
|
1234
|
+
if content_encoding:
|
|
1235
|
+
headers["Content-Encoding"] = content_encoding
|
|
1236
|
+
response = await self.async_transport.request(
|
|
1237
|
+
"POST",
|
|
1238
|
+
path,
|
|
1239
|
+
base_url=self._config.train_base_url,
|
|
1240
|
+
pool="train",
|
|
1241
|
+
content=body,
|
|
1242
|
+
content_type=P.PROTO_CONTENT_TYPE,
|
|
1243
|
+
accept=JSON_CONTENT_TYPE,
|
|
1244
|
+
extra_headers=headers,
|
|
1245
|
+
)
|
|
1246
|
+
return _json_object(response)
|
|
1247
|
+
|
|
1248
|
+
async def get_server_capabilities_async(self) -> ServerCapabilities:
|
|
1249
|
+
"""Async capabilities query; the sync equivalent lives on UserClient."""
|
|
1250
|
+
response = await self.async_transport.request(
|
|
1251
|
+
"GET",
|
|
1252
|
+
P.PATH_CAPABILITIES,
|
|
1253
|
+
base_url=self._config.service_base_url,
|
|
1254
|
+
extra_headers=self._headers(),
|
|
1255
|
+
accept=JSON_CONTENT_TYPE,
|
|
1256
|
+
)
|
|
1257
|
+
payload = _json_object(response)
|
|
1258
|
+
models = [
|
|
1259
|
+
SupportedModel(
|
|
1260
|
+
model_name=item.get("model_name"),
|
|
1261
|
+
max_context_length=item.get("max_context_length"),
|
|
1262
|
+
trainable=item.get("trainable"),
|
|
1263
|
+
sampleable=item.get("sampleable"),
|
|
1264
|
+
)
|
|
1265
|
+
for item in payload.get("supported_models") or []
|
|
1266
|
+
]
|
|
1267
|
+
return ServerCapabilities(supported_models=models)
|
|
1268
|
+
|
|
1269
|
+
async def close_async(self) -> None:
|
|
1270
|
+
"""Async cleanup: finish the session and close both transports."""
|
|
1271
|
+
with self._lock:
|
|
1272
|
+
if self._closed:
|
|
1273
|
+
return
|
|
1274
|
+
self._closed = True
|
|
1275
|
+
heartbeat, self._heartbeat = self._heartbeat, None
|
|
1276
|
+
session_id, self._session_id = self._session_id, None
|
|
1277
|
+
transport = self._async_transport or AsyncTransport(self._config)
|
|
1278
|
+
if self._async_heartbeat_task is not None:
|
|
1279
|
+
task, self._async_heartbeat_task = self._async_heartbeat_task, None
|
|
1280
|
+
task.cancel()
|
|
1281
|
+
try:
|
|
1282
|
+
await task
|
|
1283
|
+
except asyncio.CancelledError:
|
|
1284
|
+
pass
|
|
1285
|
+
if heartbeat is not None:
|
|
1286
|
+
heartbeat.stop()
|
|
1287
|
+
if session_id is not None:
|
|
1288
|
+
try:
|
|
1289
|
+
await transport.request(
|
|
1290
|
+
"POST",
|
|
1291
|
+
P.PATH_FINISH_SESSION.format(session_id=session_id),
|
|
1292
|
+
base_url=self._config.session_base_url,
|
|
1293
|
+
pool="control",
|
|
1294
|
+
json_body={},
|
|
1295
|
+
accept=JSON_CONTENT_TYPE,
|
|
1296
|
+
extra_headers=self._headers(),
|
|
1297
|
+
max_retries=0,
|
|
1298
|
+
)
|
|
1299
|
+
except Exception as exc: # noqa: BLE001 - best effort, like close()
|
|
1300
|
+
log.debug("finishing session %s failed: %s", session_id, exc)
|
|
1301
|
+
await transport.aclose()
|
|
1302
|
+
self._async_transport = None
|
|
1303
|
+
self._transport.close()
|
|
1304
|
+
|
|
1305
|
+
aclose = close_async
|
|
1306
|
+
|
|
1307
|
+
def _create_trainer(self, path: str, body: dict[str, Any]) -> str:
|
|
1308
|
+
"""Create a training model through the service plane.
|
|
1309
|
+
|
|
1310
|
+
The platform service records the trainer under the session (so it can
|
|
1311
|
+
release it when the session ends) and forwards the create to the
|
|
1312
|
+
training engine. Its future is polled on the service base, and
|
|
1313
|
+
resolves to the Training Model ID that every ``/train`` step carries.
|
|
1314
|
+
"""
|
|
1315
|
+
request_id = self._submit_on(
|
|
1316
|
+
path, body, base_url=self._config.service_train_base_url
|
|
1317
|
+
)
|
|
1318
|
+
return self.resolver(base_url=self._config.service_base_url).resolve(
|
|
1319
|
+
request_id, timeout=None, parse=P.parse_model_id
|
|
1320
|
+
)
|
|
1321
|
+
|
|
1322
|
+
def _submit(self, path: str, body: dict[str, Any]) -> str:
|
|
1323
|
+
"""Send a request that returns a bare ``request_id`` (train plane)."""
|
|
1324
|
+
return self._submit_on(path, body)
|
|
1325
|
+
|
|
1326
|
+
def _submit_on(
|
|
1327
|
+
self, path: str, body: dict[str, Any], *, base_url: str | None = None
|
|
1328
|
+
) -> str:
|
|
1329
|
+
"""Send a request that returns a bare ``request_id`` on a given plane."""
|
|
1330
|
+
payload = self._post_json(path, body, base_url=base_url)
|
|
1331
|
+
request_id = payload.get("request_id")
|
|
1332
|
+
if not request_id:
|
|
1333
|
+
raise ConfigurationError(f"{path} returned no request_id: {payload!r}")
|
|
1334
|
+
return str(request_id)
|
|
1335
|
+
|
|
1336
|
+
def _post_json(
|
|
1337
|
+
self,
|
|
1338
|
+
path: str,
|
|
1339
|
+
body: dict[str, Any],
|
|
1340
|
+
*,
|
|
1341
|
+
timeout: float | None = None,
|
|
1342
|
+
max_retries: int | None = None,
|
|
1343
|
+
pool: str = "control",
|
|
1344
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
1345
|
+
base_url: str | None = None,
|
|
1346
|
+
) -> dict[str, Any]:
|
|
1347
|
+
response = self._transport.request(
|
|
1348
|
+
"POST",
|
|
1349
|
+
path,
|
|
1350
|
+
base_url=base_url or self._config.train_base_url,
|
|
1351
|
+
pool=pool,
|
|
1352
|
+
json_body=body,
|
|
1353
|
+
accept=JSON_CONTENT_TYPE,
|
|
1354
|
+
extra_headers=self._headers(extra_headers),
|
|
1355
|
+
timeout=timeout,
|
|
1356
|
+
max_retries=max_retries,
|
|
1357
|
+
)
|
|
1358
|
+
return _json_object(response)
|
|
1359
|
+
|
|
1360
|
+
def post_proto(
|
|
1361
|
+
self,
|
|
1362
|
+
path: str,
|
|
1363
|
+
body: bytes,
|
|
1364
|
+
*,
|
|
1365
|
+
content_encoding: str | None = None,
|
|
1366
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
1367
|
+
) -> dict[str, Any]:
|
|
1368
|
+
"""Send a protobuf body on the training pool and read a JSON ack."""
|
|
1369
|
+
headers = self._headers(extra_headers)
|
|
1370
|
+
if content_encoding:
|
|
1371
|
+
headers["Content-Encoding"] = content_encoding
|
|
1372
|
+
response = self._transport.request(
|
|
1373
|
+
"POST",
|
|
1374
|
+
path,
|
|
1375
|
+
base_url=self._config.train_base_url,
|
|
1376
|
+
pool="train",
|
|
1377
|
+
content=body,
|
|
1378
|
+
content_type=P.PROTO_CONTENT_TYPE,
|
|
1379
|
+
accept=JSON_CONTENT_TYPE,
|
|
1380
|
+
extra_headers=headers,
|
|
1381
|
+
)
|
|
1382
|
+
return _json_object(response)
|
|
1383
|
+
|
|
1384
|
+
@property
|
|
1385
|
+
def transport(self) -> Transport:
|
|
1386
|
+
return self._transport
|
|
1387
|
+
|
|
1388
|
+
# -- lifecycle ------------------------------------------------------------
|
|
1389
|
+
def close(
|
|
1390
|
+
self,
|
|
1391
|
+
status: str | None = None,
|
|
1392
|
+
detail: str | None = None,
|
|
1393
|
+
) -> Any:
|
|
1394
|
+
"""Stop the heartbeat, finish the session, close connections.
|
|
1395
|
+
|
|
1396
|
+
Ordering matters: the heartbeat stops *before* the session is finished,
|
|
1397
|
+
matching the constraint the existing reporter contract documents.
|
|
1398
|
+
Finishing is best-effort -- the server reclaims an idle session anyway,
|
|
1399
|
+
so a failure here must not mask whatever the caller was really doing.
|
|
1400
|
+
|
|
1401
|
+
``status`` and ``detail`` are accepted for Tinker call-shape
|
|
1402
|
+
compatibility (``close("success", detail=...)``). The relay's finish
|
|
1403
|
+
endpoint carries no request fields, so they are not transmitted. The
|
|
1404
|
+
return value is a completed future-shaped object, so ported code that
|
|
1405
|
+
calls ``close(...).result()`` also works.
|
|
1406
|
+
"""
|
|
1407
|
+
with self._lock:
|
|
1408
|
+
if self._closed:
|
|
1409
|
+
return _CompletedFuture()
|
|
1410
|
+
self._closed = True
|
|
1411
|
+
heartbeat, self._heartbeat = self._heartbeat, None
|
|
1412
|
+
session_id, self._session_id = self._session_id, None
|
|
1413
|
+
|
|
1414
|
+
if heartbeat is not None:
|
|
1415
|
+
heartbeat.stop()
|
|
1416
|
+
if session_id is not None:
|
|
1417
|
+
try:
|
|
1418
|
+
self._post_json(
|
|
1419
|
+
P.PATH_FINISH_SESSION.format(session_id=session_id),
|
|
1420
|
+
{},
|
|
1421
|
+
max_retries=0,
|
|
1422
|
+
base_url=self._config.session_base_url,
|
|
1423
|
+
)
|
|
1424
|
+
except Exception as exc: # noqa: BLE001
|
|
1425
|
+
log.debug("finishing session %s failed: %s", session_id, exc)
|
|
1426
|
+
self._transport.close()
|
|
1427
|
+
return _CompletedFuture()
|
|
1428
|
+
|
|
1429
|
+
def __enter__(self) -> ServiceClient:
|
|
1430
|
+
return self
|
|
1431
|
+
|
|
1432
|
+
def __exit__(self, *_exc: object) -> None:
|
|
1433
|
+
self.close()
|
|
1434
|
+
|
|
1435
|
+
def __repr__(self) -> str:
|
|
1436
|
+
session = self._session_id or "no session"
|
|
1437
|
+
return f"<ServiceClient {self._config.origin} ({session})>"
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
class _CompletedFuture:
|
|
1441
|
+
"""A completed future-shaped value for Tinker's ``close(...).result()``."""
|
|
1442
|
+
|
|
1443
|
+
__slots__ = ()
|
|
1444
|
+
|
|
1445
|
+
def result(self, timeout: float | None = None) -> None:
|
|
1446
|
+
return None
|
|
1447
|
+
|
|
1448
|
+
def done(self) -> bool:
|
|
1449
|
+
return True
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
def _json_object(response: Any) -> dict[str, Any]:
|
|
1453
|
+
"""Read a JSON object body, or ``{}`` for an empty one."""
|
|
1454
|
+
raw = response.content
|
|
1455
|
+
if not raw:
|
|
1456
|
+
return {}
|
|
1457
|
+
payload = response.json()
|
|
1458
|
+
if not isinstance(payload, dict):
|
|
1459
|
+
raise ConfigurationError(
|
|
1460
|
+
f"expected a JSON object from {response.request.url}, got {type(payload).__name__}"
|
|
1461
|
+
)
|
|
1462
|
+
return payload
|