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,213 @@
|
|
|
1
|
+
"""Exception hierarchy.
|
|
2
|
+
|
|
3
|
+
Our own classes, not Tinker's. Users who previously wrote
|
|
4
|
+
``except tinker.XxxError`` have to change those lines; that cost is accepted.
|
|
5
|
+
|
|
6
|
+
Two axes matter to callers:
|
|
7
|
+
|
|
8
|
+
* **retryable** -- transport faults and 429/5xx. The transport layer retries
|
|
9
|
+
these itself; the exception only escapes once the budget is spent.
|
|
10
|
+
* **category** -- ``"user"`` or ``"server"``, carried through from the
|
|
11
|
+
upstream error envelope (``{"error": ..., "category": ...}``) so callers can
|
|
12
|
+
tell "I sent something wrong" from "the backend is unwell" without parsing
|
|
13
|
+
status codes.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"MindRecursiveError",
|
|
20
|
+
"ConfigurationError",
|
|
21
|
+
"APIError",
|
|
22
|
+
"APIConnectionError",
|
|
23
|
+
"APITimeoutError",
|
|
24
|
+
"AuthenticationError",
|
|
25
|
+
"PermissionDeniedError",
|
|
26
|
+
"NotFoundError",
|
|
27
|
+
"BadRequestError",
|
|
28
|
+
"ConflictError",
|
|
29
|
+
"GoneError",
|
|
30
|
+
"PayloadTooLargeError",
|
|
31
|
+
"RateLimitError",
|
|
32
|
+
"ServerError",
|
|
33
|
+
"RequestFailedError",
|
|
34
|
+
"FutureTimeoutError",
|
|
35
|
+
"SessionClosedError",
|
|
36
|
+
"status_to_error",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class MindRecursiveError(Exception):
|
|
41
|
+
"""Base class for everything this SDK raises."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ConfigurationError(MindRecursiveError):
|
|
45
|
+
"""Bad or missing local configuration -- no request was attempted."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class APIError(MindRecursiveError):
|
|
49
|
+
"""An HTTP request reached the relay and came back unusable."""
|
|
50
|
+
|
|
51
|
+
#: Whether retrying the identical request could plausibly succeed.
|
|
52
|
+
retryable: bool = False
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
message: str,
|
|
57
|
+
*,
|
|
58
|
+
status: int | None = None,
|
|
59
|
+
category: str | None = None,
|
|
60
|
+
path: str | None = None,
|
|
61
|
+
body: bytes | None = None,
|
|
62
|
+
code: int | str | None = None,
|
|
63
|
+
request_id: str | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
super().__init__(message)
|
|
66
|
+
self.message = message
|
|
67
|
+
self.status = status
|
|
68
|
+
self.category = category
|
|
69
|
+
self.path = path
|
|
70
|
+
self.body = body
|
|
71
|
+
#: Platform calls only: the server business code (``int``, e.g. 140058)
|
|
72
|
+
#: or the relay entry code (``str``, e.g. ``"credential_rejected"``).
|
|
73
|
+
self.code = code
|
|
74
|
+
#: Relay request id from an entry rejection, for support tickets.
|
|
75
|
+
self.request_id = request_id
|
|
76
|
+
|
|
77
|
+
def __str__(self) -> str:
|
|
78
|
+
bits = [self.message]
|
|
79
|
+
if self.code is not None:
|
|
80
|
+
bits.append(f"code={self.code}")
|
|
81
|
+
if self.status is not None:
|
|
82
|
+
bits.append(f"status={self.status}")
|
|
83
|
+
if self.path:
|
|
84
|
+
bits.append(f"path={self.path}")
|
|
85
|
+
if self.category:
|
|
86
|
+
bits.append(f"category={self.category}")
|
|
87
|
+
return " ".join(bits)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class APIConnectionError(APIError):
|
|
91
|
+
"""The request never produced a response (DNS, TCP, TLS, reset)."""
|
|
92
|
+
|
|
93
|
+
retryable = True
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class APITimeoutError(APIConnectionError):
|
|
97
|
+
"""The request exceeded its timeout budget."""
|
|
98
|
+
|
|
99
|
+
retryable = True
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class AuthenticationError(APIError):
|
|
103
|
+
"""401. The API key is missing, malformed, or rejected."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class PermissionDeniedError(APIError):
|
|
107
|
+
"""403. Authenticated, but not allowed to touch this resource."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class NotFoundError(APIError):
|
|
111
|
+
"""404.
|
|
112
|
+
|
|
113
|
+
On the training plane this is most often the ``/train`` suffix trap rather
|
|
114
|
+
than a genuinely missing resource -- see ``_config.resolve_base_urls``.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class BadRequestError(APIError):
|
|
119
|
+
"""400. The server rejected the request shape."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class ConflictError(APIError):
|
|
123
|
+
"""409. State conflict, e.g. reporting to a sealed session."""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class GoneError(APIError):
|
|
127
|
+
"""410. The resource existed and has been reclaimed."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class PayloadTooLargeError(APIError):
|
|
131
|
+
"""413. Body exceeded a server limit.
|
|
132
|
+
|
|
133
|
+
For ``forward_backward`` this means the chunking budget negotiated through
|
|
134
|
+
``client/config`` was not respected.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class RateLimitError(APIError):
|
|
139
|
+
"""429. Retryable, and ``Retry-After`` is honoured when present."""
|
|
140
|
+
|
|
141
|
+
retryable = True
|
|
142
|
+
|
|
143
|
+
def __init__(self, *args, retry_after: float | None = None, **kwargs) -> None:
|
|
144
|
+
super().__init__(*args, **kwargs)
|
|
145
|
+
self.retry_after = retry_after
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class ServerError(APIError):
|
|
149
|
+
"""5xx. Retryable."""
|
|
150
|
+
|
|
151
|
+
retryable = True
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class RequestFailedError(MindRecursiveError):
|
|
155
|
+
"""The future resolved to ``RequestFailedResponse``.
|
|
156
|
+
|
|
157
|
+
The HTTP call succeeded; the *work* failed. Carries the upstream
|
|
158
|
+
``category`` verbatim -- this is the channel through which backend
|
|
159
|
+
constraints surface, e.g.::
|
|
160
|
+
|
|
161
|
+
UNSUPPORTED: FSDP2 requires beta1=0.9, beta2=0.999, eps=1e-8
|
|
162
|
+
and lora_plus_ratio=1
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(self, error: str, *, category: str | None = None, request_id: str | None = None):
|
|
166
|
+
super().__init__(error)
|
|
167
|
+
self.error = error
|
|
168
|
+
self.category = category
|
|
169
|
+
self.request_id = request_id
|
|
170
|
+
|
|
171
|
+
def __str__(self) -> str:
|
|
172
|
+
prefix = f"[{self.category}] " if self.category else ""
|
|
173
|
+
suffix = f" (request_id={self.request_id})" if self.request_id else ""
|
|
174
|
+
return f"{prefix}{self.error}{suffix}"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class FutureTimeoutError(MindRecursiveError):
|
|
178
|
+
"""``result(timeout=...)`` expired while the request was still pending."""
|
|
179
|
+
|
|
180
|
+
def __init__(self, request_id: str, timeout: float, queue_state: str | None = None):
|
|
181
|
+
state = f", last queue_state={queue_state}" if queue_state else ""
|
|
182
|
+
super().__init__(
|
|
183
|
+
f"future {request_id} did not resolve within {timeout}s{state}"
|
|
184
|
+
)
|
|
185
|
+
self.request_id = request_id
|
|
186
|
+
self.timeout = timeout
|
|
187
|
+
self.queue_state = queue_state
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class SessionClosedError(MindRecursiveError):
|
|
191
|
+
"""The session was closed locally; its clients are no longer usable."""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
#: status -> exception class. 404 and 429 get bespoke handling in the caller.
|
|
195
|
+
_BY_STATUS: dict[int, type[APIError]] = {
|
|
196
|
+
400: BadRequestError,
|
|
197
|
+
401: AuthenticationError,
|
|
198
|
+
403: PermissionDeniedError,
|
|
199
|
+
404: NotFoundError,
|
|
200
|
+
409: ConflictError,
|
|
201
|
+
410: GoneError,
|
|
202
|
+
413: PayloadTooLargeError,
|
|
203
|
+
429: RateLimitError,
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def status_to_error(status: int) -> type[APIError]:
|
|
208
|
+
"""Map an HTTP status onto the exception class to raise."""
|
|
209
|
+
if status in _BY_STATUS:
|
|
210
|
+
return _BY_STATUS[status]
|
|
211
|
+
if status >= 500:
|
|
212
|
+
return ServerError
|
|
213
|
+
return APIError
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""The two-phase future protocol.
|
|
2
|
+
|
|
3
|
+
``create_model``, ``forward_backward``, ``optim_step``, ``save_weights`` and
|
|
4
|
+
friends do not return results. They return a ``request_id``, and the result is
|
|
5
|
+
fetched by polling ``POST /api/v1/retrieve_future``. This is not an optional
|
|
6
|
+
optimisation -- it is the only way to get a result. Observed on the wire::
|
|
7
|
+
|
|
8
|
+
POST /api/v1/create_model
|
|
9
|
+
RESP {"request_id":"01a1d90a-06d8-75e0-8f5e-fa1cc9946e11"}
|
|
10
|
+
|
|
11
|
+
POST /api/v1/retrieve_future
|
|
12
|
+
REQ {"request_id":"01a1d90a-...","allow_metadata_only":true}
|
|
13
|
+
RESP {"model_id":"01a1d90a-054d-76cd-bb63-fd038d4d9897_0"}
|
|
14
|
+
|
|
15
|
+
Polling resolves to one of three things:
|
|
16
|
+
|
|
17
|
+
* a ``try_again`` envelope -- still pending, carrying a ``queue_state`` that
|
|
18
|
+
distinguishes a working queue from one paused on capacity or rate limit;
|
|
19
|
+
* a ``request_failed`` envelope -- the work failed, surfaced as
|
|
20
|
+
:class:`RequestFailedError` with the server's category and message. This is
|
|
21
|
+
how backend constraints arrive, e.g. the FSDP2 Adam-parameter rejection;
|
|
22
|
+
* a real payload, JSON or protobuf depending on the request.
|
|
23
|
+
|
|
24
|
+
``APIFuture.result()`` hides the polling but never hides those outcomes.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import logging
|
|
30
|
+
import random
|
|
31
|
+
import asyncio
|
|
32
|
+
import threading
|
|
33
|
+
import time
|
|
34
|
+
from typing import Any, Awaitable, Callable, Generic, TypeVar
|
|
35
|
+
|
|
36
|
+
from ._errors import FutureTimeoutError, RequestFailedError
|
|
37
|
+
|
|
38
|
+
__all__ = ["APIFuture", "FutureResolver", "QUEUE_STATES"]
|
|
39
|
+
|
|
40
|
+
log = logging.getLogger("mind_recursive.futures")
|
|
41
|
+
|
|
42
|
+
T = TypeVar("T")
|
|
43
|
+
U = TypeVar("U")
|
|
44
|
+
|
|
45
|
+
#: ``try_again.queue_state`` values. ``active`` means the request is simply
|
|
46
|
+
#: not done; the paused states mean the server is deliberately holding it.
|
|
47
|
+
QUEUE_STATES = ("active", "paused_capacity", "paused_rate_limit")
|
|
48
|
+
|
|
49
|
+
_POLL_MIN = 0.05
|
|
50
|
+
_POLL_MAX = 2.0
|
|
51
|
+
#: While the queue is paused there is no point polling fast.
|
|
52
|
+
_POLL_MAX_PAUSED = 10.0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _poll_delay(attempt: int, queue_state: str | None) -> float:
|
|
56
|
+
"""Backoff between polls, slower when the server says it is paused."""
|
|
57
|
+
ceiling = _POLL_MAX_PAUSED if (queue_state or "").startswith("paused") else _POLL_MAX
|
|
58
|
+
target = min(_POLL_MIN * (2 ** min(attempt, 10)), ceiling)
|
|
59
|
+
return random.uniform(_POLL_MIN, max(target, _POLL_MIN))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FutureResolver:
|
|
63
|
+
"""Polls ``retrieve_future`` on behalf of :class:`APIFuture`.
|
|
64
|
+
|
|
65
|
+
Injected rather than inherited so tests can drive futures without HTTP.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
poll: Callable[[str], dict[str, Any] | bytes],
|
|
71
|
+
*,
|
|
72
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
73
|
+
clock: Callable[[], float] = time.monotonic,
|
|
74
|
+
) -> None:
|
|
75
|
+
self._poll = poll
|
|
76
|
+
self._sleep = sleep
|
|
77
|
+
self._clock = clock
|
|
78
|
+
|
|
79
|
+
def resolve(
|
|
80
|
+
self,
|
|
81
|
+
request_id: str,
|
|
82
|
+
*,
|
|
83
|
+
timeout: float | None,
|
|
84
|
+
parse: Callable[[dict[str, Any] | bytes], T],
|
|
85
|
+
) -> T:
|
|
86
|
+
"""Poll until the request resolves.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
request_id: the id returned by the submitting call.
|
|
90
|
+
timeout: wall-clock budget in seconds; ``None`` waits indefinitely.
|
|
91
|
+
Training steps legitimately take minutes, so there is no
|
|
92
|
+
default deadline.
|
|
93
|
+
parse: turns the resolved payload into the caller's type.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
FutureTimeoutError: the budget expired while still pending.
|
|
97
|
+
RequestFailedError: the server reported the work failed.
|
|
98
|
+
"""
|
|
99
|
+
started = self._clock()
|
|
100
|
+
attempt = 0
|
|
101
|
+
queue_state: str | None = None
|
|
102
|
+
|
|
103
|
+
while True:
|
|
104
|
+
payload = self._poll(request_id)
|
|
105
|
+
|
|
106
|
+
# Protobuf bodies are never envelopes; a binary body is the result.
|
|
107
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
108
|
+
return parse(bytes(payload))
|
|
109
|
+
|
|
110
|
+
kind = payload.get("type")
|
|
111
|
+
if kind == "try_again":
|
|
112
|
+
queue_state = payload.get("queue_state") or queue_state
|
|
113
|
+
elif kind == "request_failed" or (
|
|
114
|
+
"error" in payload and "category" in payload
|
|
115
|
+
):
|
|
116
|
+
raise RequestFailedError(
|
|
117
|
+
str(payload.get("error", "request failed")),
|
|
118
|
+
category=payload.get("category"),
|
|
119
|
+
request_id=request_id,
|
|
120
|
+
)
|
|
121
|
+
else:
|
|
122
|
+
return parse(payload)
|
|
123
|
+
|
|
124
|
+
if timeout is not None and self._clock() - started >= timeout:
|
|
125
|
+
raise FutureTimeoutError(request_id, timeout, queue_state)
|
|
126
|
+
|
|
127
|
+
delay = _poll_delay(attempt, queue_state)
|
|
128
|
+
if timeout is not None:
|
|
129
|
+
remaining = timeout - (self._clock() - started)
|
|
130
|
+
if remaining <= 0:
|
|
131
|
+
raise FutureTimeoutError(request_id, timeout, queue_state)
|
|
132
|
+
delay = min(delay, remaining)
|
|
133
|
+
self._sleep(delay)
|
|
134
|
+
attempt += 1
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class AsyncFutureResolver:
|
|
138
|
+
"""Async twin of :class:`FutureResolver`; polls with ``asyncio.sleep``."""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
poll: Callable[[str], Awaitable[dict[str, Any] | bytes]],
|
|
143
|
+
*,
|
|
144
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
145
|
+
clock: Callable[[], float] = time.monotonic,
|
|
146
|
+
) -> None:
|
|
147
|
+
self._poll = poll
|
|
148
|
+
self._sleep = sleep
|
|
149
|
+
self._clock = clock
|
|
150
|
+
|
|
151
|
+
async def resolve(
|
|
152
|
+
self,
|
|
153
|
+
request_id: str,
|
|
154
|
+
*,
|
|
155
|
+
timeout: float | None,
|
|
156
|
+
parse: Callable[[dict[str, Any] | bytes], T],
|
|
157
|
+
) -> T:
|
|
158
|
+
started = self._clock()
|
|
159
|
+
attempt = 0
|
|
160
|
+
queue_state: str | None = None
|
|
161
|
+
|
|
162
|
+
while True:
|
|
163
|
+
payload = await self._poll(request_id)
|
|
164
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
165
|
+
return parse(bytes(payload))
|
|
166
|
+
|
|
167
|
+
kind = payload.get("type")
|
|
168
|
+
if kind == "try_again":
|
|
169
|
+
queue_state = payload.get("queue_state") or queue_state
|
|
170
|
+
elif kind == "request_failed" or (
|
|
171
|
+
"error" in payload and "category" in payload
|
|
172
|
+
):
|
|
173
|
+
raise RequestFailedError(
|
|
174
|
+
str(payload.get("error", "request failed")),
|
|
175
|
+
category=payload.get("category"),
|
|
176
|
+
request_id=request_id,
|
|
177
|
+
)
|
|
178
|
+
else:
|
|
179
|
+
return parse(payload)
|
|
180
|
+
|
|
181
|
+
if timeout is not None and self._clock() - started >= timeout:
|
|
182
|
+
raise FutureTimeoutError(request_id, timeout, queue_state)
|
|
183
|
+
|
|
184
|
+
delay = _poll_delay(attempt, queue_state)
|
|
185
|
+
if timeout is not None:
|
|
186
|
+
remaining = timeout - (self._clock() - started)
|
|
187
|
+
if remaining <= 0:
|
|
188
|
+
raise FutureTimeoutError(request_id, timeout, queue_state)
|
|
189
|
+
delay = min(delay, remaining)
|
|
190
|
+
await self._sleep(delay)
|
|
191
|
+
attempt += 1
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class APIFuture(Generic[T]):
|
|
195
|
+
"""A pending server-side request.
|
|
196
|
+
|
|
197
|
+
Call :meth:`result` to block until it resolves. The result is cached, so
|
|
198
|
+
calling it twice is cheap and does not re-poll.
|
|
199
|
+
|
|
200
|
+
Named and shaped like Tinker's ``APIFuture`` so recipe code ports, but it
|
|
201
|
+
is our class.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
__slots__ = ("_request_id", "_resolver", "_parse", "_value", "_done", "_lock", "_error")
|
|
205
|
+
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
request_id: str,
|
|
209
|
+
resolver: FutureResolver,
|
|
210
|
+
parse: Callable[[dict[str, Any] | bytes], T],
|
|
211
|
+
) -> None:
|
|
212
|
+
self._request_id = request_id
|
|
213
|
+
self._resolver = resolver
|
|
214
|
+
self._parse = parse
|
|
215
|
+
self._value: T | None = None
|
|
216
|
+
self._error: Exception | None = None
|
|
217
|
+
self._done = False
|
|
218
|
+
self._lock = threading.Lock()
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def request_id(self) -> str:
|
|
222
|
+
"""The server-side id, useful in logs and support requests."""
|
|
223
|
+
return self._request_id
|
|
224
|
+
|
|
225
|
+
def done(self) -> bool:
|
|
226
|
+
"""Whether the result has already been fetched."""
|
|
227
|
+
return self._done
|
|
228
|
+
|
|
229
|
+
def result(self, timeout: float | None = None) -> T:
|
|
230
|
+
"""Block until the request resolves and return its payload.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
timeout: seconds to wait. ``None`` (default) waits as long as it
|
|
234
|
+
takes -- a training step is allowed to be slow.
|
|
235
|
+
|
|
236
|
+
Raises:
|
|
237
|
+
FutureTimeoutError: still pending when the budget expired.
|
|
238
|
+
RequestFailedError: the server reported failure.
|
|
239
|
+
"""
|
|
240
|
+
with self._lock:
|
|
241
|
+
if self._done:
|
|
242
|
+
if self._error is not None:
|
|
243
|
+
raise self._error
|
|
244
|
+
return self._value # type: ignore[return-value]
|
|
245
|
+
try:
|
|
246
|
+
value = self._resolver.resolve(
|
|
247
|
+
self._request_id, timeout=timeout, parse=self._parse
|
|
248
|
+
)
|
|
249
|
+
except FutureTimeoutError:
|
|
250
|
+
# A timeout is not terminal: the request is still running and
|
|
251
|
+
# a later, more patient call can still collect it.
|
|
252
|
+
raise
|
|
253
|
+
except Exception as exc:
|
|
254
|
+
self._error = exc
|
|
255
|
+
self._done = True
|
|
256
|
+
raise
|
|
257
|
+
self._value = value
|
|
258
|
+
self._done = True
|
|
259
|
+
return value
|
|
260
|
+
|
|
261
|
+
def map(self, fn: Callable[[T], U]) -> APIFuture[U]:
|
|
262
|
+
"""A future that applies ``fn`` to this future's result.
|
|
263
|
+
|
|
264
|
+
Used by compatibility shells that have to reshape a payload without
|
|
265
|
+
issuing a second request -- for example
|
|
266
|
+
:meth:`mind_recursive.Sampler.compute_logprobs` extracts
|
|
267
|
+
``SampleResponse.prompt_logprobs`` out of the sampling future.
|
|
268
|
+
"""
|
|
269
|
+
return APIFuture(
|
|
270
|
+
self._request_id,
|
|
271
|
+
self._resolver,
|
|
272
|
+
lambda payload: fn(self._parse(payload)),
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
def __repr__(self) -> str:
|
|
276
|
+
state = "done" if self._done else "pending"
|
|
277
|
+
return f"<APIFuture {self._request_id} {state}>"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Hand-written protobuf codec for the two binary messages on the wire.
|
|
2
|
+
|
|
3
|
+
Only ``forward_backward`` (request + its future response) and ``sample``
|
|
4
|
+
responses are protobuf; everything else is JSON. See ``codec`` for the wire
|
|
5
|
+
primitives, ``schema`` for field numbers, and ``encode``/``decode`` for the
|
|
6
|
+
message mappings.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .decode import (
|
|
10
|
+
decode_forward_backward_output,
|
|
11
|
+
decode_sample_response,
|
|
12
|
+
decode_tensor,
|
|
13
|
+
)
|
|
14
|
+
from .encode import encode_datum, encode_forward_backward_request, encode_tensor
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"encode_forward_backward_request",
|
|
18
|
+
"encode_datum",
|
|
19
|
+
"encode_tensor",
|
|
20
|
+
"decode_forward_backward_output",
|
|
21
|
+
"decode_sample_response",
|
|
22
|
+
"decode_tensor",
|
|
23
|
+
]
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Minimal protobuf wire codec.
|
|
2
|
+
|
|
3
|
+
``forward_backward`` is protobuf-only upstream -- ``tinker/resources/training.py``
|
|
4
|
+
hardcodes ``Content-Type: application/x-protobuf`` with no JSON branch -- and its
|
|
5
|
+
future resolves to a protobuf body too. Everything else on the wire is JSON.
|
|
6
|
+
|
|
7
|
+
Rather than depend on ``protobuf`` plus generated modules, we encode and decode
|
|
8
|
+
these two messages by hand. The schema is small, frozen by the server, and
|
|
9
|
+
exercised on every training step, so a few hundred lines of explicit wire
|
|
10
|
+
handling is cheaper than a C-extension dependency.
|
|
11
|
+
|
|
12
|
+
Field numbers below are transcribed from ``tinker/proto/tinker_public_pb2``
|
|
13
|
+
(tinker 0.39.0) and pinned by ``tests/test_proto_golden.py``, which asserts our
|
|
14
|
+
bytes match the generated encoder when it is importable.
|
|
15
|
+
|
|
16
|
+
Wire types used here::
|
|
17
|
+
|
|
18
|
+
0 varint int32/int64/uint32/uint64/bool/enum
|
|
19
|
+
1 fixed64 double
|
|
20
|
+
2 length-delim string/bytes/embedded message/packed repeated
|
|
21
|
+
5 fixed32 float
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import struct
|
|
27
|
+
from typing import Iterator
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"encode_varint",
|
|
31
|
+
"decode_varint",
|
|
32
|
+
"tag",
|
|
33
|
+
"field_varint",
|
|
34
|
+
"field_bytes",
|
|
35
|
+
"field_string",
|
|
36
|
+
"field_double",
|
|
37
|
+
"field_message",
|
|
38
|
+
"iter_fields",
|
|
39
|
+
"WIRE_VARINT",
|
|
40
|
+
"WIRE_FIXED64",
|
|
41
|
+
"WIRE_BYTES",
|
|
42
|
+
"WIRE_FIXED32",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
WIRE_VARINT = 0
|
|
46
|
+
WIRE_FIXED64 = 1
|
|
47
|
+
WIRE_BYTES = 2
|
|
48
|
+
WIRE_FIXED32 = 5
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def encode_varint(value: int) -> bytes:
|
|
52
|
+
"""Base-128 varint. Negative values use two's complement over 64 bits."""
|
|
53
|
+
if value < 0:
|
|
54
|
+
value += 1 << 64
|
|
55
|
+
out = bytearray()
|
|
56
|
+
while True:
|
|
57
|
+
byte = value & 0x7F
|
|
58
|
+
value >>= 7
|
|
59
|
+
if value:
|
|
60
|
+
out.append(byte | 0x80)
|
|
61
|
+
else:
|
|
62
|
+
out.append(byte)
|
|
63
|
+
return bytes(out)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def decode_varint(buf: bytes, pos: int) -> tuple[int, int]:
|
|
67
|
+
"""Read one varint. Returns ``(value, new_pos)``."""
|
|
68
|
+
result = 0
|
|
69
|
+
shift = 0
|
|
70
|
+
while True:
|
|
71
|
+
if pos >= len(buf):
|
|
72
|
+
raise ValueError("truncated varint")
|
|
73
|
+
byte = buf[pos]
|
|
74
|
+
pos += 1
|
|
75
|
+
result |= (byte & 0x7F) << shift
|
|
76
|
+
if not byte & 0x80:
|
|
77
|
+
return result, pos
|
|
78
|
+
shift += 7
|
|
79
|
+
if shift > 63:
|
|
80
|
+
raise ValueError("varint overflows 64 bits")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def tag(number: int, wire_type: int) -> bytes:
|
|
84
|
+
return encode_varint((number << 3) | wire_type)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def field_varint(number: int, value: int) -> bytes:
|
|
88
|
+
return tag(number, WIRE_VARINT) + encode_varint(value)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def field_bytes(number: int, value: bytes) -> bytes:
|
|
92
|
+
return tag(number, WIRE_BYTES) + encode_varint(len(value)) + value
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def field_string(number: int, value: str) -> bytes:
|
|
96
|
+
return field_bytes(number, value.encode("utf-8"))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def field_double(number: int, value: float) -> bytes:
|
|
100
|
+
return tag(number, WIRE_FIXED64) + struct.pack("<d", value)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def field_message(number: int, payload: bytes) -> bytes:
|
|
104
|
+
"""Embed a sub-message. Equivalent to ``field_bytes`` but clearer at call sites."""
|
|
105
|
+
return field_bytes(number, payload)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def packed_varints(number: int, values: list[int]) -> bytes:
|
|
109
|
+
"""Packed repeated varint field (proto3 default for scalar repeats)."""
|
|
110
|
+
if not values:
|
|
111
|
+
return b""
|
|
112
|
+
body = b"".join(encode_varint(v) for v in values)
|
|
113
|
+
return field_bytes(number, body)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def iter_fields(buf: bytes) -> Iterator[tuple[int, int, bytes | int | float]]:
|
|
117
|
+
"""Walk a serialised message, yielding ``(field_number, wire_type, value)``.
|
|
118
|
+
|
|
119
|
+
Length-delimited fields yield ``bytes``; varints yield ``int``; fixed32
|
|
120
|
+
and fixed64 yield the raw 4 or 8 bytes so the caller decides between
|
|
121
|
+
float/double and fixed-width integers. Unknown fields are yielded too,
|
|
122
|
+
which is how forward compatibility is preserved: callers skip what they
|
|
123
|
+
do not recognise instead of failing.
|
|
124
|
+
"""
|
|
125
|
+
pos = 0
|
|
126
|
+
end = len(buf)
|
|
127
|
+
while pos < end:
|
|
128
|
+
key, pos = decode_varint(buf, pos)
|
|
129
|
+
number, wire_type = key >> 3, key & 0x07
|
|
130
|
+
if wire_type == WIRE_VARINT:
|
|
131
|
+
value, pos = decode_varint(buf, pos)
|
|
132
|
+
yield number, wire_type, value
|
|
133
|
+
elif wire_type == WIRE_BYTES:
|
|
134
|
+
length, pos = decode_varint(buf, pos)
|
|
135
|
+
if pos + length > end:
|
|
136
|
+
raise ValueError("truncated length-delimited field")
|
|
137
|
+
yield number, wire_type, buf[pos : pos + length]
|
|
138
|
+
pos += length
|
|
139
|
+
elif wire_type == WIRE_FIXED64:
|
|
140
|
+
if pos + 8 > end:
|
|
141
|
+
raise ValueError("truncated fixed64")
|
|
142
|
+
yield number, wire_type, buf[pos : pos + 8]
|
|
143
|
+
pos += 8
|
|
144
|
+
elif wire_type == WIRE_FIXED32:
|
|
145
|
+
if pos + 4 > end:
|
|
146
|
+
raise ValueError("truncated fixed32")
|
|
147
|
+
yield number, wire_type, buf[pos : pos + 4]
|
|
148
|
+
pos += 4
|
|
149
|
+
elif wire_type == 3: # deprecated start-group
|
|
150
|
+
raise ValueError("group wire type is not supported")
|
|
151
|
+
elif wire_type == 4: # deprecated end-group
|
|
152
|
+
raise ValueError("unexpected end-group")
|
|
153
|
+
else:
|
|
154
|
+
raise ValueError(f"unknown wire type {wire_type}")
|