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,316 @@
|
|
|
1
|
+
"""Wire constants and payload parsers.
|
|
2
|
+
|
|
3
|
+
Paths, header names and the small parse functions that turn JSON envelopes into
|
|
4
|
+
our types. Kept in one module so the whole surface the server sees is auditable
|
|
5
|
+
in a single place.
|
|
6
|
+
|
|
7
|
+
Note the plane split: training *and sampling* paths are relative to
|
|
8
|
+
``{origin}/train`` -- the relay's ``/train/**`` handler is a general
|
|
9
|
+
pass-through and the training service implements sampling itself. Platform paths are
|
|
10
|
+
relative to ``{origin}/api/mint/cli/v1``, which the relay remounts under the
|
|
11
|
+
platform service's ``/api/v1``. ``_config`` derives both, so nothing here needs
|
|
12
|
+
to know the origin.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from ._errors import ConfigurationError
|
|
20
|
+
from .types import ForwardBackwardOutput, SampleResponse
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"PATH_CAPABILITIES",
|
|
24
|
+
"PATH_HEALTHZ",
|
|
25
|
+
"PATH_CLIENT_CONFIG",
|
|
26
|
+
"PATH_CLIENT_DYNAMIC_CONFIG",
|
|
27
|
+
"PATH_CREATE_SESSION",
|
|
28
|
+
"PATH_HEARTBEAT",
|
|
29
|
+
"PATH_FINISH_SESSION",
|
|
30
|
+
"PATH_CREATE_MODEL",
|
|
31
|
+
"PATH_CREATE_MODEL_FROM_STATE",
|
|
32
|
+
"PATH_FORWARD_BACKWARD",
|
|
33
|
+
"PATH_OPTIM_STEP",
|
|
34
|
+
"PATH_GET_INFO",
|
|
35
|
+
"PATH_SAVE_WEIGHTS",
|
|
36
|
+
"PATH_SAVE_WEIGHTS_FOR_SAMPLER",
|
|
37
|
+
"PATH_LOAD_WEIGHTS",
|
|
38
|
+
"PATH_RETRIEVE_FUTURE",
|
|
39
|
+
"PATH_SAMPLE_RETRIEVE_FUTURE",
|
|
40
|
+
"PATH_SERVICE_RETRIEVE_FUTURE",
|
|
41
|
+
"PATH_SERVICE_CREATE_SAMPLING_SESSION",
|
|
42
|
+
"PATH_ASAMPLE",
|
|
43
|
+
"PATH_TELEMETRY",
|
|
44
|
+
"PATH_REPORT_EVENTS",
|
|
45
|
+
"PATH_REPORT_METRIC",
|
|
46
|
+
"PATH_REPORT_ARTIFACT",
|
|
47
|
+
"PATH_REPORT_SUMMARY",
|
|
48
|
+
"PROTO_CONTENT_TYPE",
|
|
49
|
+
"ACCEPT_PROTO_OR_JSON",
|
|
50
|
+
"parse_model_id",
|
|
51
|
+
"parse_weights_path",
|
|
52
|
+
"parse_sampling_session_id",
|
|
53
|
+
"parse_optim_step",
|
|
54
|
+
"parse_load_weights",
|
|
55
|
+
"parse_forward_backward_output",
|
|
56
|
+
"parse_sample_response",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
# Every path is relative to one of five bases (three destination platforms:
|
|
60
|
+
# /train -> the training service, /sample -> the inference service, /service -> platform service,
|
|
61
|
+
# which also owns /service/session and /service/report). The base already contains the
|
|
62
|
+
# fixed `/api/mindrsi/v1` root and the segment, so a path never repeats
|
|
63
|
+
# `/api/v1`, `/api/mint/cli/v1` or `/v1`.
|
|
64
|
+
|
|
65
|
+
# -- session segment (relative to {origin}/api/mindrsi/v1/service/session) ----------------
|
|
66
|
+
#: Session lifecycle is client-level, not training-level: the container is
|
|
67
|
+
#: opened before a trainer or sampler exists and both live inside it.
|
|
68
|
+
PATH_CREATE_SESSION = "/create"
|
|
69
|
+
PATH_HEARTBEAT = "/{session_id}/heartbeat"
|
|
70
|
+
PATH_FINISH_SESSION = "/{session_id}/finish"
|
|
71
|
+
|
|
72
|
+
# -- service segment (relative to {origin}/api/mindrsi/v1/service) ----------------
|
|
73
|
+
#: Connectivity and negotiation. Asking what the backend serves, or how a
|
|
74
|
+
#: client must behave, is not a training call and needs no session.
|
|
75
|
+
PATH_CAPABILITIES = "/get_server_capabilities"
|
|
76
|
+
PATH_HEALTHZ = "/healthz"
|
|
77
|
+
PATH_CLIENT_CONFIG = "/client/config"
|
|
78
|
+
PATH_CLIENT_DYNAMIC_CONFIG = "/client/dynamic_config"
|
|
79
|
+
PATH_TELEMETRY = "/telemetry"
|
|
80
|
+
|
|
81
|
+
# -- train plane (relative to {origin}/api/mindrsi/v1/train) ----------------------
|
|
82
|
+
#: ``create_model`` / ``create_model_from_state`` are sent on the
|
|
83
|
+
#: ``/service/train`` base (the platform service owns trainer lifecycle); the
|
|
84
|
+
#: leaf names are unchanged.
|
|
85
|
+
PATH_CREATE_MODEL = "/create_model"
|
|
86
|
+
#: Create the resource and load a saved training state in one submission. The
|
|
87
|
+
#: server resolves ``state_path`` to a ready training-state artifact; this is
|
|
88
|
+
#: the atomic counterpart of ``create_model`` + ``load_weights``.
|
|
89
|
+
PATH_CREATE_MODEL_FROM_STATE = "/create_model_from_state"
|
|
90
|
+
PATH_FORWARD_BACKWARD = "/forward_backward"
|
|
91
|
+
PATH_OPTIM_STEP = "/optim_step"
|
|
92
|
+
PATH_GET_INFO = "/get_info"
|
|
93
|
+
PATH_SAVE_WEIGHTS = "/save_weights"
|
|
94
|
+
PATH_SAVE_WEIGHTS_FOR_SAMPLER = "/save_weights_for_sampler"
|
|
95
|
+
PATH_LOAD_WEIGHTS = "/load_weights"
|
|
96
|
+
PATH_RETRIEVE_FUTURE = "/retrieve_future"
|
|
97
|
+
|
|
98
|
+
# -- sample plane (relative to {origin}/api/mindrsi/v1/sample) --------------------
|
|
99
|
+
PATH_ASAMPLE = "/asample"
|
|
100
|
+
#: Create a sampler. Every sampler is created on the service base: the
|
|
101
|
+
#: platform service opens it under the inference-side session it manages for the
|
|
102
|
+
#: Service Session (deploying trained weights first), so this returns a
|
|
103
|
+
#: ``request_id`` and resolves via the service plane's ``retrieve_future``.
|
|
104
|
+
PATH_SERVICE_CREATE_SAMPLING_SESSION = "/create_sampling_session"
|
|
105
|
+
#: Sampling futures are polled on the sample base. The wire path is the same as
|
|
106
|
+
#: the training one; the base is what tells the relay which plane produced it.
|
|
107
|
+
PATH_SAMPLE_RETRIEVE_FUTURE = "/retrieve_future"
|
|
108
|
+
#: A service-plane future (temporary-deployment sampler create) is polled on
|
|
109
|
+
#: the service base: ``{origin}/api/mindrsi/v1/service/retrieve_future``.
|
|
110
|
+
PATH_SERVICE_RETRIEVE_FUTURE = "/retrieve_future"
|
|
111
|
+
|
|
112
|
+
# -- report plane (relative to {origin}/api/mindrsi/v1/service/report) --------------------
|
|
113
|
+
#: The reporting service's write routes, re-mounted at the report
|
|
114
|
+
#: base and keyed by the SDK's own ``session_id``. The SDK has no "execution"
|
|
115
|
+
#: concept and never sends an ``execution_id``; the relay maps the session to
|
|
116
|
+
#: whatever record it keeps. They are the contract the relay implements; the
|
|
117
|
+
#: production relay does not serve them yet, so a report is best-effort and a
|
|
118
|
+
#: 404 is a warning.
|
|
119
|
+
#:
|
|
120
|
+
#: ``log`` and ``event`` share ``/events`` because a log line *is* an event
|
|
121
|
+
#: upstream; metrics go to ``/log``, which is the listener's name for them.
|
|
122
|
+
PATH_REPORT_EVENTS = "/{session_id}/events"
|
|
123
|
+
PATH_REPORT_METRIC = "/{session_id}/log"
|
|
124
|
+
PATH_REPORT_ARTIFACT = "/{session_id}/artifact"
|
|
125
|
+
PATH_REPORT_SUMMARY = "/{session_id}/summary"
|
|
126
|
+
|
|
127
|
+
# -- headers ------------------------------------------------------------------
|
|
128
|
+
#: There is no custom-header constant here because the SDK sends none: every
|
|
129
|
+
#: request carries ``X-API-Key`` and ``User-Agent`` and nothing else.
|
|
130
|
+
#: Attribution rides in ``create_session``'s ``client_id`` field, because
|
|
131
|
+
#: "these sessions come from one process" is a property of the session, not of
|
|
132
|
+
#: each request. Business labels such as "algorithm" or "rollout vs eval" are
|
|
133
|
+
#: not request attributes either: billing attributes by model and by operation,
|
|
134
|
+
#: so a per-request label would invent a dimension nothing reads. Free-form
|
|
135
|
+
#: tags belong in ``user_metadata`` on the resource.
|
|
136
|
+
|
|
137
|
+
#: What a sampling session's weights are bound to. ``snapshot`` is fixed
|
|
138
|
+
#: weights; ``inflight`` tracks a live training model, so samples follow the
|
|
139
|
+
#: weights as training steps (on-policy RL). This is a real wire field, not an
|
|
140
|
+
#: attribution label: the training service consumes it.
|
|
141
|
+
SAMPLER_KINDS = ("snapshot", "inflight")
|
|
142
|
+
|
|
143
|
+
PROTO_CONTENT_TYPE = "application/x-protobuf"
|
|
144
|
+
#: forward_backward futures resolve to protobuf; everything else to JSON. We
|
|
145
|
+
#: advertise both and branch on the response's Content-Type.
|
|
146
|
+
ACCEPT_PROTO_OR_JSON = "application/x-protobuf, application/json"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _require(payload: dict[str, Any], key: str, what: str) -> Any:
|
|
150
|
+
value = payload.get(key)
|
|
151
|
+
if value in (None, ""):
|
|
152
|
+
raise ConfigurationError(f"{what} response is missing {key!r}: {payload!r}")
|
|
153
|
+
return value
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def parse_model_id(payload: dict[str, Any] | bytes) -> str:
|
|
157
|
+
"""Pull ``model_id`` out of a resolved ``create_model`` future."""
|
|
158
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
159
|
+
raise ConfigurationError("create_model resolved to a binary body")
|
|
160
|
+
return str(_require(payload, "model_id", "create_model"))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class CheckpointPath(str):
|
|
164
|
+
"""A save path that also answers to upstream's ``.path`` spelling.
|
|
165
|
+
|
|
166
|
+
Tinker resolves save futures to a response object with a ``path`` field;
|
|
167
|
+
this SDK resolves them to the path string itself. A ``str`` subclass keeps
|
|
168
|
+
both call shapes working without changing what the value is.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def path(self) -> str:
|
|
173
|
+
return str(self)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def parse_weights_path(payload: dict[str, Any] | bytes) -> str:
|
|
177
|
+
"""Pull the ``mint://`` path out of a resolved save-weights future."""
|
|
178
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
179
|
+
raise ConfigurationError("save_weights resolved to a binary body")
|
|
180
|
+
return CheckpointPath(_require(payload, "path", "save_weights"))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def parse_sampling_session_id(payload: dict[str, Any] | bytes) -> str:
|
|
184
|
+
"""Pull ``sampling_session_id`` out of a create_sampling_session result.
|
|
185
|
+
|
|
186
|
+
Handles both shapes: the relay-direct create returns it on the call, and
|
|
187
|
+
the service-plane create resolves a future to the same object.
|
|
188
|
+
"""
|
|
189
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
190
|
+
raise ConfigurationError(
|
|
191
|
+
"create_sampling_session resolved to a binary body"
|
|
192
|
+
)
|
|
193
|
+
return str(_require(payload, "sampling_session_id", "create_sampling_session"))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def parse_optim_step(payload: dict[str, Any] | bytes) -> dict[str, Any]:
|
|
197
|
+
"""``optim_step`` resolves to a small JSON object (may be empty)."""
|
|
198
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
199
|
+
raise ConfigurationError("optim_step resolved to a binary body")
|
|
200
|
+
return payload
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def parse_load_weights(payload: dict[str, Any] | bytes) -> dict[str, Any]:
|
|
204
|
+
"""``load_weights`` resolves to a small JSON object.
|
|
205
|
+
|
|
206
|
+
Separate from :func:`parse_optim_step` even though the shape is the same
|
|
207
|
+
today: upstream models them as two types (``LoadWeightsResponse`` carries
|
|
208
|
+
``path`` and ``model_id``, ``OptimStepResponse`` carries ``metrics``), so
|
|
209
|
+
sharing one parser names the wrong thing and would hide the day they
|
|
210
|
+
diverge.
|
|
211
|
+
"""
|
|
212
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
213
|
+
raise ConfigurationError("load_weights resolved to a binary body")
|
|
214
|
+
return payload
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def parse_forward_backward_output(
|
|
218
|
+
payload: dict[str, Any] | bytes,
|
|
219
|
+
) -> ForwardBackwardOutput:
|
|
220
|
+
"""Decode a resolved ``forward_backward`` future.
|
|
221
|
+
|
|
222
|
+
Normally protobuf. A JSON body is still accepted: the server may fall back
|
|
223
|
+
to it, and refusing to read a well-formed result would be gratuitous.
|
|
224
|
+
"""
|
|
225
|
+
from ._proto import decode_forward_backward_output
|
|
226
|
+
|
|
227
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
228
|
+
return decode_forward_backward_output(bytes(payload))
|
|
229
|
+
|
|
230
|
+
metrics = {
|
|
231
|
+
key: float(value)
|
|
232
|
+
for key, value in (payload.get("metrics") or {}).items()
|
|
233
|
+
if isinstance(value, (int, float))
|
|
234
|
+
}
|
|
235
|
+
return ForwardBackwardOutput(
|
|
236
|
+
loss_fn_output_type=str(payload.get("loss_fn_output_type") or "ArrayRecord"),
|
|
237
|
+
loss_fn_outputs=[],
|
|
238
|
+
metrics=metrics,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def parse_sample_response(payload: dict[str, Any] | bytes) -> SampleResponse:
|
|
243
|
+
"""Decode a resolved ``asample`` future (protobuf or JSON)."""
|
|
244
|
+
from ._proto import decode_sample_response
|
|
245
|
+
from .types import SampledSequence
|
|
246
|
+
|
|
247
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
248
|
+
return decode_sample_response(bytes(payload))
|
|
249
|
+
|
|
250
|
+
sequences = []
|
|
251
|
+
for item in payload.get("sequences") or []:
|
|
252
|
+
sequences.append(
|
|
253
|
+
SampledSequence(
|
|
254
|
+
tokens=[int(t) for t in item.get("tokens") or []],
|
|
255
|
+
stop_reason=item.get("stop_reason") or "stop",
|
|
256
|
+
logprobs=item.get("logprobs"),
|
|
257
|
+
sequence_id=item.get("sequence_id"),
|
|
258
|
+
topk_logprobs=_parse_topk(item.get("topk_sampled_logprobs")),
|
|
259
|
+
)
|
|
260
|
+
)
|
|
261
|
+
return SampleResponse(
|
|
262
|
+
sequences=sequences,
|
|
263
|
+
prompt_logprobs=payload.get("prompt_logprobs"),
|
|
264
|
+
prompt_cache_hit_tokens=int(payload.get("prompt_cache_hit_tokens") or 0),
|
|
265
|
+
topk_prompt_logprobs=_parse_topk(payload.get("topk_prompt_logprobs")),
|
|
266
|
+
target_prompt_logprobs=_parse_tensor(payload.get("target_prompt_logprobs")),
|
|
267
|
+
prompt_alt_tokens=_parse_prompt_alt_tokens(payload.get("prompt_alt_tokens")),
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _parse_topk(raw: Any) -> Any:
|
|
272
|
+
"""Build a ``TopkLogprobs`` from its JSON object, if present."""
|
|
273
|
+
if not raw:
|
|
274
|
+
return None
|
|
275
|
+
from .types import TopkLogprobs
|
|
276
|
+
|
|
277
|
+
k = int(raw.get("k") or 0)
|
|
278
|
+
token_ids = [int(t) for t in raw.get("token_ids") or []]
|
|
279
|
+
length = int(raw.get("length") or 0)
|
|
280
|
+
if length == 0 and k:
|
|
281
|
+
length = len(token_ids) // k
|
|
282
|
+
return TopkLogprobs(
|
|
283
|
+
token_ids=token_ids,
|
|
284
|
+
logprobs=[float(x) for x in raw.get("logprobs") or []],
|
|
285
|
+
k=k,
|
|
286
|
+
length=length,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _parse_tensor(raw: Any) -> Any:
|
|
291
|
+
"""Build a ``TensorData`` from the JSON tensor shape, if present."""
|
|
292
|
+
if not raw:
|
|
293
|
+
return None
|
|
294
|
+
import numpy as np
|
|
295
|
+
|
|
296
|
+
from .types import TensorData
|
|
297
|
+
|
|
298
|
+
dtype = raw.get("dtype") or "float32"
|
|
299
|
+
return TensorData(
|
|
300
|
+
data=np.asarray(raw.get("data") or []),
|
|
301
|
+
dtype=dtype,
|
|
302
|
+
shape=raw.get("shape"),
|
|
303
|
+
sparse_crow_indices=raw.get("sparse_crow_indices"),
|
|
304
|
+
sparse_col_indices=raw.get("sparse_col_indices"),
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _parse_prompt_alt_tokens(raw: Any) -> Any:
|
|
309
|
+
if not raw:
|
|
310
|
+
return None
|
|
311
|
+
from .types import PromptAltTokens
|
|
312
|
+
|
|
313
|
+
return PromptAltTokens(
|
|
314
|
+
tokens=_parse_tensor(raw.get("tokens")),
|
|
315
|
+
logprobs=_parse_tensor(raw.get("logprobs")),
|
|
316
|
+
)
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Session negotiation, heartbeat, and the server's behaviour flags.
|
|
2
|
+
|
|
3
|
+
Two pieces the stock SDK gets for free and we must implement:
|
|
4
|
+
|
|
5
|
+
**``client/config`` is a set of instructions, not information.** The server
|
|
6
|
+
tells the client how to behave: how large a chunk may be, whether to compress,
|
|
7
|
+
how many concurrent samples to allow. Ignoring it is not "using defaults", it
|
|
8
|
+
is violating a negotiated contract. Observed on alpha::
|
|
9
|
+
|
|
10
|
+
{"pjwt_auth_enabled":false, "credential_default_source":"api_key",
|
|
11
|
+
"parallel_fwdbwd_chunks":true, "proto_write_fwdbwd":false,
|
|
12
|
+
"proto_compress_fwdbwd":false, "fwd_via_fwdbwd":false,
|
|
13
|
+
"fwdbwd_max_chunk_len":1024, "fwdbwd_max_chunk_bytes_count":50000000,
|
|
14
|
+
"sample_max_concurrent_requests":2000, "sample_join_sampling_session":true,
|
|
15
|
+
"use_pyqwest_transport":false}
|
|
16
|
+
|
|
17
|
+
``pjwt_auth_enabled: false`` is also the root cause of a dead end documented
|
|
18
|
+
in the design: it is why ``TINKER_CREDENTIAL_CMD`` cannot work against this platform.
|
|
19
|
+
|
|
20
|
+
**Heartbeats are mandatory.** Without ``session_heartbeat`` the server reclaims
|
|
21
|
+
the session's resources as idle, killing an in-flight training run. The
|
|
22
|
+
heartbeat runs on a daemon thread so it cannot keep a process alive, and it
|
|
23
|
+
stops before the session is finished.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
import threading
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from typing import Any, Callable
|
|
32
|
+
|
|
33
|
+
__all__ = ["ClientConfig", "Heartbeat", "DEFAULT_HEARTBEAT_SECONDS"]
|
|
34
|
+
|
|
35
|
+
log = logging.getLogger("mind_recursive.session")
|
|
36
|
+
|
|
37
|
+
#: Upstream heartbeats roughly every 10s. The server's idle reclaim window is
|
|
38
|
+
#: larger than this, so the interval has headroom for one missed beat.
|
|
39
|
+
DEFAULT_HEARTBEAT_SECONDS = 10.0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class ClientConfig:
|
|
44
|
+
"""Server-negotiated behaviour flags.
|
|
45
|
+
|
|
46
|
+
Unknown keys are kept in ``extra`` rather than dropped, so a server that
|
|
47
|
+
adds a flag does not lose it on the way through an older SDK.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
#: Whether the server does JWT exchange. False on Mind Recursive: it only accepts
|
|
51
|
+
#: API keys, which is why credential-command auth cannot work here.
|
|
52
|
+
pjwt_auth_enabled: bool = False
|
|
53
|
+
credential_default_source: str = "api_key"
|
|
54
|
+
|
|
55
|
+
#: Chunking budget for forward_backward. Exceeding either limit earns a
|
|
56
|
+
#: 413 rather than a helpful message, so the client must split batches.
|
|
57
|
+
fwdbwd_max_chunk_len: int = 1024
|
|
58
|
+
fwdbwd_max_chunk_bytes_count: int = 50_000_000
|
|
59
|
+
parallel_fwdbwd_chunks: bool = True
|
|
60
|
+
|
|
61
|
+
#: Whether to zstd-compress forward_backward bodies. Server's call.
|
|
62
|
+
proto_compress_fwdbwd: bool = False
|
|
63
|
+
proto_write_fwdbwd: bool = False
|
|
64
|
+
#: Whether a plain forward must be routed through forward_backward.
|
|
65
|
+
fwd_via_fwdbwd: bool = False
|
|
66
|
+
|
|
67
|
+
sample_max_concurrent_requests: int = 2000
|
|
68
|
+
sample_join_sampling_session: bool = True
|
|
69
|
+
sample_no_retries: bool = False
|
|
70
|
+
|
|
71
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
72
|
+
|
|
73
|
+
_KNOWN = (
|
|
74
|
+
"pjwt_auth_enabled",
|
|
75
|
+
"credential_default_source",
|
|
76
|
+
"fwdbwd_max_chunk_len",
|
|
77
|
+
"fwdbwd_max_chunk_bytes_count",
|
|
78
|
+
"parallel_fwdbwd_chunks",
|
|
79
|
+
"proto_compress_fwdbwd",
|
|
80
|
+
"proto_write_fwdbwd",
|
|
81
|
+
"fwd_via_fwdbwd",
|
|
82
|
+
"sample_max_concurrent_requests",
|
|
83
|
+
"sample_join_sampling_session",
|
|
84
|
+
"sample_no_retries",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@classmethod
|
|
88
|
+
def from_wire(cls, payload: dict[str, Any] | None) -> ClientConfig:
|
|
89
|
+
"""Build from a ``client/config`` response, tolerating absent keys.
|
|
90
|
+
|
|
91
|
+
A missing flag keeps our default; a malformed value is ignored with a
|
|
92
|
+
warning rather than raising, because a surprising config value should
|
|
93
|
+
not stop a training run from starting.
|
|
94
|
+
"""
|
|
95
|
+
if not payload:
|
|
96
|
+
return cls()
|
|
97
|
+
known: dict[str, Any] = {}
|
|
98
|
+
extra: dict[str, Any] = {}
|
|
99
|
+
for key, value in payload.items():
|
|
100
|
+
if key in cls._KNOWN:
|
|
101
|
+
known[key] = value
|
|
102
|
+
else:
|
|
103
|
+
extra[key] = value
|
|
104
|
+
|
|
105
|
+
config = cls(extra=extra)
|
|
106
|
+
for key, value in known.items():
|
|
107
|
+
current = getattr(config, key)
|
|
108
|
+
try:
|
|
109
|
+
if isinstance(current, bool):
|
|
110
|
+
coerced: Any = bool(value)
|
|
111
|
+
elif isinstance(current, int):
|
|
112
|
+
coerced = int(value)
|
|
113
|
+
else:
|
|
114
|
+
coerced = value
|
|
115
|
+
except (TypeError, ValueError):
|
|
116
|
+
log.warning("ignoring malformed client/config value %s=%r", key, value)
|
|
117
|
+
continue
|
|
118
|
+
setattr(config, key, coerced)
|
|
119
|
+
return config
|
|
120
|
+
|
|
121
|
+
def chunk_budget(self) -> tuple[int, int]:
|
|
122
|
+
"""``(max_datums_per_chunk, max_bytes_per_chunk)``."""
|
|
123
|
+
return self.fwdbwd_max_chunk_len, self.fwdbwd_max_chunk_bytes_count
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Heartbeat:
|
|
127
|
+
"""Background keep-alive for one session.
|
|
128
|
+
|
|
129
|
+
Runs on a daemon thread: a forgotten heartbeat must never prevent a process
|
|
130
|
+
from exiting. Failures are logged and retried on the next tick -- a single
|
|
131
|
+
missed beat is survivable, and raising from a background thread would be
|
|
132
|
+
both unhelpful and unobservable.
|
|
133
|
+
|
|
134
|
+
The exception is a *terminal* failure, such as the server answering 410
|
|
135
|
+
Gone because it reclaimed the session. Retrying that forever would be noise
|
|
136
|
+
on the network and in the log, so an exception listed in ``stop_on`` ends
|
|
137
|
+
the loop instead.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
beat: Callable[[], None],
|
|
143
|
+
*,
|
|
144
|
+
interval: float = DEFAULT_HEARTBEAT_SECONDS,
|
|
145
|
+
name: str = "mind-recursive-heartbeat",
|
|
146
|
+
stop_on: tuple[type[BaseException], ...] = (),
|
|
147
|
+
) -> None:
|
|
148
|
+
if not (interval > 0) or interval != interval or interval == float("inf"):
|
|
149
|
+
raise ValueError(f"heartbeat interval must be a finite positive number, got {interval!r}")
|
|
150
|
+
self._beat = beat
|
|
151
|
+
self._interval = interval
|
|
152
|
+
self._name = name
|
|
153
|
+
self._stop_on = stop_on
|
|
154
|
+
self._stop = threading.Event()
|
|
155
|
+
self._thread: threading.Thread | None = None
|
|
156
|
+
self._consecutive_failures = 0
|
|
157
|
+
self._terminal_error: BaseException | None = None
|
|
158
|
+
|
|
159
|
+
def start(self) -> None:
|
|
160
|
+
"""Start beating. Idempotent."""
|
|
161
|
+
if self._thread is not None:
|
|
162
|
+
return
|
|
163
|
+
self._stop.clear()
|
|
164
|
+
self._thread = threading.Thread(target=self._run, name=self._name, daemon=True)
|
|
165
|
+
self._thread.start()
|
|
166
|
+
|
|
167
|
+
def _run(self) -> None:
|
|
168
|
+
# Wait first: the session was just created, so it is already fresh.
|
|
169
|
+
while not self._stop.wait(self._interval):
|
|
170
|
+
try:
|
|
171
|
+
self._beat()
|
|
172
|
+
self._consecutive_failures = 0
|
|
173
|
+
except Exception as exc: # noqa: BLE001 - a heartbeat must not crash
|
|
174
|
+
if self._stop_on and isinstance(exc, self._stop_on):
|
|
175
|
+
self._terminal_error = exc
|
|
176
|
+
log.info("session heartbeat stopped: %s", exc)
|
|
177
|
+
return
|
|
178
|
+
self._consecutive_failures += 1
|
|
179
|
+
log.warning(
|
|
180
|
+
"session heartbeat failed (%d consecutive): %s",
|
|
181
|
+
self._consecutive_failures,
|
|
182
|
+
exc,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
def stop(self, timeout: float = 2.0) -> None:
|
|
186
|
+
"""Stop beating and join the thread.
|
|
187
|
+
|
|
188
|
+
Must be called before finishing a session: the ordering (stop, then
|
|
189
|
+
report the terminal state) is the same constraint the training
|
|
190
|
+
package's reporter observes.
|
|
191
|
+
"""
|
|
192
|
+
self._stop.set()
|
|
193
|
+
thread, self._thread = self._thread, None
|
|
194
|
+
if thread is not None:
|
|
195
|
+
thread.join(timeout=timeout)
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def running(self) -> bool:
|
|
199
|
+
thread = self._thread
|
|
200
|
+
return thread is not None and thread.is_alive()
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def consecutive_failures(self) -> int:
|
|
204
|
+
"""Failed beats since the last success -- surfaced in ``sys.*`` metrics."""
|
|
205
|
+
return self._consecutive_failures
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def terminal_error(self) -> BaseException | None:
|
|
209
|
+
"""The ``stop_on`` exception that ended the loop, if one did."""
|
|
210
|
+
return self._terminal_error
|
|
211
|
+
|
|
212
|
+
def __enter__(self) -> Heartbeat:
|
|
213
|
+
self.start()
|
|
214
|
+
return self
|
|
215
|
+
|
|
216
|
+
def __exit__(self, *_exc: object) -> None:
|
|
217
|
+
self.stop()
|