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,332 @@
1
+ """Decode protobuf responses: ``ForwardBackwardOutput`` and ``SampleResponse``.
2
+
3
+ The subtle part is ``BatchedTensor``: the server packs every datum's values
4
+ into one buffer plus an int64 ``offsets`` array. Those offsets are **byte**
5
+ offsets into the pre-widening stream, so when bfloat16 is widened to float32
6
+ or int32 to int64 the offsets still have to be divided by the *original*
7
+ itemsize. Getting this wrong silently misaligns per-datum logprobs.
8
+
9
+ Unknown fields are skipped rather than rejected, so a server that adds a field
10
+ does not break older SDKs.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import struct
16
+
17
+ import numpy as np
18
+
19
+ from ..types import (
20
+ ForwardBackwardOutput,
21
+ PromptAltTokens,
22
+ SampledSequence,
23
+ SampleResponse,
24
+ TensorData,
25
+ TopkLogprobs,
26
+ )
27
+ from . import schema as S
28
+ from .codec import WIRE_BYTES, decode_varint, iter_fields
29
+
30
+ __all__ = [
31
+ "decode_forward_backward_output",
32
+ "decode_sample_response",
33
+ "decode_tensor",
34
+ "decode_topk_logprobs",
35
+ ]
36
+
37
+
38
+ def _unpack_varints(buf: bytes) -> list[int]:
39
+ """Read a packed repeated varint field."""
40
+ out: list[int] = []
41
+ pos = 0
42
+ while pos < len(buf):
43
+ value, pos = decode_varint(buf, pos)
44
+ out.append(value)
45
+ return out
46
+
47
+
48
+ def _map_entry(buf: bytes) -> tuple[str, bytes | float | int | None]:
49
+ """Decode one map entry into ``(key, raw_value)``."""
50
+ key = ""
51
+ value: bytes | float | int | None = None
52
+ for number, wire, raw in iter_fields(buf):
53
+ if number == S.MapEntry.KEY and wire == WIRE_BYTES:
54
+ key = bytes(raw).decode("utf-8")
55
+ elif number == S.MapEntry.VALUE:
56
+ value = struct.unpack("<d", raw)[0] if wire == 1 else raw
57
+ return key, value
58
+
59
+
60
+ def decode_tensor(buf: bytes) -> TensorData:
61
+ """Decode a proto ``Tensor`` into a ``TensorData``, preserving sparsity."""
62
+ dense: bytes | None = None
63
+ sparse: bytes | None = None
64
+ dtype_enum = S.DTYPE_FLOAT32
65
+ shape: list[int] = []
66
+
67
+ for number, wire, raw in iter_fields(buf):
68
+ if number == S.Tensor.DENSE and wire == WIRE_BYTES:
69
+ dense = bytes(raw)
70
+ elif number == S.Tensor.SPARSE_CSR and wire == WIRE_BYTES:
71
+ sparse = bytes(raw)
72
+ elif number == S.Tensor.DTYPE:
73
+ dtype_enum = int(raw)
74
+ elif number == S.Tensor.SHAPE:
75
+ # Packed when emitted by the generated encoder, but a conformant
76
+ # writer may also emit one varint per element.
77
+ shape.extend(_unpack_varints(bytes(raw)) if wire == WIRE_BYTES else [int(raw)])
78
+
79
+ np_name = S.DTYPE_TO_NUMPY.get(dtype_enum)
80
+ public = S.DTYPE_TO_PUBLIC.get(dtype_enum)
81
+ if np_name is None or public is None:
82
+ raise ValueError(f"unsupported proto dtype: {dtype_enum}")
83
+
84
+ if sparse is not None:
85
+ values = b""
86
+ crow = b""
87
+ col = b""
88
+ for number, wire, raw in iter_fields(sparse):
89
+ if number == S.SparseCsr.VALUES:
90
+ values = bytes(raw)
91
+ elif number == S.SparseCsr.CROW_INDICES:
92
+ crow = bytes(raw)
93
+ elif number == S.SparseCsr.COL_INDICES:
94
+ col = bytes(raw)
95
+ return TensorData(
96
+ data=np.frombuffer(values, dtype=np_name).copy(),
97
+ dtype=public, # type: ignore[arg-type]
98
+ shape=shape or None,
99
+ sparse_crow_indices=np.frombuffer(crow, dtype=np.int64).tolist(),
100
+ sparse_col_indices=np.frombuffer(col, dtype=np.int64).tolist(),
101
+ )
102
+
103
+ arr = np.frombuffer(dense or b"", dtype=np_name).copy()
104
+ arr = _widen(arr, dtype_enum)
105
+ return TensorData(data=arr, dtype=public, shape=shape or None) # type: ignore[arg-type]
106
+
107
+
108
+ def _widen(arr: np.ndarray, dtype_enum: int) -> np.ndarray:
109
+ """Widen a wire dtype to its public counterpart, preserving element count.
110
+
111
+ bfloat16 is the upper 16 bits of a float32, so shifting left by 16 and
112
+ viewing as float32 is bit-exact for finite values.
113
+ """
114
+ if dtype_enum == S.DTYPE_BFLOAT16:
115
+ return (arr.astype(np.uint32) << 16).view(np.float32)
116
+ if dtype_enum == S.DTYPE_INT32:
117
+ return arr.astype(np.int64)
118
+ return arr
119
+
120
+
121
+ def _decode_batched_tensor(buf: bytes) -> tuple[list[np.ndarray], str, list[int]]:
122
+ """Slice a ``BatchedTensor`` into per-datum flat arrays.
123
+
124
+ Returns ``(per_datum_arrays, public_dtype, trailing_shape)``.
125
+ """
126
+ data = b""
127
+ offsets_raw = b""
128
+ dtype_enum = S.DTYPE_FLOAT32
129
+ trailing: list[int] = []
130
+
131
+ for number, wire, raw in iter_fields(buf):
132
+ if number == S.BatchedTensor.DATA:
133
+ data = bytes(raw)
134
+ elif number == S.BatchedTensor.OFFSETS:
135
+ offsets_raw = bytes(raw)
136
+ elif number == S.BatchedTensor.DTYPE:
137
+ dtype_enum = int(raw)
138
+ elif number == S.BatchedTensor.TRAILING_SHAPE:
139
+ trailing.extend(
140
+ _unpack_varints(bytes(raw)) if wire == WIRE_BYTES else [int(raw)]
141
+ )
142
+
143
+ np_name = S.DTYPE_TO_NUMPY.get(dtype_enum)
144
+ public = S.DTYPE_TO_PUBLIC.get(dtype_enum)
145
+ if np_name is None or public is None:
146
+ raise ValueError(f"unsupported proto DType in BatchedTensor: {dtype_enum}")
147
+
148
+ offsets = np.frombuffer(offsets_raw, dtype=np.int64)
149
+ buf_arr = np.frombuffer(data, dtype=np_name)
150
+ # Capture the itemsize *before* widening: offsets index the original stream.
151
+ src_itemsize = np.dtype(np_name).itemsize
152
+ buf_arr = _widen(buf_arr, dtype_enum)
153
+
154
+ per_datum: list[np.ndarray] = []
155
+ for i in range(max(len(offsets) - 1, 0)):
156
+ start = int(offsets[i]) // src_itemsize
157
+ end = int(offsets[i + 1]) // src_itemsize
158
+ per_datum.append(buf_arr[start:end])
159
+ return per_datum, public, trailing
160
+
161
+
162
+ def decode_forward_backward_output(buf: bytes) -> ForwardBackwardOutput:
163
+ """Decode a ``ForwardBackwardOutput``.
164
+
165
+ Handles any number of ``ArrayRecord`` chunks. Field names are invariant
166
+ across chunks, but dtype and trailing shape are per-chunk: ragged outputs
167
+ (variable-K loss fields) arrive as several internally-rectangular chunks.
168
+ """
169
+ output_type = ""
170
+ records: list[bytes] = []
171
+ metrics: dict[str, float] = {}
172
+
173
+ for number, _wire, raw in iter_fields(buf):
174
+ if number == S.ForwardBackwardOutput.LOSS_FN_OUTPUT_TYPE:
175
+ output_type = bytes(raw).decode("utf-8")
176
+ elif number == S.ForwardBackwardOutput.LOSS_FN_OUTPUTS:
177
+ records.append(bytes(raw))
178
+ elif number == S.ForwardBackwardOutput.METRICS:
179
+ key, value = _map_entry(bytes(raw))
180
+ if key:
181
+ metrics[key] = float(value) if isinstance(value, (int, float)) else 0.0
182
+
183
+ # Bare class name, matching the JSON response shape.
184
+ class_name = output_type.rsplit(":", 1)[-1] if output_type else "ArrayRecord"
185
+ if not records:
186
+ return ForwardBackwardOutput(
187
+ loss_fn_output_type=class_name, loss_fn_outputs=[], metrics=metrics
188
+ )
189
+
190
+ per_field_arrays: dict[str, list[np.ndarray]] = {}
191
+ per_field_meta: dict[str, list[tuple[str, list[int]]]] = {}
192
+ num_datums = 0
193
+
194
+ for record in records:
195
+ for number, wire, raw in iter_fields(record):
196
+ if number == S.ArrayRecord.FIELDS:
197
+ name, payload = _map_entry(bytes(raw))
198
+ if not name or not isinstance(payload, (bytes, bytearray)):
199
+ continue
200
+ arrays, dtype, trailing = _decode_batched_tensor(bytes(payload))
201
+ per_field_arrays.setdefault(name, []).extend(arrays)
202
+ per_field_meta.setdefault(name, []).extend(
203
+ [(dtype, trailing)] * len(arrays)
204
+ )
205
+ elif number == S.ArrayRecord.NUM_DATUMS:
206
+ num_datums += int(raw)
207
+
208
+ # num_datums is authoritative: it survives server-side filters that strip
209
+ # every field (e.g. drop_fwdbwd_logprobs). Fall back to the first field's
210
+ # count for messages predating it.
211
+ if num_datums == 0 and per_field_arrays:
212
+ num_datums = len(next(iter(per_field_arrays.values())))
213
+
214
+ outputs: list[dict[str, TensorData]] = []
215
+ for i in range(num_datums):
216
+ datum: dict[str, TensorData] = {}
217
+ for name, arrays in per_field_arrays.items():
218
+ if i >= len(arrays):
219
+ continue
220
+ dtype, trailing = per_field_meta[name][i]
221
+ arr = arrays[i]
222
+ trailing_elems = 1
223
+ for dim in trailing:
224
+ trailing_elems *= dim
225
+ leading = arr.size // trailing_elems if trailing_elems else 0
226
+ datum[name] = TensorData(
227
+ data=arr, dtype=dtype, shape=[leading, *trailing] # type: ignore[arg-type]
228
+ )
229
+ outputs.append(datum)
230
+
231
+ return ForwardBackwardOutput(
232
+ loss_fn_output_type=class_name, loss_fn_outputs=outputs, metrics=metrics
233
+ )
234
+
235
+
236
+ def decode_topk_logprobs(buf: bytes) -> TopkLogprobs:
237
+ """Decode a ``TopkLogprobs`` block.
238
+
239
+ ``token_ids`` is int32 and ``logprobs`` float32, both row-major over
240
+ ``length`` positions by ``k`` ranks.
241
+ """
242
+ token_ids: list[int] = []
243
+ logprobs: list[float] = []
244
+ k = 0
245
+ length = 0
246
+
247
+ for number, _wire, raw in iter_fields(buf):
248
+ if number == S.TopkLogprobs.TOKEN_IDS:
249
+ token_ids = np.frombuffer(bytes(raw), dtype=np.int32).tolist()
250
+ elif number == S.TopkLogprobs.LOGPROBS:
251
+ logprobs = np.frombuffer(bytes(raw), dtype=np.float32).tolist()
252
+ elif number == S.TopkLogprobs.K:
253
+ k = int(raw)
254
+ elif number == S.TopkLogprobs.LENGTH:
255
+ length = int(raw)
256
+
257
+ # length is derivable, but only the server knows it when k is 0.
258
+ if length == 0 and k:
259
+ length = len(token_ids) // k
260
+ return TopkLogprobs(token_ids=token_ids, logprobs=logprobs, k=k, length=length)
261
+
262
+
263
+ def _decode_prompt_alt_tokens(buf: bytes) -> PromptAltTokens:
264
+ tokens: TensorData | None = None
265
+ logprobs: TensorData | None = None
266
+ for number, _wire, raw in iter_fields(buf):
267
+ if number == S.PromptAltTokens.TOKENS:
268
+ tokens = decode_tensor(bytes(raw))
269
+ elif number == S.PromptAltTokens.LOGPROBS:
270
+ logprobs = decode_tensor(bytes(raw))
271
+ return PromptAltTokens(tokens=tokens, logprobs=logprobs)
272
+
273
+
274
+ def decode_sample_response(buf: bytes) -> SampleResponse:
275
+ """Decode a ``SampleResponse``."""
276
+ sequences: list[SampledSequence] = []
277
+ prompt_logprobs: list[float] | None = None
278
+ cache_hits = 0
279
+ topk_prompt: TopkLogprobs | None = None
280
+ target_prompt: TensorData | None = None
281
+ alt_tokens: PromptAltTokens | None = None
282
+
283
+ for number, _wire, raw in iter_fields(buf):
284
+ if number == S.SampleResponse.SEQUENCES:
285
+ sequences.append(_decode_sampled_sequence(bytes(raw)))
286
+ elif number == S.SampleResponse.PROMPT_LOGPROBS:
287
+ prompt_logprobs = np.frombuffer(bytes(raw), dtype=np.float32).tolist()
288
+ elif number == S.SampleResponse.PROMPT_CACHE_HIT_TOKENS:
289
+ cache_hits = int(raw)
290
+ elif number == S.SampleResponse.TOPK_PROMPT_LOGPROBS:
291
+ topk_prompt = decode_topk_logprobs(bytes(raw))
292
+ elif number == S.SampleResponse.TARGET_PROMPT_LOGPROBS:
293
+ target_prompt = decode_tensor(bytes(raw))
294
+ elif number == S.SampleResponse.PROMPT_ALT_TOKENS:
295
+ alt_tokens = _decode_prompt_alt_tokens(bytes(raw))
296
+
297
+ return SampleResponse(
298
+ sequences=sequences,
299
+ prompt_logprobs=prompt_logprobs,
300
+ prompt_cache_hit_tokens=cache_hits,
301
+ topk_prompt_logprobs=topk_prompt,
302
+ target_prompt_logprobs=target_prompt,
303
+ prompt_alt_tokens=alt_tokens,
304
+ )
305
+
306
+
307
+ def _decode_sampled_sequence(buf: bytes) -> SampledSequence:
308
+ stop_reason = "stop"
309
+ tokens: list[int] = []
310
+ logprobs: list[float] | None = None
311
+ topk: TopkLogprobs | None = None
312
+
313
+ for number, _wire, raw in iter_fields(buf):
314
+ if number == S.SampledSequence.STOP_REASON:
315
+ mapped = S.STOP_REASON_TO_STR.get(int(raw))
316
+ if mapped is None:
317
+ raise ValueError(f"unknown stop_reason enum value: {int(raw)}")
318
+ stop_reason = mapped
319
+ elif number == S.SampledSequence.TOKENS:
320
+ tokens = np.frombuffer(bytes(raw), dtype=np.int32).tolist()
321
+ elif number == S.SampledSequence.LOGPROBS:
322
+ data = bytes(raw)
323
+ logprobs = np.frombuffer(data, dtype=np.float32).tolist() if data else None
324
+ elif number == S.SampledSequence.TOPK_SAMPLED_LOGPROBS:
325
+ topk = decode_topk_logprobs(bytes(raw))
326
+
327
+ return SampledSequence(
328
+ tokens=tokens,
329
+ stop_reason=stop_reason, # type: ignore[arg-type]
330
+ logprobs=logprobs,
331
+ topk_logprobs=topk,
332
+ )
@@ -0,0 +1,163 @@
1
+ """Encode ``ForwardBackwardRequest`` to protobuf bytes.
2
+
3
+ This is the training hot path: it runs once per step, with the whole batch in
4
+ the body. Correctness here is non-negotiable -- a mis-encoded tensor trains on
5
+ garbage without raising -- so the encoding of every field is spelled out
6
+ explicitly against ``schema`` rather than inferred.
7
+
8
+ Byte-level conventions copied from the upstream encoder
9
+ (``tinker/proto/request_conv.py``), because the server's decoder assumes them:
10
+
11
+ * ``EncodedTextChunk.tokens``: **int32** little-endian, not int64.
12
+ * ``Tensor.dense``: contiguous bytes in the tensor's declared dtype.
13
+ * ``SparseCsr`` indices: int64 regardless of the value dtype.
14
+ * ``loss_fn_config``: numbers are dual-written to the legacy map (field 5) and
15
+ the v2 map (field 7); strings go only to v2. Old servers read field 5, new
16
+ servers prefer field 7.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+
23
+ from ..types import (
24
+ Datum,
25
+ DmelChunk,
26
+ EncodedTextChunk,
27
+ ImageChunk,
28
+ ModelInputChunk,
29
+ TensorData,
30
+ )
31
+ from . import schema as S
32
+ from .codec import (
33
+ field_bytes,
34
+ field_double,
35
+ field_message,
36
+ field_string,
37
+ field_varint,
38
+ packed_varints,
39
+ )
40
+
41
+ __all__ = ["encode_forward_backward_request", "encode_tensor", "encode_datum"]
42
+
43
+
44
+ def encode_tensor(td: TensorData) -> bytes:
45
+ """Serialise a ``TensorData`` as a proto ``Tensor``."""
46
+ proto_dtype = S.PUBLIC_TO_DTYPE.get(td.dtype)
47
+ if proto_dtype is None:
48
+ raise ValueError(f"unsupported TensorData dtype for the wire: {td.dtype!r}")
49
+
50
+ out = bytearray()
51
+ if td.is_sparse:
52
+ # Sparse CSR: values keep the declared dtype, indices are always int64.
53
+ csr = bytearray()
54
+ csr += field_bytes(S.SparseCsr.VALUES, np.ascontiguousarray(td.data).tobytes())
55
+ csr += field_bytes(
56
+ S.SparseCsr.CROW_INDICES,
57
+ np.asarray(td.sparse_crow_indices, dtype=np.int64).tobytes(),
58
+ )
59
+ csr += field_bytes(
60
+ S.SparseCsr.COL_INDICES,
61
+ np.asarray(td.sparse_col_indices, dtype=np.int64).tobytes(),
62
+ )
63
+ out += field_message(S.Tensor.SPARSE_CSR, bytes(csr))
64
+ else:
65
+ out += field_bytes(S.Tensor.DENSE, np.ascontiguousarray(td.data).tobytes())
66
+
67
+ out += field_varint(S.Tensor.DTYPE, proto_dtype)
68
+ if td.shape:
69
+ out += packed_varints(S.Tensor.SHAPE, [int(s) for s in td.shape])
70
+ return bytes(out)
71
+
72
+
73
+ def _map_entry(number: int, key: str, value_payload: bytes) -> bytes:
74
+ """One ``map<string, Message>`` entry."""
75
+ entry = field_string(S.MapEntry.KEY, key) + field_message(
76
+ S.MapEntry.VALUE, value_payload
77
+ )
78
+ return field_message(number, entry)
79
+
80
+
81
+ def _map_entry_double(number: int, key: str, value: float) -> bytes:
82
+ """One ``map<string, double>`` entry."""
83
+ entry = field_string(S.MapEntry.KEY, key) + field_double(S.MapEntry.VALUE, value)
84
+ return field_message(number, entry)
85
+
86
+
87
+ def encode_chunk(chunk: ModelInputChunk) -> bytes:
88
+ """The ``Chunk`` message body: its single oneof arm, with no outer tag.
89
+
90
+ The caller wraps this in ``Datum.model_input``, so tagging happens at
91
+ exactly one site.
92
+ """
93
+ if isinstance(chunk, EncodedTextChunk):
94
+ tokens = np.asarray(chunk.tokens, dtype=np.int32).tobytes()
95
+ return field_message(
96
+ S.Chunk.ENCODED_TEXT, field_bytes(S.EncodedTextChunk.TOKENS, tokens)
97
+ )
98
+ if isinstance(chunk, ImageChunk):
99
+ inner = bytearray()
100
+ inner += field_bytes(S.ImageChunk.DATA, chunk.data)
101
+ inner += field_string(S.ImageChunk.FORMAT, chunk.format)
102
+ if chunk.expected_tokens is not None:
103
+ inner += field_varint(S.ImageChunk.EXPECTED_TOKENS, int(chunk.expected_tokens))
104
+ return field_message(S.Chunk.IMAGE, bytes(inner))
105
+ if isinstance(chunk, DmelChunk):
106
+ return field_message(S.Chunk.DMEL, field_bytes(S.DmelChunk.DMEL, chunk.dmel))
107
+ raise ValueError(f"unsupported model input chunk type: {type(chunk).__name__}")
108
+
109
+
110
+ def encode_datum(datum: Datum) -> bytes:
111
+ """Serialise one ``Datum``."""
112
+ out = bytearray()
113
+ for chunk in datum.model_input.chunks:
114
+ out += field_message(S.Datum.MODEL_INPUT, encode_chunk(chunk))
115
+ for name, td in datum.loss_fn_inputs.items():
116
+ out += _map_entry(S.Datum.LOSS_FN_INPUTS, name, encode_tensor(td))
117
+ return bytes(out)
118
+
119
+
120
+ def encode_forward_backward_request(
121
+ *,
122
+ model_id: str,
123
+ seq_id: int,
124
+ data: list[Datum],
125
+ loss_fn: str,
126
+ loss_fn_config: dict[str, float | str] | None = None,
127
+ forward_only: bool = False,
128
+ ) -> bytes:
129
+ """Serialise a complete ``ForwardBackwardRequest``.
130
+
131
+ Args:
132
+ model_id: the training model this step applies to.
133
+ seq_id: monotonic step sequence within the session. Upstream always
134
+ sets it (>= 1); a 0 trips the server's range check.
135
+ data: the batch.
136
+ loss_fn: one of the server's loss function names.
137
+ loss_fn_config: optional loss parameters. Numbers are dual-written to
138
+ the legacy and v2 maps; strings exist only on v2.
139
+ forward_only: run the forward pass without accumulating gradients.
140
+ """
141
+ out = bytearray()
142
+ out += field_string(S.ForwardBackwardRequest.MODEL_ID, model_id)
143
+ out += field_varint(S.ForwardBackwardRequest.SEQ_ID, int(seq_id))
144
+ for datum in data:
145
+ out += field_message(S.ForwardBackwardRequest.DATA, encode_datum(datum))
146
+ out += field_string(S.ForwardBackwardRequest.LOSS_FN, loss_fn)
147
+
148
+ if loss_fn_config:
149
+ for key, value in loss_fn_config.items():
150
+ if isinstance(value, str):
151
+ v2 = field_string(S.LossConfigValue.TEXT, value)
152
+ out += _map_entry(S.ForwardBackwardRequest.LOSS_FN_CONFIG_V2, key, v2)
153
+ else:
154
+ number = float(value)
155
+ out += _map_entry_double(
156
+ S.ForwardBackwardRequest.LOSS_FN_CONFIG, key, number
157
+ )
158
+ v2 = field_double(S.LossConfigValue.NUMBER, number)
159
+ out += _map_entry(S.ForwardBackwardRequest.LOSS_FN_CONFIG_V2, key, v2)
160
+
161
+ if forward_only:
162
+ out += field_varint(S.ForwardBackwardRequest.FORWARD_ONLY, 1)
163
+ return bytes(out)
@@ -0,0 +1,186 @@
1
+ """Field numbers and enum values for the public Tinker protobuf schema.
2
+
3
+ Transcribed from ``tinker/proto/tinker_public_pb2`` (tinker 0.39.0) by
4
+ reflecting over the generated descriptors. This is the one place in the SDK
5
+ that mirrors an upstream schema, and it is deliberately data-only: the schema
6
+ is part of the *on-wire protocol*, which we must match regardless of whether
7
+ we depend on upstream client code.
8
+
9
+ ``tests/test_proto_golden.py`` re-derives these from the generated module when
10
+ it is importable, so drift fails the test rather than corrupting a training run.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ __all__ = [
16
+ "DTYPE_UNSPECIFIED",
17
+ "DTYPE_FLOAT32",
18
+ "DTYPE_INT64",
19
+ "DTYPE_INT32",
20
+ "DTYPE_BFLOAT16",
21
+ "STOP_REASON_STOP",
22
+ "STOP_REASON_LENGTH",
23
+ "DTYPE_TO_NUMPY",
24
+ "DTYPE_TO_PUBLIC",
25
+ "PUBLIC_TO_DTYPE",
26
+ "STOP_REASON_TO_STR",
27
+ ]
28
+
29
+ # -- enum DType ---------------------------------------------------------------
30
+ DTYPE_UNSPECIFIED = 0
31
+ DTYPE_FLOAT32 = 1
32
+ DTYPE_INT64 = 2
33
+ DTYPE_INT32 = 3
34
+ DTYPE_BFLOAT16 = 4
35
+
36
+ # -- enum StopReason ----------------------------------------------------------
37
+ STOP_REASON_STOP = 0
38
+ STOP_REASON_LENGTH = 1
39
+
40
+ STOP_REASON_TO_STR: dict[int, str] = {
41
+ STOP_REASON_STOP: "stop",
42
+ STOP_REASON_LENGTH: "length",
43
+ }
44
+
45
+ #: Proto dtype -> numpy dtype string for ``frombuffer``. bfloat16 arrives as
46
+ #: uint16 bytes and is widened to float32 by the decoder.
47
+ DTYPE_TO_NUMPY: dict[int, str] = {
48
+ DTYPE_FLOAT32: "float32",
49
+ DTYPE_INT64: "int64",
50
+ DTYPE_INT32: "int32",
51
+ DTYPE_BFLOAT16: "uint16",
52
+ }
53
+
54
+ #: Proto dtype -> public TensorDtype. Integer widths collapse to int64 and
55
+ #: bfloat16 collapses to float32, matching the JSON response shape.
56
+ DTYPE_TO_PUBLIC: dict[int, str] = {
57
+ DTYPE_FLOAT32: "float32",
58
+ DTYPE_BFLOAT16: "float32",
59
+ DTYPE_INT64: "int64",
60
+ DTYPE_INT32: "int64",
61
+ }
62
+
63
+ #: Public TensorDtype -> proto dtype. Only these two are exposed to users.
64
+ PUBLIC_TO_DTYPE: dict[str, int] = {
65
+ "float32": DTYPE_FLOAT32,
66
+ "int64": DTYPE_INT64,
67
+ }
68
+
69
+
70
+ class Tensor:
71
+ DENSE = 1 # bytes
72
+ SPARSE_CSR = 2 # message SparseCsr
73
+ DTYPE = 3 # enum DType
74
+ SHAPE = 4 # repeated int64
75
+
76
+
77
+ class SparseCsr:
78
+ VALUES = 1 # bytes
79
+ CROW_INDICES = 2 # bytes
80
+ COL_INDICES = 3 # bytes
81
+
82
+
83
+ class EncodedTextChunk:
84
+ TOKENS = 1 # bytes (int32-packed)
85
+
86
+
87
+ class ImageChunk:
88
+ DATA = 1 # bytes
89
+ FORMAT = 2 # string
90
+ EXPECTED_TOKENS = 3 # int32
91
+ OVERRIDE_DIMENSIONS = 4 # message ImageDimensions
92
+
93
+
94
+ class ImageDimensions:
95
+ WIDTH = 1 # uint32
96
+ HEIGHT = 2 # uint32
97
+
98
+
99
+ class DmelChunk:
100
+ DMEL = 1 # bytes
101
+
102
+
103
+ class Chunk:
104
+ """oneof: exactly one of these is set per chunk."""
105
+
106
+ ENCODED_TEXT = 1 # message EncodedTextChunk
107
+ IMAGE = 2 # message ImageChunk
108
+ DMEL = 3 # message DmelChunk
109
+
110
+
111
+ class Datum:
112
+ MODEL_INPUT = 1 # repeated Chunk
113
+ LOSS_FN_INPUTS = 2 # map<string, Tensor>
114
+ MODEL_INPUT_SPANS = 3 # repeated ProvenanceSpan
115
+ LOSS_FN_INPUT_SPANS = 4 # repeated ProvenanceSpan
116
+
117
+
118
+ class ForwardBackwardRequest:
119
+ MODEL_ID = 1 # string
120
+ SEQ_ID = 2 # int32
121
+ DATA = 3 # repeated Datum
122
+ LOSS_FN = 4 # string
123
+ LOSS_FN_CONFIG = 5 # map<string, double> (legacy)
124
+ FORWARD_ONLY = 6 # bool
125
+ LOSS_FN_CONFIG_V2 = 7 # map<string, LossConfigValue>
126
+
127
+
128
+ class LossConfigValue:
129
+ """oneof: number or text."""
130
+
131
+ NUMBER = 1 # double
132
+ TEXT = 2 # string
133
+
134
+
135
+ class BatchedTensor:
136
+ DATA = 1 # bytes
137
+ OFFSETS = 2 # bytes (int64-packed byte offsets)
138
+ DTYPE = 3 # enum DType
139
+ TRAILING_SHAPE = 4 # repeated int64
140
+
141
+
142
+ class ArrayRecord:
143
+ TYPE_TAG = 1 # string
144
+ FIELDS = 2 # map<string, BatchedTensor>
145
+ NUM_DATUMS = 3 # int64
146
+
147
+
148
+ class ForwardBackwardOutput:
149
+ LOSS_FN_OUTPUT_TYPE = 1 # string
150
+ LOSS_FN_OUTPUTS = 2 # repeated ArrayRecord
151
+ METRICS = 3 # map<string, double>
152
+
153
+
154
+ class SampledSequence:
155
+ STOP_REASON = 1 # enum StopReason
156
+ TOKENS = 2 # bytes (int32-packed)
157
+ LOGPROBS = 3 # bytes (float32-packed)
158
+ TOPK_SAMPLED_LOGPROBS = 4 # message TopkLogprobs
159
+
160
+
161
+ class SampleResponse:
162
+ SEQUENCES = 1 # repeated SampledSequence
163
+ PROMPT_LOGPROBS = 2 # bytes (float32-packed)
164
+ TOPK_PROMPT_LOGPROBS = 3 # message TopkLogprobs
165
+ PROMPT_CACHE_HIT_TOKENS = 4 # int32
166
+ TARGET_PROMPT_LOGPROBS = 5 # message Tensor
167
+ PROMPT_ALT_TOKENS = 6 # message PromptAltTokens
168
+
169
+
170
+ class TopkLogprobs:
171
+ TOKEN_IDS = 1 # bytes (int32-packed, n*k)
172
+ LOGPROBS = 2 # bytes (float32-packed, n*k)
173
+ K = 3 # uint32
174
+ LENGTH = 4 # uint32
175
+
176
+
177
+ class PromptAltTokens:
178
+ TOKENS = 1 # message Tensor (int64, [len(prompt)-1, k])
179
+ LOGPROBS = 2 # message Tensor (float32, same shape)
180
+
181
+
182
+ class MapEntry:
183
+ """Every protobuf map entry is a sub-message with these two fields."""
184
+
185
+ KEY = 1
186
+ VALUE = 2