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,335 @@
|
|
|
1
|
+
"""``Reporter``: the HTTP write path behind ``sc.log/metric/...``.
|
|
2
|
+
|
|
3
|
+
Reports are sent over the client's own transport to the report base,
|
|
4
|
+
``{origin}/api/mindrsi/v1/service/report/{session_id}/{events,log,artifact,summary}`` --
|
|
5
|
+
the shapes the reporting service exposes, mounted where a relay user
|
|
6
|
+
can reach them. The key is the SDK's own ``session_id``; the SDK has no
|
|
7
|
+
"execution" concept. There is no local-only mode and no opt-in switch: a
|
|
8
|
+
reporting call is an HTTP call, using the same connection, credentials and
|
|
9
|
+
retry policy as the rest of the run.
|
|
10
|
+
|
|
11
|
+
It stays best-effort: a reporting failure is logged and swallowed, because a
|
|
12
|
+
metrics endpoint being down must not kill a GPU training run. Shapes are
|
|
13
|
+
validated against the upstream contract before the request, so a payload that
|
|
14
|
+
would be rejected leaves a clear local warning instead of an opaque 400.
|
|
15
|
+
|
|
16
|
+
Reading reports back is a console/platform concern, not part of this SDK.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from . import _protocol as P
|
|
27
|
+
from ._console import emit
|
|
28
|
+
|
|
29
|
+
__all__ = ["Reporter", "SYS_PREFIX"]
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger("mind_recursive.reporter")
|
|
32
|
+
|
|
33
|
+
#: Namespace for metrics the SDK reports on its own behalf. Keeping these
|
|
34
|
+
#: separate matters: a user metric colliding with a built-in would hit the
|
|
35
|
+
#: server's type lock and get the whole report rejected.
|
|
36
|
+
SYS_PREFIX = "sys."
|
|
37
|
+
|
|
38
|
+
#: ``kind`` -> full report path. ``log`` and ``event`` share ``/events``: a
|
|
39
|
+
#: log line *is* an event upstream. Metrics go to ``/log``, which is the
|
|
40
|
+
#: upstream listener's name for it.
|
|
41
|
+
_ROUTES = {
|
|
42
|
+
"event": P.PATH_REPORT_EVENTS,
|
|
43
|
+
"log": P.PATH_REPORT_EVENTS,
|
|
44
|
+
"metric": P.PATH_REPORT_METRIC,
|
|
45
|
+
"artifact": P.PATH_REPORT_ARTIFACT,
|
|
46
|
+
"summary": P.PATH_REPORT_SUMMARY,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#: Reporting is not the training path: a report may wait a little, but a dead
|
|
50
|
+
#: endpoint must not hold a step for minutes.
|
|
51
|
+
REPORT_TIMEOUT = 10.0
|
|
52
|
+
REPORT_MAX_RETRIES = 1
|
|
53
|
+
|
|
54
|
+
_LEVELS = ("debug", "info", "warning", "error")
|
|
55
|
+
|
|
56
|
+
#: ``level`` as spelled on the wire -> ``logging`` level for the terminal echo.
|
|
57
|
+
_TERMINAL_LEVELS = {
|
|
58
|
+
"debug": logging.DEBUG,
|
|
59
|
+
"info": logging.INFO,
|
|
60
|
+
"warning": logging.WARNING,
|
|
61
|
+
"error": logging.ERROR,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _echo_log(message: str, level: str, step: int | None) -> None:
|
|
66
|
+
"""Echo a user log line to the terminal, beside the web report."""
|
|
67
|
+
prefix = f"step={step} " if step is not None else ""
|
|
68
|
+
emit(f"log: {prefix}{message}", level=_TERMINAL_LEVELS.get(level, logging.INFO))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _echo_metric(metrics: dict[str, Any], step: int, stage: str | None) -> None:
|
|
72
|
+
label = f" [{stage}]" if stage else ""
|
|
73
|
+
emit(f"metric{label} step={step}: {metrics}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _echo_artifact(uri: str, artifact_type: str, name: str | None) -> None:
|
|
77
|
+
suffix = f" (name={name})" if name else ""
|
|
78
|
+
emit(f"artifact {artifact_type}: {uri}{suffix}")
|
|
79
|
+
|
|
80
|
+
#: Upstream limits, enforced here so a shape that the reporting service would
|
|
81
|
+
#: reject does not pass silently. Sources: event field caps in
|
|
82
|
+
#: ``internal/biz/biz_execution/report_events.go:26-40``; the artifact byte cap
|
|
83
|
+
#: is ``REPORT_MAX_ARTIFACT_BYTES``, default 8 KiB.
|
|
84
|
+
MAX_EVENT_ID_CHARS = 64
|
|
85
|
+
MAX_EVENT_TYPE_BYTES = 128
|
|
86
|
+
MAX_EVENT_CODE_CHARS = 128
|
|
87
|
+
MAX_EVENT_MESSAGE_CHARS = 2048
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _now_ms() -> int:
|
|
91
|
+
return int(time.time() * 1000)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Reporter:
|
|
95
|
+
"""The reporting surface behind ``ServiceClient.log/metric/...``.
|
|
96
|
+
|
|
97
|
+
One reporter per client, owned by the client itself. It is not created by
|
|
98
|
+
the caller and not exposed on the package surface: there is exactly one
|
|
99
|
+
writer for a session, and its methods are the ``ServiceClient``'s methods.
|
|
100
|
+
|
|
101
|
+
Every method is an HTTP write (see the module docstring), best-effort and
|
|
102
|
+
never raising: reporting must not break training.
|
|
103
|
+
|
|
104
|
+
Example::
|
|
105
|
+
|
|
106
|
+
sc = mind_recursive.ServiceClient()
|
|
107
|
+
sc.log("starting on Qwen/Qwen3.8-27B")
|
|
108
|
+
for step, batch in enumerate(batches):
|
|
109
|
+
out = tc.forward_backward(batch).result()
|
|
110
|
+
tc.optim_step().result()
|
|
111
|
+
sc.metric({"loss": out.loss}, step=step, total=800)
|
|
112
|
+
sc.summary(final_loss=0.42)
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(self, *, service: Any) -> None:
|
|
116
|
+
self._service = service
|
|
117
|
+
self._lock = threading.Lock()
|
|
118
|
+
self._seq = 0
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def reporter_id(self) -> str | None:
|
|
122
|
+
"""``{session_id}:reporter``, or ``None`` once the client is closed.
|
|
123
|
+
|
|
124
|
+
Derived the same way a model id is, so the single reporter is
|
|
125
|
+
addressable as a resource inside its session rather than anonymous.
|
|
126
|
+
"""
|
|
127
|
+
session_id = getattr(self._service, "session_id", None)
|
|
128
|
+
if session_id is None:
|
|
129
|
+
return None
|
|
130
|
+
return f"{session_id}:reporter"
|
|
131
|
+
|
|
132
|
+
# -- reporting ------------------------------------------------------------
|
|
133
|
+
def log(
|
|
134
|
+
self,
|
|
135
|
+
message: str,
|
|
136
|
+
*,
|
|
137
|
+
level: str = "info",
|
|
138
|
+
step: int | None = None,
|
|
139
|
+
) -> None:
|
|
140
|
+
"""Record one runtime log line. Sugar over :meth:`event` with ``type="log"``.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
message: human-readable text.
|
|
144
|
+
level: ``debug`` | ``info`` | ``warning`` | ``error``.
|
|
145
|
+
step: optional step number, to line the log up with metrics.
|
|
146
|
+
"""
|
|
147
|
+
try:
|
|
148
|
+
message = str(message)
|
|
149
|
+
_echo_log(message, level, step)
|
|
150
|
+
self.event("log", level=level, message=message, step=step)
|
|
151
|
+
except Exception as exc: # noqa: BLE001 - reporting must not break training
|
|
152
|
+
log.warning("reporter.log failed (ignored): %s", exc)
|
|
153
|
+
|
|
154
|
+
def event(
|
|
155
|
+
self,
|
|
156
|
+
type: str, # noqa: A002 - the contract field is named "type"
|
|
157
|
+
*,
|
|
158
|
+
level: str = "info",
|
|
159
|
+
code: str | None = None,
|
|
160
|
+
message: str | None = None,
|
|
161
|
+
data: dict[str, Any] | None = None,
|
|
162
|
+
step: int | None = None,
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Record a structured timeline event.
|
|
165
|
+
|
|
166
|
+
``log`` is a special case: ``log(text)`` is ``event("log", message=text)``.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
type: dotted open-set name, e.g. ``upstream.retrying``. Upstream
|
|
170
|
+
requires ``^[a-z0-9_.]+$``, at most 128 bytes.
|
|
171
|
+
level: ``debug`` | ``info`` | ``warning`` | ``error``.
|
|
172
|
+
code: machine-readable reason code, e.g. ``429``.
|
|
173
|
+
message: human-readable text.
|
|
174
|
+
data: structured extras (must be a JSON object, not a list).
|
|
175
|
+
step: optional step number, to line the event up with metrics.
|
|
176
|
+
"""
|
|
177
|
+
try:
|
|
178
|
+
with self._lock:
|
|
179
|
+
self._seq += 1
|
|
180
|
+
seq = self._seq
|
|
181
|
+
event: dict[str, Any] = {
|
|
182
|
+
"id": f"{seq:08d}-{_now_ms()}"[:MAX_EVENT_ID_CHARS],
|
|
183
|
+
"seq": seq,
|
|
184
|
+
"ts": _now_ms(),
|
|
185
|
+
"type": str(type)[:MAX_EVENT_TYPE_BYTES],
|
|
186
|
+
"level": level if level in _LEVELS else "info",
|
|
187
|
+
}
|
|
188
|
+
if message is not None:
|
|
189
|
+
event["message"] = str(message)[:MAX_EVENT_MESSAGE_CHARS]
|
|
190
|
+
if code:
|
|
191
|
+
event["code"] = str(code)[:MAX_EVENT_CODE_CHARS]
|
|
192
|
+
if data:
|
|
193
|
+
# Upstream rejects a non-object ``data`` for the whole batch.
|
|
194
|
+
if not isinstance(data, dict):
|
|
195
|
+
raise TypeError(
|
|
196
|
+
f"event data must be a dict, got {data.__class__.__name__}"
|
|
197
|
+
)
|
|
198
|
+
event["data"] = data
|
|
199
|
+
if step is not None:
|
|
200
|
+
event["step"] = int(step)
|
|
201
|
+
self._record("event", event)
|
|
202
|
+
except Exception as exc: # noqa: BLE001 - reporting must not break training
|
|
203
|
+
log.warning("reporter.event failed (ignored): %s", exc)
|
|
204
|
+
|
|
205
|
+
def metric(
|
|
206
|
+
self,
|
|
207
|
+
metrics: dict[str, Any],
|
|
208
|
+
*,
|
|
209
|
+
step: int,
|
|
210
|
+
stage: str | None = None,
|
|
211
|
+
total: int | None = None,
|
|
212
|
+
timings: dict[str, float] | None = None,
|
|
213
|
+
counters: dict[str, int] | None = None,
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Record one step's metrics.
|
|
216
|
+
|
|
217
|
+
Values follow the server's metric type system: scalars, or objects
|
|
218
|
+
carrying ``_type``. A key's type is locked by its first non-null value
|
|
219
|
+
upstream, so a later type change would be rejected there.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
metrics: this step's values. ``None`` values are dropped rather
|
|
223
|
+
than sent, since a null would otherwise occupy a key without
|
|
224
|
+
locking its type.
|
|
225
|
+
step: the step number. Points are upserted by step.
|
|
226
|
+
stage: optional label such as ``training`` or ``evaling``.
|
|
227
|
+
total: revised total step count, for progress display.
|
|
228
|
+
timings: named durations for this step. Emitted as the
|
|
229
|
+
``sys.step_seconds`` distribution.
|
|
230
|
+
counters: named counters for this step. Emitted as ``sys.<name>``.
|
|
231
|
+
"""
|
|
232
|
+
try:
|
|
233
|
+
payload = {k: v for k, v in metrics.items() if v is not None}
|
|
234
|
+
if timings:
|
|
235
|
+
labels = sorted(timings)
|
|
236
|
+
payload[f"{SYS_PREFIX}step_seconds"] = {
|
|
237
|
+
"_type": "distribution",
|
|
238
|
+
"labels": labels,
|
|
239
|
+
"values": [round(max(timings[k], 0.0), 6) for k in labels],
|
|
240
|
+
"unit": "s",
|
|
241
|
+
"_render": "stack",
|
|
242
|
+
}
|
|
243
|
+
for name, value in (counters or {}).items():
|
|
244
|
+
payload[f"{SYS_PREFIX}{name}"] = value
|
|
245
|
+
body: dict[str, Any] = {"ts": _now_ms(), "step": int(step), "metrics": payload}
|
|
246
|
+
if stage is not None:
|
|
247
|
+
body["stage"] = stage
|
|
248
|
+
if total is not None:
|
|
249
|
+
body["total"] = total
|
|
250
|
+
_echo_metric(payload, step, stage)
|
|
251
|
+
self._record("metric", body)
|
|
252
|
+
except Exception as exc: # noqa: BLE001 - reporting must not break training
|
|
253
|
+
log.warning("reporter.metric failed (ignored): %s", exc)
|
|
254
|
+
|
|
255
|
+
def artifact(
|
|
256
|
+
self,
|
|
257
|
+
uri: str,
|
|
258
|
+
*,
|
|
259
|
+
type: str, # noqa: A002 - the contract field is named "type"
|
|
260
|
+
name: str | None = None,
|
|
261
|
+
version: str | None = None,
|
|
262
|
+
description: str | None = None,
|
|
263
|
+
metadata: dict[str, Any] | None = None,
|
|
264
|
+
) -> None:
|
|
265
|
+
"""Record a produced artefact by reference. Append-only.
|
|
266
|
+
|
|
267
|
+
Only the pointer is kept; the bytes are never fetched. ``uri`` must
|
|
268
|
+
carry a scheme -- ``mint://``, ``oss://``, ``hf://``, ``https://``.
|
|
269
|
+
Upstream rejects a bare string, ``javascript:`` and ``data:``.
|
|
270
|
+
"""
|
|
271
|
+
try:
|
|
272
|
+
text = str(uri)
|
|
273
|
+
if "://" not in text:
|
|
274
|
+
raise ValueError(f"artifact uri needs a scheme: {text!r}")
|
|
275
|
+
body: dict[str, Any] = {"ts": _now_ms(), "type": type, "uri": text}
|
|
276
|
+
for key, value in (
|
|
277
|
+
("name", name),
|
|
278
|
+
("version", version),
|
|
279
|
+
("description", description),
|
|
280
|
+
("metadata", metadata),
|
|
281
|
+
):
|
|
282
|
+
if value is not None:
|
|
283
|
+
body[key] = value
|
|
284
|
+
_echo_artifact(text, type, name)
|
|
285
|
+
self._record("artifact", body)
|
|
286
|
+
except Exception as exc: # noqa: BLE001
|
|
287
|
+
log.warning("reporter.artifact failed (ignored): %s", exc)
|
|
288
|
+
|
|
289
|
+
def summary(self, mapping: dict[str, Any] | None = None, /, **kwargs: Any) -> None:
|
|
290
|
+
"""Record terminal scalars. Merged by key, last write wins.
|
|
291
|
+
|
|
292
|
+
``summary(final_loss=0.4)`` and ``summary({"final_loss": 0.4})`` are
|
|
293
|
+
equivalent and may be mixed.
|
|
294
|
+
"""
|
|
295
|
+
try:
|
|
296
|
+
merged: dict[str, Any] = {}
|
|
297
|
+
if mapping:
|
|
298
|
+
merged.update(mapping)
|
|
299
|
+
merged.update(kwargs)
|
|
300
|
+
self._record("summary", {"ts": _now_ms(), "summary": merged})
|
|
301
|
+
except Exception as exc: # noqa: BLE001
|
|
302
|
+
log.warning("reporter.summary failed (ignored): %s", exc)
|
|
303
|
+
|
|
304
|
+
# -- sink -----------------------------------------------------------------
|
|
305
|
+
def _record(self, kind: str, body: dict[str, Any]) -> None:
|
|
306
|
+
"""POST one report through the service's own transport.
|
|
307
|
+
|
|
308
|
+
Reusing the transport keeps headers, retry policy, pooling and timeouts
|
|
309
|
+
identical to the rest of the run, so a reporting call cannot be the one
|
|
310
|
+
request that behaves differently. ``require_session`` only rules out a
|
|
311
|
+
closed client here: a report belongs to a session, and the client has
|
|
312
|
+
held one since construction.
|
|
313
|
+
|
|
314
|
+
Failures are logged and swallowed: reporting must never break training.
|
|
315
|
+
"""
|
|
316
|
+
try:
|
|
317
|
+
path = _ROUTES[kind]
|
|
318
|
+
session_id = self._service.require_session()
|
|
319
|
+
payload = (
|
|
320
|
+
{"events": [body]} if kind in ("event", "log") else dict(body)
|
|
321
|
+
)
|
|
322
|
+
self._service.transport.request(
|
|
323
|
+
"POST",
|
|
324
|
+
path.format(session_id=session_id),
|
|
325
|
+
base_url=self._service.config.report_base_url,
|
|
326
|
+
pool="control",
|
|
327
|
+
json_body=payload,
|
|
328
|
+
timeout=REPORT_TIMEOUT,
|
|
329
|
+
max_retries=REPORT_MAX_RETRIES,
|
|
330
|
+
)
|
|
331
|
+
except Exception as exc: # noqa: BLE001 - reporting must not break training
|
|
332
|
+
log.warning("report %s failed (ignored): %s", kind, exc)
|
|
333
|
+
|
|
334
|
+
def __repr__(self) -> str:
|
|
335
|
+
return f"<Reporter {self.reporter_id or '(no session)'}>"
|