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,406 @@
1
+ """``Sampler``: token-level sampling.
2
+
3
+ Tokens in, tokens plus logprobs out. This is the only sampling surface the SDK
4
+ exposes: algorithms that need it need exact token ids and token-aligned
5
+ logprobs, which a message-level chat API cannot give. Building an
6
+ ``importance_sampling`` datum for GRPO is the case that decides this.
7
+
8
+ Sampling reaches the training service through the same relay ``/train`` pass-through as
9
+ training: the relay is a general proxy, not a sampling-specific one. The relay's
10
+ separate hardcoded Tinker routes (whose upstream is the inference service) are deliberately
11
+ not used here -- their field spellings differ, e.g. ``topk_sample_logprobs``
12
+ versus the native ``topk_sampled_logprobs``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import threading
19
+ from typing import Any, Sequence
20
+
21
+ from . import _protocol as P
22
+ from ._errors import ConfigurationError
23
+ from ._futures import APIFuture
24
+ from .types import ModelInput, SampleResponse, SamplingParams, TensorData
25
+
26
+ __all__ = ["Sampler"]
27
+
28
+ log = logging.getLogger("mind_recursive.sampler")
29
+
30
+
31
+ class Sampler:
32
+ """A sampling session over one set of weights.
33
+
34
+ Obtained from :meth:`mind_recursive.ServiceClient.create_sampler` or
35
+ :meth:`save_weights_and_get_sampler`.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ *,
41
+ service: Any,
42
+ sampling_session_id: str,
43
+ base_model: str | None = None,
44
+ model_path: str | None = None,
45
+ kind: str = "snapshot",
46
+ record_stability_info: bool = False,
47
+ ) -> None:
48
+ self._service = service
49
+ self._sampling_session_id = sampling_session_id
50
+ self._base_model = base_model
51
+ self._model_path = model_path
52
+ self._kind = kind
53
+ # Session-wide default for sample(record_stability_info=...). Set when
54
+ # the session came from an ephemeral export, which has no
55
+ # create_sampling_session call to carry the flag.
56
+ self._record_stability_info = record_stability_info
57
+ # Per-sampler request counter, as Tinker keeps one per sampling client:
58
+ # The inference service requires a non-negative ``seq_id`` on every ``asample``
59
+ # (it is the idempotency key of the request), so a caller who does not
60
+ # pass one gets the next value. Guarded because samplers are shared by
61
+ # rollout threads.
62
+ self._next_seq_id = 0
63
+ self._seq_lock = threading.Lock()
64
+
65
+ def _allocate_seq_id(self) -> int:
66
+ with self._seq_lock:
67
+ seq_id = self._next_seq_id
68
+ self._next_seq_id += 1
69
+ return seq_id
70
+
71
+ @property
72
+ def sampling_session_id(self) -> str:
73
+ return self._sampling_session_id
74
+
75
+ @property
76
+ def model_path(self) -> str | None:
77
+ return self._model_path
78
+
79
+ @property
80
+ def base_model(self) -> str | None:
81
+ return self._base_model
82
+
83
+ @property
84
+ def kind(self) -> str:
85
+ """``snapshot`` for fixed weights, ``inflight`` for a live model's."""
86
+ return self._kind
87
+
88
+ def _sample_body(
89
+ self,
90
+ prompt: ModelInput | Sequence[int],
91
+ num_samples: int,
92
+ sampling_params: SamplingParams | None,
93
+ include_prompt_logprobs: bool | None,
94
+ topk_prompt_logprobs: int,
95
+ topk_sample_logprobs: int,
96
+ target_prompt_logprobs: TensorData | None,
97
+ prompt_alt_tokens_k: int,
98
+ prompt_logprobs_last_n: int | None,
99
+ seq_id: int | None,
100
+ prompt_logprobs: bool,
101
+ record_stability_info: bool,
102
+ ) -> dict[str, Any]:
103
+ """Shared request body for :meth:`sample` and :meth:`sample_async`."""
104
+ if include_prompt_logprobs is not None:
105
+ if prompt_logprobs and not include_prompt_logprobs:
106
+ raise ValueError(
107
+ "include_prompt_logprobs=False conflicts with "
108
+ "prompt_logprobs=True"
109
+ )
110
+ prompt_logprobs = include_prompt_logprobs
111
+ if num_samples < 1:
112
+ raise ValueError("num_samples must be at least 1")
113
+ model_input = (
114
+ prompt if isinstance(prompt, ModelInput) else ModelInput.from_ints(prompt)
115
+ )
116
+ params = sampling_params or SamplingParams()
117
+
118
+ if prompt_logprobs_last_n is not None:
119
+ if not prompt_logprobs:
120
+ raise ValueError(
121
+ "prompt_logprobs_last_n scores prompt tokens, so it needs "
122
+ "prompt_logprobs=True"
123
+ )
124
+ if prompt_logprobs_last_n < 1:
125
+ raise ValueError("prompt_logprobs_last_n must be at least 1")
126
+ limit = model_input.length - 1
127
+ if limit >= 1 and prompt_logprobs_last_n > limit:
128
+ raise ValueError(
129
+ f"prompt_logprobs_last_n must be at most len(prompt) - 1 "
130
+ f"({limit}), got {prompt_logprobs_last_n}"
131
+ )
132
+ for name, value in (
133
+ ("topk_prompt_logprobs", topk_prompt_logprobs),
134
+ ("topk_sample_logprobs", topk_sample_logprobs),
135
+ ("prompt_alt_tokens_k", prompt_alt_tokens_k),
136
+ ):
137
+ if value < 0:
138
+ raise ValueError(f"{name} cannot be negative, got {value}")
139
+ if seq_id is not None and seq_id < 0:
140
+ raise ValueError("seq_id cannot be negative")
141
+
142
+ body: dict[str, Any] = {
143
+ "num_samples": num_samples,
144
+ "prompt": _encode_model_input(model_input),
145
+ "sampling_params": params.to_wire(),
146
+ "sampling_session_id": self._sampling_session_id,
147
+ "type": "sample",
148
+ }
149
+ body["seq_id"] = seq_id if seq_id is not None else self._allocate_seq_id()
150
+ if prompt_logprobs:
151
+ body["prompt_logprobs"] = True
152
+ if prompt_logprobs_last_n is not None:
153
+ body["prompt_logprobs_last_n"] = prompt_logprobs_last_n
154
+ if topk_prompt_logprobs:
155
+ body["topk_prompt_logprobs"] = topk_prompt_logprobs
156
+ if topk_sample_logprobs:
157
+ body["topk_sample_logprobs"] = topk_sample_logprobs
158
+ if target_prompt_logprobs is not None:
159
+ body["target_prompt_logprobs"] = target_prompt_logprobs.to_wire()
160
+ if prompt_alt_tokens_k:
161
+ body["prompt_alt_tokens_k"] = prompt_alt_tokens_k
162
+ if record_stability_info or self._record_stability_info:
163
+ body["record_stability_info"] = True
164
+ return body
165
+
166
+ def sample(
167
+ self,
168
+ prompt: ModelInput | Sequence[int],
169
+ num_samples: int = 1,
170
+ sampling_params: SamplingParams | None = None,
171
+ include_prompt_logprobs: bool | None = None,
172
+ topk_prompt_logprobs: int = 0,
173
+ topk_sample_logprobs: int = 0,
174
+ target_prompt_logprobs: TensorData | None = None,
175
+ prompt_alt_tokens_k: int = 0,
176
+ prompt_logprobs_last_n: int | None = None,
177
+ *,
178
+ seq_id: int | None = None,
179
+ prompt_logprobs: bool = False,
180
+ record_stability_info: bool = False,
181
+ ) -> APIFuture[SampleResponse]:
182
+ """Sample continuations for one prompt.
183
+
184
+ Per-token logprobs for the *sampled* tokens come back unconditionally in
185
+ ``SampledSequence.logprobs`` -- policy-gradient losses need them, so
186
+ they are not behind a flag. Everything about the *prompt* costs extra
187
+ compute, so it is opt-in through the parameters below.
188
+
189
+ Args:
190
+ prompt: a :class:`~mind_recursive.types.ModelInput`, or token ids.
191
+ num_samples: how many continuations to draw.
192
+ sampling_params: decoding parameters; defaults are used if omitted.
193
+ include_prompt_logprobs: Tinker's spelling of ``prompt_logprobs``.
194
+ Passing one spelling is enough; giving both with conflicting
195
+ values raises locally.
196
+ seq_id: sequence index within the sampling session. Multi-turn
197
+ callers pass a distinct one per turn so the request id is
198
+ deterministic and a retry cannot be mistaken for a new turn.
199
+ Omitted, the sampler allocates the next one (0, 1, 2, ...);
200
+ the server requires one on every request.
201
+ prompt_logprobs: score the prompt tokens too, returned in
202
+ ``SampleResponse.prompt_logprobs``.
203
+ prompt_logprobs_last_n: score only the last N prompt tokens;
204
+ earlier entries come back as ``None``. The prefix before them
205
+ can then be served from the server's prefix cache, so scoring a
206
+ short suffix of a long prompt costs about what the suffix costs.
207
+ Requires ``prompt_logprobs``; must be between 1 and
208
+ ``len(prompt) - 1``.
209
+ topk_prompt_logprobs: return the top-k at each prompt position.
210
+ topk_sample_logprobs: return the top-k at each sampled position, in
211
+ ``SampledSequence.topk_logprobs``. Distillation against a
212
+ teacher's distribution is the case that wants this.
213
+ target_prompt_logprobs: token ids to score at chosen prompt
214
+ positions, as an int64 tensor of shape ``[len(prompt) - 1, K]``:
215
+ cell ``[i, j]`` is scored at prompt position ``i + 1``, since
216
+ position 0 has no preceding context. ``-1`` requests nothing.
217
+ May be sparse CSR, in which case only the listed cells are sent
218
+ and returned. Pair it with ``max_tokens=1`` to make the request
219
+ a pure prefill scoring pass.
220
+ prompt_alt_tokens_k: draw this many alternative tokens at every
221
+ prompt position after the first, at the request's temperature,
222
+ within the same prefill.
223
+ record_stability_info: have the server record per-sequence
224
+ stability information, referenced later by ``sequence_id``
225
+ (``stable_reinforce``).
226
+
227
+ Returns:
228
+ A future resolving to :class:`~mind_recursive.types.SampleResponse`.
229
+ """
230
+ body = self._sample_body(
231
+ prompt,
232
+ num_samples,
233
+ sampling_params,
234
+ include_prompt_logprobs,
235
+ topk_prompt_logprobs,
236
+ topk_sample_logprobs,
237
+ target_prompt_logprobs,
238
+ prompt_alt_tokens_k,
239
+ prompt_logprobs_last_n,
240
+ seq_id,
241
+ prompt_logprobs,
242
+ record_stability_info,
243
+ )
244
+ payload = self._service._post_json(
245
+ P.PATH_ASAMPLE,
246
+ body,
247
+ pool="train",
248
+ base_url=self._service.config.sample_base_url,
249
+ )
250
+ request_id = payload.get("request_id")
251
+ if not request_id:
252
+ raise ConfigurationError(f"asample returned no request_id: {payload!r}")
253
+ return APIFuture(
254
+ str(request_id),
255
+ # Poll the future on the plane that produced it, not on /train.
256
+ self._service.resolver(base_url=self._service.config.sample_base_url),
257
+ P.parse_sample_response,
258
+ )
259
+
260
+ async def sample_async(
261
+ self,
262
+ prompt: ModelInput | Sequence[int],
263
+ num_samples: int = 1,
264
+ sampling_params: SamplingParams | None = None,
265
+ include_prompt_logprobs: bool | None = None,
266
+ topk_prompt_logprobs: int = 0,
267
+ topk_sample_logprobs: int = 0,
268
+ target_prompt_logprobs: TensorData | None = None,
269
+ prompt_alt_tokens_k: int = 0,
270
+ prompt_logprobs_last_n: int | None = None,
271
+ *,
272
+ seq_id: int | None = None,
273
+ prompt_logprobs: bool = False,
274
+ record_stability_info: bool = False,
275
+ ) -> SampleResponse:
276
+ """Async twin of :meth:`sample`."""
277
+ body = self._sample_body(
278
+ prompt,
279
+ num_samples,
280
+ sampling_params,
281
+ include_prompt_logprobs,
282
+ topk_prompt_logprobs,
283
+ topk_sample_logprobs,
284
+ target_prompt_logprobs,
285
+ prompt_alt_tokens_k,
286
+ prompt_logprobs_last_n,
287
+ seq_id,
288
+ prompt_logprobs,
289
+ record_stability_info,
290
+ )
291
+ payload = await self._service._apost_json(
292
+ P.PATH_ASAMPLE,
293
+ body,
294
+ pool="train",
295
+ base_url=self._service.config.sample_base_url,
296
+ )
297
+ request_id = payload.get("request_id")
298
+ if not request_id:
299
+ raise ConfigurationError(f"asample returned no request_id: {payload!r}")
300
+ return await self._service.async_resolver(
301
+ base_url=self._service.config.sample_base_url
302
+ ).resolve(request_id, timeout=None, parse=P.parse_sample_response)
303
+
304
+ async def compute_logprobs_async(
305
+ self,
306
+ prompt: ModelInput | Sequence[int],
307
+ prompt_logprobs_last_n: int | None = None,
308
+ ) -> list[float] | None:
309
+ """Async twin of :meth:`compute_logprobs`."""
310
+ response = await self.sample_async(
311
+ prompt,
312
+ num_samples=1,
313
+ sampling_params=SamplingParams(max_tokens=1),
314
+ include_prompt_logprobs=True,
315
+ prompt_logprobs_last_n=prompt_logprobs_last_n,
316
+ )
317
+ return response.prompt_logprobs
318
+
319
+ async def get_base_model_async(self) -> str | None:
320
+ """Async twin of :meth:`get_base_model`."""
321
+ return self._base_model
322
+
323
+ def compute_logprobs(
324
+ self,
325
+ prompt: ModelInput | Sequence[int],
326
+ prompt_logprobs_last_n: int | None = None,
327
+ ) -> APIFuture[list[float] | None]:
328
+ """Score the prompt tokens, Tinker-style.
329
+
330
+ This is a thin shell over :meth:`sample`: one prefill with
331
+ ``max_tokens=1`` and ``prompt_logprobs=True``, reshaping the response
332
+ to the prompt logprobs. It does not add a second wire endpoint.
333
+
334
+ Args:
335
+ prompt: a :class:`~mind_recursive.types.ModelInput`, or token ids.
336
+ prompt_logprobs_last_n: score only the last N prompt tokens; earlier
337
+ entries come back as ``None``. Must be between 1 and
338
+ ``len(prompt) - 1``.
339
+
340
+ Returns:
341
+ A future resolving to the per-token prompt logprobs.
342
+ """
343
+ future = self.sample(
344
+ prompt,
345
+ num_samples=1,
346
+ sampling_params=SamplingParams(max_tokens=1),
347
+ include_prompt_logprobs=True,
348
+ prompt_logprobs_last_n=prompt_logprobs_last_n,
349
+ )
350
+ return future.map(lambda response: response.prompt_logprobs)
351
+
352
+ def get_base_model(self) -> str | None:
353
+ """The base model name, when the sampler knows it.
354
+
355
+ Tinker resolves this server-side for checkpoint-only samplers; this SDK
356
+ only knows the name when it was passed to ``create_sampler``, so a
357
+ checkpoint-only sampler returns ``None``.
358
+ """
359
+ return self._base_model
360
+
361
+ def result(self, timeout: float | None = None) -> Sampler:
362
+ """Tinker-style future compatibility: return this sampler.
363
+
364
+ ``ServiceClient.create_sampling_client`` returns a sampler directly;
365
+ upstream returns a future of one. Creation already blocked by the time
366
+ this object exists, so ``.result()`` is the identity here.
367
+ """
368
+ return self
369
+
370
+ def __repr__(self) -> str:
371
+ target = self._model_path or self._base_model or self._kind
372
+ return f"<Sampler {self._sampling_session_id} ({target})>"
373
+
374
+
375
+ def _encode_model_input(model_input: ModelInput) -> dict[str, Any]:
376
+ """JSON encoding of a ``ModelInput`` for the sampling request.
377
+
378
+ Sampling requests are JSON (only ``forward_backward`` is protobuf), so
379
+ chunks are serialised as objects here rather than packed bytes.
380
+ """
381
+ from .types import DmelChunk, EncodedTextChunk, ImageChunk
382
+
383
+ chunks: list[dict[str, Any]] = []
384
+ for chunk in model_input.chunks:
385
+ if isinstance(chunk, EncodedTextChunk):
386
+ chunks.append({"type": "encoded_text", "tokens": list(chunk.tokens)})
387
+ elif isinstance(chunk, ImageChunk):
388
+ import base64
389
+
390
+ entry: dict[str, Any] = {
391
+ "type": "image",
392
+ "data": base64.b64encode(chunk.data).decode("ascii"),
393
+ "format": chunk.format,
394
+ }
395
+ if chunk.expected_tokens is not None:
396
+ entry["expected_tokens"] = chunk.expected_tokens
397
+ chunks.append(entry)
398
+ elif isinstance(chunk, DmelChunk):
399
+ import base64
400
+
401
+ chunks.append(
402
+ {"type": "dmel", "dmel": base64.b64encode(chunk.dmel).decode("ascii")}
403
+ )
404
+ else:
405
+ raise ValueError(f"unsupported chunk type: {type(chunk).__name__}")
406
+ return {"chunks": chunks}