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.
@@ -0,0 +1,191 @@
1
+ """mind_recursive -- the Mind Recursive platform's Python SDK.
2
+
3
+ Low-level training and sampling against the Mind Recursive platform, for people who write their own
4
+ training loop, plus the session-less platform resources on ``UserClient``:
5
+ datasets (``uc.datasets``), managed training runs with their records, metrics
6
+ and events (``uc.training``), models (``uc.models``), deployments
7
+ (``uc.deployments``) and calls to them in the OpenAI format
8
+ (``uc.chat.completions.create``). Evaluation stays with the web app.
9
+
10
+ The module name is ``mind_recursive``; ``import mind_recursive as mr`` is the
11
+ short form used in the docs.
12
+
13
+ import mind_recursive
14
+
15
+ sc = mind_recursive.ServiceClient() # opens a session immediately
16
+ trainer = sc.create_lora_trainer(
17
+ base_model="Qwen/Qwen3.8-27B",
18
+ rank=32,
19
+ )
20
+
21
+ sc.log("starting SFT")
22
+
23
+ for step, batch in enumerate(batches):
24
+ out = trainer.forward_backward(batch).result()
25
+ trainer.optim_step().result()
26
+ sc.metric({"loss": out.loss}, step=step, stage="training", total=800)
27
+
28
+ path = trainer.save_weights_only("step-100").result()
29
+ sc.artifact(path, type="sampler_weights")
30
+ sc.summary(final_loss=out.loss)
31
+
32
+ One client, two things made from it. ``ServiceClient`` is the only object that
33
+ holds a connection, a session and the billing identity; the trainer and
34
+ sampler are handles onto server-side resources, so closing the service client
35
+ is the only cleanup there is. Reporting belongs to the client itself: there is
36
+ one writer per session, so ``log`` / ``event`` / ``metric`` / ``artifact`` /
37
+ ``summary`` are methods on ``ServiceClient``.
38
+
39
+ ``from mind_recursive import tinker`` exposes the Tinker-shaped namespace for porting
40
+ existing Tinker or cookbook code, matching Tinker's lowercase import. The
41
+ native ``mind_recursive`` classes keep their own shape; the compatibility namespace is
42
+ where Tinker method shapes live.
43
+
44
+ Importing this package has no side effects: no monkeypatching, no
45
+ ``os.environ`` rewriting. Credentials and URLs resolve when a client is
46
+ constructed, which is what makes it possible to talk to Mind Recursive and
47
+ upstream Tinker from one process.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ from ._config import Config, build_config, normalize_origin
53
+ from ._version import __version__
54
+ from ._errors import (
55
+ APIConnectionError,
56
+ APIError,
57
+ APITimeoutError,
58
+ AuthenticationError,
59
+ BadRequestError,
60
+ ConfigurationError,
61
+ ConflictError,
62
+ FutureTimeoutError,
63
+ GoneError,
64
+ MindRecursiveError,
65
+ NotFoundError,
66
+ PayloadTooLargeError,
67
+ PermissionDeniedError,
68
+ RateLimitError,
69
+ RequestFailedError,
70
+ ServerError,
71
+ SessionClosedError,
72
+ )
73
+ from ._futures import APIFuture
74
+ from ._session import ClientConfig
75
+ from .sampler import Sampler
76
+ from .service import SDK_VERSION, ServiceClient
77
+ from .trainer import LoraTrainer
78
+ from .user import UserClient
79
+ from .platform import (
80
+ Account,
81
+ Dataset,
82
+ DatasetFinding,
83
+ DatasetValidationError,
84
+ Deployment,
85
+ DeploymentError,
86
+ Execution,
87
+ ExecutionEvent,
88
+ ExecutionResult,
89
+ MetricPoint,
90
+ ModelVersion,
91
+ Page,
92
+ PlatformCapabilities,
93
+ ValidationReport,
94
+ )
95
+ from .types import (
96
+ AdamParams,
97
+ Datum,
98
+ LossFnType,
99
+ ModelInfo,
100
+ SamplerKind,
101
+ TensorDtype,
102
+ DmelChunk,
103
+ EncodedTextChunk,
104
+ ForwardBackwardOutput,
105
+ ImageChunk,
106
+ LoraConfig,
107
+ ModelInput,
108
+ PromptAltTokens,
109
+ SampledSequence,
110
+ SampleResponse,
111
+ TopkLogprobs,
112
+ SamplingParams,
113
+ ServerCapabilities,
114
+ SupportedModel,
115
+ TensorData,
116
+ )
117
+
118
+ # 版本号单一事实源见 mind_recursive/_version.py(读 pyproject.toml 的 version)。
119
+
120
+ __all__ = [
121
+ "__version__",
122
+ "SDK_VERSION",
123
+ # the client, and what it creates
124
+ "ServiceClient",
125
+ "UserClient",
126
+ "LoraTrainer",
127
+ "Sampler",
128
+ # config
129
+ "Config",
130
+ "ClientConfig",
131
+ "build_config",
132
+ "normalize_origin",
133
+ # futures
134
+ "APIFuture",
135
+ # data types
136
+ "AdamParams",
137
+ "Datum",
138
+ # the Literals that type the public parameters, so callers can annotate
139
+ # their own helpers with the same names the SDK uses
140
+ "LossFnType",
141
+ "ModelInfo",
142
+ "SamplerKind",
143
+ "TensorDtype",
144
+ "DmelChunk",
145
+ "EncodedTextChunk",
146
+ "ForwardBackwardOutput",
147
+ "ImageChunk",
148
+ "LoraConfig",
149
+ "ModelInput",
150
+ "PromptAltTokens",
151
+ "SampleResponse",
152
+ "SampledSequence",
153
+ "TopkLogprobs",
154
+ "SamplingParams",
155
+ "ServerCapabilities",
156
+ "SupportedModel",
157
+ "TensorData",
158
+ # platform resources (UserClient namespaces)
159
+ "Account",
160
+ "Dataset",
161
+ "DatasetFinding",
162
+ "Deployment",
163
+ "Execution",
164
+ "ExecutionEvent",
165
+ "ExecutionResult",
166
+ "MetricPoint",
167
+ "ModelVersion",
168
+ "Page",
169
+ "PlatformCapabilities",
170
+ "ValidationReport",
171
+ # errors
172
+ "MindRecursiveError",
173
+ "ConfigurationError",
174
+ "APIError",
175
+ "APIConnectionError",
176
+ "APITimeoutError",
177
+ "AuthenticationError",
178
+ "PermissionDeniedError",
179
+ "NotFoundError",
180
+ "BadRequestError",
181
+ "ConflictError",
182
+ "GoneError",
183
+ "PayloadTooLargeError",
184
+ "RateLimitError",
185
+ "ServerError",
186
+ "RequestFailedError",
187
+ "FutureTimeoutError",
188
+ "SessionClosedError",
189
+ "DatasetValidationError",
190
+ "DeploymentError",
191
+ ]
@@ -0,0 +1,317 @@
1
+ """Credential and base-URL resolution.
2
+
3
+ Two rules:
4
+
5
+ 1. **No global state.** Settings resolve when a client is constructed; nothing
6
+ reads or rewrites ``os.environ`` at import time, so one process can talk to
7
+ several backends.
8
+
9
+ 2. **One fixed root.** The SDK takes the platform origin and appends the fixed
10
+ ``/api/mindrsi/v1`` root itself; the planes differ by the path segment after
11
+ it (``/train``, ``/sample``, ``/service``). ``MIND_RECURSIVE_BASE_URL`` is
12
+ therefore the origin -- optionally with that suffix -- and nothing else. Any
13
+ other path is rejected rather than reinterpreted.
14
+
15
+ **One built-in default: production.** With no ``base_url`` argument and no
16
+ ``MIND_RECURSIVE_BASE_URL``, the SDK talks to :data:`DEFAULT_BASE_URL`, so a
17
+ user only has to set ``MIND_RECURSIVE_API_KEY``. Other environments set the
18
+ base URL explicitly; the default is a fallback, never an override.
19
+
20
+ Precedence for both key and URL: explicit argument > environment.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ from dataclasses import dataclass
27
+ from urllib.parse import urlsplit, urlunsplit
28
+
29
+ from ._errors import ConfigurationError
30
+
31
+ __all__ = [
32
+ "Config",
33
+ "resolve_base_urls",
34
+ "resolve_api_key",
35
+ "normalize_origin",
36
+ "MIND_RECURSIVE_PREFIX",
37
+ "SERVICE_SEGMENT",
38
+ "SESSION_SEGMENT",
39
+ "TRAIN_SEGMENT",
40
+ "SAMPLE_SEGMENT",
41
+ "SERVICE_SAMPLE_SEGMENT",
42
+ "SERVICE_TRAIN_SEGMENT",
43
+ "REPORT_SEGMENT",
44
+ "PLATFORM_PREFIX",
45
+ "ENV_API_KEYS",
46
+ "ENV_BASE_URLS",
47
+ "ENV_WEB_URLS",
48
+ "DEFAULT_BASE_URL",
49
+ "DEFAULT_WEB_URL",
50
+ "resolve_web_url",
51
+ "web_session_url",
52
+ ]
53
+
54
+ #: Env names for each setting. Kept as tuples so lookups stay uniform.
55
+ ENV_API_KEYS = ("MIND_RECURSIVE_API_KEY",)
56
+ ENV_BASE_URLS = ("MIND_RECURSIVE_BASE_URL",)
57
+ ENV_WEB_URLS = ("MIND_RECURSIVE_WEB_URL",)
58
+
59
+ #: The production origin, used when neither ``base_url=`` nor
60
+ #: ``MIND_RECURSIVE_BASE_URL`` is set. Point other environments at their
61
+ #: origin explicitly.
62
+ DEFAULT_BASE_URL = "https://mintcn.macaron.xin"
63
+
64
+ #: Web console path for one session. The SDK only *prints* this link -- it is
65
+ #: not an API plane and never receives a request. ``MIND_RECURSIVE_WEB_URL``
66
+ #: overrides it for another deployment.
67
+ DEFAULT_WEB_URL = "https://mintrecursive.mindlab.im/v2train/records/sessions/"
68
+
69
+ ENV_API_KEY = ENV_API_KEYS[0]
70
+ ENV_BASE_URL = ENV_BASE_URLS[0]
71
+ ENV_WEB_URL = ENV_WEB_URLS[0]
72
+
73
+
74
+ def _first_env(names: tuple[str, ...], environ: dict[str, str]) -> str:
75
+ """First non-blank value among ``names``, in preference order."""
76
+ for name in names:
77
+ value = environ.get(name, "").strip()
78
+ if value:
79
+ return value
80
+ return ""
81
+
82
+ #: The one fixed root the SDK appends to the relay origin. There is no
83
+ #: per-plane base URL any more: the planes differ by the path segment after
84
+ #: this root, which names the destination platform (``/train``,
85
+ #: ``/sample``, ``/service``), and the relay routes on it. Keeping one root
86
+ #: means a caller configures an origin, not a plane.
87
+ MIND_RECURSIVE_PREFIX = "/api/mindrsi/v1"
88
+
89
+ #: Path segment for connectivity and negotiation: capability discovery,
90
+ #: health, and the client behaviour config. None of it is about training.
91
+ SERVICE_SEGMENT = "/service"
92
+
93
+ #: Path segment for session lifecycle: create, heartbeat, finish.
94
+ #: A session is the container both trainers and samplers live in, so its
95
+ #: lifecycle is not a training-plane concept and does not hang under ``/train``.
96
+ #: It is owned by the platform service, so it sits under ``/service``.
97
+ SESSION_SEGMENT = "/service/session"
98
+
99
+ #: Path segment for the training plane (session, model, steps, weights, and the
100
+ #: future that belongs to a training call).
101
+ TRAIN_SEGMENT = "/train"
102
+
103
+ #: Path segment for the sampling plane (sampling session, ``asample``, and the
104
+ #: future that belongs to a sampling call).
105
+ SAMPLE_SEGMENT = "/sample"
106
+
107
+ #: Path segment for creating a sampler whose weights come from training (a
108
+ #: saved ``model_path``). The inference service can only serve a path once it is deployed,
109
+ #: and that temporary deployment is owned by the platform service, so this
110
+ #: create goes through ``/service`` and resolves via the service plane's
111
+ #: future. A sampler keyed on a public ``base_model`` instead names an
112
+ #: already-deployed model and stays relay-direct on ``/sample``.
113
+ SERVICE_SAMPLE_SEGMENT = "/service/sample"
114
+
115
+ #: Path segment for creating a trainer. The platform service owns the
116
+ #: training control plane: it records each trainer under the session and
117
+ #: releases it when the session ends, so ``create_model`` and
118
+ #: ``create_model_from_state`` go through ``/service`` and resolve via the
119
+ #: service plane's future. Training steps stay relay-direct on ``/train``.
120
+ SERVICE_TRAIN_SEGMENT = "/service/train"
121
+
122
+ #: Path segment for the SDK's session reports: log / metric / artifact /
123
+ #: summary, keyed by the client's own ``session_id``.
124
+ REPORT_SEGMENT = "/service/report"
125
+
126
+ #: The platform API root: datasets, managed training, models and deployments
127
+ #: (``mind_recursive.platform``). A sibling of :data:`MIND_RECURSIVE_PREFIX`,
128
+ #: not a segment under it.
129
+ PLATFORM_PREFIX = "/api/mint/cli/v1"
130
+
131
+
132
+ def normalize_origin(url: str) -> str:
133
+ """Reduce an accepted base-URL spelling to a bare relay origin.
134
+
135
+ Accepts the origin with or without the fixed ``/api/mindrsi/v1`` suffix, and
136
+ rejects any other path. There is deliberately no ``/train`` handling: the
137
+ old spelling was exactly the confusion this design removes, so it fails
138
+ loudly instead of being silently reinterpreted.
139
+
140
+ >>> normalize_origin("https://relay.example.com")
141
+ 'https://relay.example.com'
142
+ >>> normalize_origin("https://relay.example.com/api/mindrsi/v1/")
143
+ 'https://relay.example.com'
144
+
145
+ Raises:
146
+ ConfigurationError: not an absolute http(s) URL, carries a
147
+ query/fragment, or carries a path other than the fixed prefix.
148
+ """
149
+ raw = (url or "").strip()
150
+ if not raw:
151
+ raise ConfigurationError("base_url is empty")
152
+ parts = urlsplit(raw)
153
+ if parts.scheme not in ("http", "https"):
154
+ raise ConfigurationError(
155
+ f"base_url must be an absolute http(s) URL, got {raw!r}"
156
+ )
157
+ if not parts.netloc:
158
+ raise ConfigurationError(f"base_url has no host: {raw!r}")
159
+ if parts.query or parts.fragment:
160
+ raise ConfigurationError(
161
+ f"base_url must not carry a query or fragment, got {raw!r}"
162
+ )
163
+ path = parts.path.rstrip("/")
164
+ if path.endswith(MIND_RECURSIVE_PREFIX):
165
+ path = path[: -len(MIND_RECURSIVE_PREFIX)]
166
+ path = path.rstrip("/")
167
+ if path:
168
+ raise ConfigurationError(
169
+ f"base_url must be the relay origin (optionally with the fixed "
170
+ f"{MIND_RECURSIVE_PREFIX} suffix), got path {parts.path!r}. The SDK "
171
+ f"appends {MIND_RECURSIVE_PREFIX} itself; do not pass /train or a full "
172
+ f"endpoint."
173
+ )
174
+ return urlunsplit((parts.scheme, parts.netloc, "", "", ""))
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class Config:
179
+ """Resolved connection settings. Immutable; built once per client."""
180
+
181
+ api_key: str
182
+ origin: str
183
+ #: ``origin + MIND_RECURSIVE_PREFIX`` -- the one fixed root every call hangs off.
184
+ api_base_url: str
185
+ service_base_url: str
186
+ session_base_url: str
187
+ train_base_url: str
188
+ sample_base_url: str
189
+ service_sample_base_url: str
190
+ service_train_base_url: str
191
+ report_base_url: str
192
+ #: ``origin + PLATFORM_PREFIX``. Defaulted so a hand-built ``Config``
193
+ #: from before the platform calls existed still constructs.
194
+ platform_base_url: str = ""
195
+ #: Web console base for one session; a link is this plus the session id.
196
+ #: Printed on session creation, never called.
197
+ web_url: str = DEFAULT_WEB_URL
198
+ timeout: float = 600.0
199
+ connect_timeout: float = 30.0
200
+ max_retries: int = 3
201
+ #: ``trust_env=False`` on the httpx client. A local SOCKS proxy picked up
202
+ #: from the ambient environment has previously hijacked traffic that was
203
+ #: meant to stay on the relay path; the platform's billing and
204
+ #: reporter clients set this for the same reason.
205
+ trust_env: bool = False
206
+
207
+ def redacted(self) -> dict[str, str]:
208
+ """Loggable form -- never includes the key."""
209
+ tail = self.api_key[-4:] if len(self.api_key) >= 4 else "?"
210
+ return {"origin": self.origin, "api_key": f"sk-...{tail}"}
211
+
212
+
213
+ def resolve_api_key(api_key: str | None, env: dict[str, str] | None = None) -> str:
214
+ """Resolve the API key: argument, then ``MIND_RECURSIVE_API_KEY``.
215
+
216
+ The key's prefix is not validated locally; the server decides.
217
+ """
218
+ environ = os.environ if env is None else env
219
+ if api_key is not None:
220
+ key = api_key.strip()
221
+ else:
222
+ key = _first_env(ENV_API_KEYS, environ)
223
+ if not key:
224
+ raise ConfigurationError(
225
+ f"no API key: pass api_key=... or set {ENV_API_KEYS[0]}; "
226
+ "user keys start with 'sk-'"
227
+ )
228
+ return key
229
+
230
+
231
+ def resolve_web_url(env: dict[str, str] | None = None) -> str:
232
+ """Resolve the web-console base: ``MIND_RECURSIVE_WEB_URL``, else default.
233
+
234
+ This URL is only used to build the link printed when a session opens; it
235
+ is not an API endpoint, so it is not validated as one.
236
+ """
237
+ environ = os.environ if env is None else env
238
+ return _first_env(ENV_WEB_URLS, environ) or DEFAULT_WEB_URL
239
+
240
+
241
+ def web_session_url(web_url: str, session_id: str) -> str:
242
+ """Join the console base and a session id with exactly one slash."""
243
+ return f"{web_url.rstrip('/')}/{session_id}"
244
+
245
+
246
+ def resolve_base_urls(
247
+ base_url: str | None = None,
248
+ env: dict[str, str] | None = None,
249
+ ) -> dict[str, str]:
250
+ """Resolve per-plane base URLs from one relay origin.
251
+
252
+ Precedence: ``base_url`` argument > ``MIND_RECURSIVE_BASE_URL`` >
253
+ :data:`DEFAULT_BASE_URL` (production).
254
+
255
+ Returns:
256
+ ``{"origin", "api", "service", "session", "train", "sample", "report",
257
+ "platform"}``.
258
+
259
+ Raises:
260
+ ConfigurationError: an explicitly given base URL is empty or unusable.
261
+ """
262
+ environ = os.environ if env is None else env
263
+ if base_url is not None:
264
+ raw = base_url.strip()
265
+ if not raw:
266
+ raise ConfigurationError(
267
+ "base_url is empty: pass the relay origin, or omit it to use "
268
+ f"{ENV_BASE_URLS[0]} / the default {DEFAULT_BASE_URL}"
269
+ )
270
+ else:
271
+ raw = _first_env(ENV_BASE_URLS, environ) or DEFAULT_BASE_URL
272
+ origin = normalize_origin(raw)
273
+ api = origin + MIND_RECURSIVE_PREFIX
274
+ return {
275
+ "origin": origin,
276
+ "api": api,
277
+ "service": api + SERVICE_SEGMENT,
278
+ "session": api + SESSION_SEGMENT,
279
+ "train": api + TRAIN_SEGMENT,
280
+ "sample": api + SAMPLE_SEGMENT,
281
+ "service_sample": api + SERVICE_SAMPLE_SEGMENT,
282
+ "service_train": api + SERVICE_TRAIN_SEGMENT,
283
+ "report": api + REPORT_SEGMENT,
284
+ "platform": origin + PLATFORM_PREFIX,
285
+ }
286
+
287
+
288
+ def build_config(
289
+ *,
290
+ api_key: str | None = None,
291
+ base_url: str | None = None,
292
+ timeout: float = 600.0,
293
+ connect_timeout: float = 30.0,
294
+ max_retries: int = 3,
295
+ trust_env: bool = False,
296
+ env: dict[str, str] | None = None,
297
+ ) -> Config:
298
+ """Assemble a :class:`Config` from arguments and environment."""
299
+ urls = resolve_base_urls(base_url, env)
300
+ return Config(
301
+ api_key=resolve_api_key(api_key, env),
302
+ origin=urls["origin"],
303
+ api_base_url=urls["api"],
304
+ service_base_url=urls["service"],
305
+ session_base_url=urls["session"],
306
+ train_base_url=urls["train"],
307
+ sample_base_url=urls["sample"],
308
+ service_sample_base_url=urls["service_sample"],
309
+ service_train_base_url=urls["service_train"],
310
+ report_base_url=urls["report"],
311
+ platform_base_url=urls["platform"],
312
+ web_url=resolve_web_url(env),
313
+ timeout=timeout,
314
+ connect_timeout=connect_timeout,
315
+ max_retries=max_retries,
316
+ trust_env=trust_env,
317
+ )
@@ -0,0 +1,72 @@
1
+ """Terminal echo for user-facing SDK events.
2
+
3
+ The reporting surface has two audiences. ``sc.log`` / ``sc.metric`` /
4
+ ``sc.artifact`` write to the web console, but the person running the script is
5
+ looking at a terminal, and a training script that has to add its own ``print``
6
+ next to every report is a worse experience than one that does not. These
7
+ methods therefore echo the same information locally.
8
+
9
+ **Why logging, not print.** A library that prints cannot be silenced, pollutes
10
+ stdout, and gives no way to route the text into the caller's own log file.
11
+ ``logging`` keeps stdout clean for program output and lets a caller raise the
12
+ level to hide the echo. To stay zero-config for a plain script, a ``stderr``
13
+ handler is installed on the ``mind_recursive`` logger the first time anything
14
+ is emitted -- but only when the application has not configured logging itself
15
+ (no handler on either the package logger or the root logger). An application
16
+ that configures logging keeps full control.
17
+
18
+ This module is deliberately tiny and import-free apart from the standard
19
+ library; importing the package must not configure handlers as a side effect.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ import sys
26
+
27
+ __all__ = ["emit"]
28
+
29
+ #: One logger name for everything the SDK echoes, so a caller can silence the
30
+ #: SDK with ``logging.getLogger("mind_recursive").setLevel(logging.WARNING)``.
31
+ LOGGER_NAME = "mind_recursive"
32
+
33
+ _handler_checked = False
34
+
35
+
36
+ def _ensure_handler() -> None:
37
+ """Install the zero-config stderr handler once, if the app has not.
38
+
39
+ Runs at first emit rather than at import: importing a library must not
40
+ configure logging behind the application's back. When the application has
41
+ already attached a handler (root or package), it owns formatting and
42
+ filtering, so nothing is added and no duplicate lines appear.
43
+ """
44
+ global _handler_checked
45
+ if _handler_checked:
46
+ return
47
+ _handler_checked = True
48
+
49
+ logger = logging.getLogger(LOGGER_NAME)
50
+ if logger.handlers or logging.getLogger().handlers:
51
+ return
52
+
53
+ handler = logging.StreamHandler(stream=sys.stderr)
54
+ handler.setFormatter(logging.Formatter("%(message)s"))
55
+ logger.addHandler(handler)
56
+ # Respect an explicit level the caller set before the first report; only
57
+ # pick INFO when nobody has expressed a preference.
58
+ if logger.level == logging.NOTSET:
59
+ logger.setLevel(logging.INFO)
60
+
61
+
62
+ def emit(message: str, *, level: int = logging.INFO) -> None:
63
+ """Echo one line to the terminal.
64
+
65
+ Best-effort by construction: a logging failure must never turn a training
66
+ call into an exception, for the same reason reporting is best-effort.
67
+ """
68
+ try:
69
+ _ensure_handler()
70
+ logging.getLogger(LOGGER_NAME).log(level, message)
71
+ except Exception: # noqa: BLE001 - echoing must not break training
72
+ pass