baseten-loops 0.35.0.dev2__tar.gz → 0.36.0__tar.gz

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.
Files changed (107) hide show
  1. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/CHANGELOG.md +26 -0
  2. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/PKG-INFO +1 -1
  3. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/__init__.py +2 -0
  4. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/models.py +22 -8
  5. baseten_loops-0.36.0/baseten/loops/renderers.py +409 -0
  6. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/sampling_client.py +21 -32
  7. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/service_client.py +44 -13
  8. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/training_client.py +5 -0
  9. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/pyproject.toml +3 -2
  10. baseten_loops-0.36.0/tests/fixtures/deepseek_v4_1_flash_1017_hf_render.json +1 -0
  11. baseten_loops-0.36.0/tests/fixtures/deepseek_v4_1_flash_hf_render.json +1 -0
  12. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_async_paths.py +2 -7
  13. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_create_lora_training_client.py +55 -1
  14. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_provenance.py +0 -49
  15. baseten_loops-0.36.0/tests/test_renderers_deepseek_v4_1_flash.py +183 -0
  16. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sampling_parse.py +17 -2
  17. baseten_loops-0.35.0.dev2/baseten/loops/renderers.py +0 -129
  18. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/.gitignore +0 -0
  19. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/LICENSE +0 -0
  20. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_async_client.py +0 -0
  21. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_capacity.py +0 -0
  22. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_chat_templates.py +0 -0
  23. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_checkpoint_download.py +0 -0
  24. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_checkpoints.py +0 -0
  25. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_h2_transport.py +0 -0
  26. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_headers.py +0 -0
  27. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_heartbeat.py +0 -0
  28. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_request_log.py +0 -0
  29. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_runs.py +0 -0
  30. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_sampler_replicas.py +0 -0
  31. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_samplers.py +0 -0
  32. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_sampling_keepalive.py +0 -0
  33. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_session_filter.py +0 -0
  34. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_sync_bridge.py +0 -0
  35. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_tracing.py +0 -0
  36. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_urls.py +0 -0
  37. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_version.py +0 -0
  38. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/_workers.py +0 -0
  39. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/cache.py +0 -0
  40. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/helpers/__init__.py +0 -0
  41. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/helpers/datum.py +0 -0
  42. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/http_errors.py +0 -0
  43. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/operation.py +0 -0
  44. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/promise_client.py +0 -0
  45. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/provenance.py +0 -0
  46. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/retry.py +0 -0
  47. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/rl_metrics.py +0 -0
  48. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/baseten/loops/trainer_deployment.py +0 -0
  49. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/acceptance_math_rl.py +0 -0
  50. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/acceptance_multiturn_rl.py +0 -0
  51. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/conftest.py +0 -0
  52. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/fixtures/glm5_3_flash_hf_render.json +0 -0
  53. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/fixtures/provenance_contract.json +0 -0
  54. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/fixtures/vlm_model_input_chunks.json +0 -0
  55. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/h2_server.py +0 -0
  56. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_adam_params.py +0 -0
  57. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_cache.py +0 -0
  58. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_capacity.py +0 -0
  59. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_capacity_refused_create.py +0 -0
  60. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_chunking.py +0 -0
  61. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_create_training_client_from_state.py +0 -0
  62. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_datum.py +0 -0
  63. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_download_checkpoint.py +0 -0
  64. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_ensure_ready.py +0 -0
  65. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_forward_backward.py +0 -0
  66. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_forward_backward_custom.py +0 -0
  67. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_get_checkpoint_archive_url.py +0 -0
  68. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_get_server_capabilities.py +0 -0
  69. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_headers.py +0 -0
  70. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_heartbeat_keepalive.py +0 -0
  71. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_lazy_async_client.py +0 -0
  72. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_lazy_paired_sampler.py +0 -0
  73. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_list_checkpoints.py +0 -0
  74. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_model_input.py +0 -0
  75. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_operation_context.py +0 -0
  76. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_pipelining.py +0 -0
  77. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_policy_version.py +0 -0
  78. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_promise_client.py +0 -0
  79. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_provenance_contract.py +0 -0
  80. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_queued_sampling.py +0 -0
  81. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_renderers.py +0 -0
  82. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_request_log.py +0 -0
  83. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_request_ordering.py +0 -0
  84. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_retry.py +0 -0
  85. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_rl_metrics.py +0 -0
  86. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_run_id_in_op_bodies.py +0 -0
  87. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sample_timeout.py +0 -0
  88. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sampling_client_close.py +0 -0
  89. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sampling_client_pickle.py +0 -0
  90. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sampling_tcp_keepalive.py +0 -0
  91. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_sampling_transport_repro.py +0 -0
  92. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_save_weights_for_sampler_bump.py +0 -0
  93. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_serverless_errors.py +0 -0
  94. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_serverless_unique_save_names.py +0 -0
  95. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_session_recovery.py +0 -0
  96. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_snapshot_sampling_client.py +0 -0
  97. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_standalone_sampler_lifecycle.py +0 -0
  98. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_team_scoped_routes.py +0 -0
  99. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_training_client.py +0 -0
  100. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_training_run_lifecycle.py +0 -0
  101. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_vlm_chunks.py +0 -0
  102. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_wait_for_trainer_ready.py +0 -0
  103. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_wandb.py +0 -0
  104. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_with_sampler.py +0 -0
  105. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/test_workers.py +0 -0
  106. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/tests/verify_worker.py +0 -0
  107. {baseten_loops-0.35.0.dev2 → baseten_loops-0.36.0}/uv.lock +0 -0
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.36.0](https://github.com/basetenlabs/baseten-loops/compare/baseten-loops-v0.35.0...baseten-loops-v0.36.0) (2026-11-14)
4
+
5
+
6
+ ### Features
7
+
8
+ * DeepSeek-V4.1-Flash and -1017 image renderers for tinker_cookbook ([#381](https://github.com/basetenlabs/baseten-loops/issues/381)) ([bed9743](https://github.com/basetenlabs/baseten-loops/commit/bed9743033d27ea026124df04e453ceacf4b89a0))
9
+
10
+ ## [0.35.0](https://github.com/basetenlabs/baseten-loops/compare/baseten-loops-v0.34.0...baseten-loops-v0.35.0) (2026-11-11)
11
+
12
+
13
+ ### Features
14
+
15
+ * expose score-centering capture and loss options ([#378](https://github.com/basetenlabs/baseten-loops/issues/378)) ([95f3df8](https://github.com/basetenlabs/baseten-loops/commit/95f3df8d2a3b363e9ead535e697c28b8d23f05c1))
16
+ * Name the auth that reads a custom base checkpoint ([#386](https://github.com/basetenlabs/baseten-loops/issues/386)) ([4fd343a](https://github.com/basetenlabs/baseten-loops/commit/4fd343a25da4e058bbd95341094826e92cbc7c03))
17
+ * Start runs from object store and training job base checkpoints ([#389](https://github.com/basetenlabs/baseten-loops/issues/389)) ([bef69c9](https://github.com/basetenlabs/baseten-loops/commit/bef69c9a5ba8e96c7a870b7a2b6eb9cfde4ae858))
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * Download serverless checkpoints whose volume path is '.' ([#361](https://github.com/basetenlabs/baseten-loops/issues/361)) ([cf349b3](https://github.com/basetenlabs/baseten-loops/commit/cf349b3bbc874ecb2141c74227453fb3c27a3e70))
23
+
24
+
25
+ ### Reverts
26
+
27
+ * remove score-centering SDK options ([#385](https://github.com/basetenlabs/baseten-loops/issues/385)) ([b47e7ba](https://github.com/basetenlabs/baseten-loops/commit/b47e7ba684d685d0a5a98fac1aaf0219c4cadd28))
28
+
3
29
  ## [0.34.0](https://github.com/basetenlabs/baseten-loops/compare/baseten-loops-v0.33.0...baseten-loops-v0.34.0) (2026-11-05)
4
30
 
5
31
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: baseten-loops
3
- Version: 0.35.0.dev2
3
+ Version: 0.36.0
4
4
  Summary: SDK for Baseten training workers
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -38,6 +38,7 @@ from baseten.loops.models import (
38
38
  SupportedModel,
39
39
  TensorData,
40
40
  WandbConfig,
41
+ WeightsAuth,
41
42
  )
42
43
  from baseten.loops.operation import (
43
44
  Operation,
@@ -135,4 +136,5 @@ __all__ = [
135
136
  "SupportedModel",
136
137
  "TensorData",
137
138
  "WandbConfig",
139
+ "WeightsAuth",
138
140
  ]
@@ -33,14 +33,7 @@ from baseten.loops.provenance import SampledProvenanceSpan as SampledProvenanceS
33
33
  SupportedImageFormat: TypeAlias = Literal["png", "jpeg"]
34
34
 
35
35
  LossFnType: TypeAlias = Literal[
36
- "cross_entropy",
37
- "importance_sampling",
38
- "ppo",
39
- "cispo",
40
- "dro",
41
- "dpo",
42
- "dppo",
43
- "score_centered_reinforce",
36
+ "cross_entropy", "importance_sampling", "ppo", "cispo", "dro", "dpo", "dppo"
44
37
  ]
45
38
 
46
39
  StopReason: TypeAlias = Literal["stop", "length"]
@@ -316,6 +309,27 @@ class WandbConfig(BaseModel):
316
309
  name: str | None = None
317
310
 
318
311
 
312
+ # ── Weights auth ─────────────────────────────────────────────────────
313
+
314
+
315
+ class WeightsAuth(BaseModel):
316
+ """Credentials Baseten uses to read a custom base checkpoint.
317
+
318
+ Only ``CUSTOM_SECRET`` is supported: set ``auth_secret_name`` to the team
319
+ secret that holds a Hugging Face token for ``hf://``, or the store's
320
+ credentials for an object store.
321
+ """
322
+
323
+ auth_method: str
324
+ auth_secret_name: str | None = None
325
+ aws_oidc_role_arn: str | None = None
326
+ aws_oidc_region: str | None = None
327
+ gcp_oidc_service_account: str | None = None
328
+ gcp_oidc_workload_id_provider: str | None = None
329
+ aws_assume_role_arn: str | None = None
330
+ aws_assume_role_region: str | None = None
331
+
332
+
319
333
  # ── Optimizer ────────────────────────────────────────────────────────
320
334
 
321
335
 
@@ -0,0 +1,409 @@
1
+ """tinker_cookbook renderers for models the cookbook cannot render.
2
+
3
+ Importing this module registers them, so ``tinker_cookbook.renderers.get_renderer``
4
+ accepts their names:
5
+
6
+ import baseten.loops.renderers
7
+ renderer = get_renderer("baseten/glm5_3_flash_max_reasoning", tokenizer)
8
+
9
+ GLM-5.3-Flash: the cookbook renders it with the text-only GLM-5.3 renderer, and its
10
+ image processor needs a newer transformers than the cookbook allows. These renderers
11
+ add image parts, as ``<|begin_of_image|>``, the image, ``<|end_of_image|>``, and count
12
+ image tokens without the image processor.
13
+
14
+ DeepSeek-V4.1-Flash: the cookbook's DeepSeek V4.1 renderer is text-only, and the
15
+ checkpoint ships no image processor. These renderers add image parts in system, user
16
+ and tool messages as the chat template does, and count image tokens as vLLM does.
17
+ DeepSeek-V4.1-Flash-1017 has its own renderers, since its chat template keeps reasoning
18
+ that V4.1's drops.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextvars
24
+ import dataclasses
25
+ import math
26
+ import re
27
+ import uuid
28
+ from collections.abc import Iterator
29
+ from contextlib import contextmanager
30
+
31
+ import tinker
32
+ from PIL import Image
33
+ from tinker_cookbook.renderers import register_renderer
34
+ from tinker_cookbook.renderers.base import (
35
+ Message,
36
+ RenderContext,
37
+ RenderedMessage,
38
+ Renderer,
39
+ RendererError,
40
+ _unpickle_renderer,
41
+ image_to_chunk,
42
+ )
43
+ from tinker_cookbook.renderers.deepseek_v4_1 import (
44
+ _DROP_REASONING_THROUGH,
45
+ DeepSeekV4_1DisableThinkingRenderer,
46
+ DeepSeekV4_1LowReasoningRenderer,
47
+ DeepSeekV4_1MaxReasoningRenderer,
48
+ DeepSeekV4_1Renderer,
49
+ )
50
+ from tinker_cookbook.renderers.glm5_3 import Glm5_3Renderer
51
+
52
+
53
+ class _Glm5_3FlashImageTokens:
54
+ """Image token counts of GLM-5.3-Flash's Glm5NextImageProcessor (transformers 5.16+).
55
+
56
+ Its smart_resize, with the checkpoint's patch_size 14, merge_size 2,
57
+ temporal_patch_size 2, and 16 to 8000 tokens per image.
58
+ """
59
+
60
+ merge_size = 2
61
+ _patch = 14
62
+ _frames = 2
63
+ _factor = _patch * merge_size
64
+ _min_pixels = 16 * _frames * _factor**2
65
+ _max_pixels = 8000 * _frames * _factor**2
66
+
67
+ def get_number_of_image_patches(
68
+ self, height: int, width: int, images_kwargs: dict
69
+ ) -> int:
70
+ factor, frames = self._factor, self._frames
71
+
72
+ def align(value: int) -> int:
73
+ return math.ceil(value / factor) * factor
74
+
75
+ h, w = align(height), align(width)
76
+ if frames * h * w < self._min_pixels:
77
+ scale = math.sqrt(self._min_pixels / (frames * height * width))
78
+ h = align(max(1, math.ceil(height * scale)))
79
+ w = align(max(1, math.ceil(width * scale)))
80
+ if frames * h * w > self._max_pixels:
81
+ # The tallest content height whose aligned canvas fits the budget.
82
+ low, high = 1, height
83
+ h, w = factor, factor
84
+ while low <= high:
85
+ content_height = (low + high) // 2
86
+ content_width = max(1, math.floor(width * content_height / height))
87
+ canvas = (align(content_height), align(content_width))
88
+ if frames * canvas[0] * canvas[1] <= self._max_pixels:
89
+ h, w = canvas
90
+ low = content_height + 1
91
+ else:
92
+ high = content_height - 1
93
+ return (h // self._patch) * (w // self._patch)
94
+
95
+
96
+ _IMAGE_TOKENS = _Glm5_3FlashImageTokens()
97
+
98
+
99
+ class Glm5_3FlashRenderer(Glm5_3Renderer):
100
+ """GLM-5.3 renderer with image parts in system, user, and tool messages."""
101
+
102
+ def render_message(self, message: Message, ctx: RenderContext) -> RenderedMessage:
103
+ content = message["content"]
104
+ if (
105
+ message["role"] == "assistant"
106
+ or isinstance(content, str)
107
+ or all(part["type"] == "text" for part in content)
108
+ ):
109
+ return super().render_message(message, ctx)
110
+ header = super().render_message({**message, "content": ""}, ctx).header
111
+ text, close = "", ""
112
+ if message["role"] == "tool":
113
+ text, close = "<tool_response>", "</tool_response>"
114
+ output: list[tinker.ModelInputChunk] = []
115
+ for part in content:
116
+ if part["type"] == "text":
117
+ text += part["text"]
118
+ continue
119
+ output.append(self._encode(text + "<|begin_of_image|>"))
120
+ output.append(image_to_chunk(part["image"], _IMAGE_TOKENS))
121
+ text = "<|end_of_image|>"
122
+ output.append(self._encode(text + close))
123
+ return RenderedMessage(header=header, output=output)
124
+
125
+ def _encode(self, text: str) -> tinker.types.EncodedTextChunk:
126
+ tokens = self.tokenizer.encode(text, add_special_tokens=False)
127
+ return tinker.types.EncodedTextChunk(tokens=tokens)
128
+
129
+ def __reduce__(self) -> tuple:
130
+ # Unpickling through this module registers the renderer names first.
131
+ return (_unpickle, (self._renderer_name, self._model_name))
132
+
133
+
134
+ def _unpickle(renderer_name: str, model_name: str) -> Renderer:
135
+ return _unpickle_renderer(renderer_name, model_name, False)
136
+
137
+
138
+ class Glm5_3FlashHighReasoningRenderer(Glm5_3FlashRenderer):
139
+ reasoning_effort = "High"
140
+
141
+
142
+ class Glm5_3FlashLowReasoningRenderer(Glm5_3FlashRenderer):
143
+ reasoning_effort = "Low"
144
+
145
+
146
+ class _DeepSeekV4_1FlashImageTokens:
147
+ """Image token counts of DeepSeek-V4.1-Flash, as vLLM's ``load_image`` gives them.
148
+
149
+ The checkpoint's vision_config: patch_size 14, downsample_ratio 3, at least 295936
150
+ pixels and at most 1024 tokens per image, no max_wh_ratio. An image spans
151
+ rows x (cols + 1) + 2 tokens: a newline token closes each row of merged patches,
152
+ and a start and an end token wrap the grid. The count is already in tokens, so
153
+ ``merge_size`` is 1.
154
+ """
155
+
156
+ merge_size = 1
157
+ _patch = 14
158
+ _downsample = 3
159
+ _min_pixels = 295936
160
+ _max_tokens = 1024
161
+
162
+ def get_number_of_image_patches(
163
+ self, height: int, width: int, images_kwargs: dict | None = None
164
+ ) -> int:
165
+ h: float = height
166
+ w: float = width
167
+ if h * w < self._min_pixels: # small images are scaled up first
168
+ scale = (self._min_pixels / (h * w)) ** 0.5
169
+ h, w = int(h * scale), int(w * scale)
170
+ p = self._patch
171
+ tokens = self._span(math.ceil(h / p) * p, math.ceil(w / p) * p)
172
+ if tokens <= self._max_tokens:
173
+ return tokens
174
+ return self._span(*self._shrink_to_budget(h, w))
175
+
176
+ def _span(self, height: int, width: int) -> int:
177
+ p, r = self._patch, self._downsample
178
+ rows, cols = math.ceil((height // p) / r), math.ceil((width // p) / r)
179
+ return rows * (cols + 1) + 2
180
+
181
+ def _shrink_to_budget(self, height: float, width: float) -> tuple[int, int]:
182
+ """The largest aspect-preserving size whose span fits the token budget."""
183
+ p, budget = self._patch, self._max_tokens
184
+ cell = p * self._downsample
185
+ aspect = height / width
186
+ max_cols = math.sqrt((budget - 2) / aspect + 0.25) - 0.5
187
+ max_rows = max_cols * aspect
188
+ if max_cols < 1.0:
189
+ return (budget - 2) // 2 * cell, cell
190
+ if max_rows < 1.0:
191
+ return cell, (budget - 3) * cell
192
+ scale = min(
193
+ math.floor(max_cols) * cell / width, math.floor(max_rows) * cell / height
194
+ )
195
+ return math.floor(height * scale / p) * p, math.floor(width * scale / p) * p
196
+
197
+
198
+ _DSV41_IMAGE_TOKENS = _DeepSeekV4_1FlashImageTokens()
199
+ _DSV41_IMAGE = "<|deepseek_image|>"
200
+ # The images of the conversation being rendered, by the index of the message that
201
+ # renders them.
202
+ _DSV41_IMAGES: contextvars.ContextVar[dict[int, list[Image.Image | str]] | None] = (
203
+ contextvars.ContextVar("_DSV41_IMAGES", default=None)
204
+ )
205
+
206
+
207
+ def _mark_images(
208
+ message: Message, tag: str, images: list[Image.Image | str]
209
+ ) -> Message:
210
+ """Join a message's parts into text, with a marker naming each image."""
211
+ content = message["content"]
212
+ if isinstance(content, str) or all(part["type"] != "image" for part in content):
213
+ return message
214
+ if message["role"] not in ("system", "user", "tool"):
215
+ raise RendererError(
216
+ f"DeepSeek V4.1 has no images in {message['role']} messages"
217
+ )
218
+ parts = []
219
+ for part in content:
220
+ if part["type"] == "image":
221
+ parts.append(f"<{tag}:{len(images)}>")
222
+ images.append(part["image"])
223
+ elif part["type"] == "text":
224
+ if _DSV41_IMAGE in part["text"]:
225
+ raise RendererError(
226
+ f"Text contains {_DSV41_IMAGE}; pass images as image parts"
227
+ )
228
+ parts.append(part["text"])
229
+ else:
230
+ raise RendererError(
231
+ f"DeepSeek V4.1 renderer does not support {part['type']!r} parts"
232
+ )
233
+ # The template joins a message's text and image blocks with blank lines.
234
+ return {**message, "content": "\n\n".join(parts)}
235
+
236
+
237
+ class DeepSeekV4_1FlashRenderer(DeepSeekV4_1Renderer):
238
+ """DeepSeek V4.1 renderer with image parts in system, user, and tool messages."""
239
+
240
+ @contextmanager
241
+ def _conversation(self, messages: list[Message]) -> Iterator[list[Message]]:
242
+ if _DSV41_IMAGES.get() is not None: # an outer call already shaped them
243
+ with super()._conversation(messages) as shaped:
244
+ yield shaped
245
+ return
246
+ # The base class merges and reorders messages as text, so each image travels
247
+ # as a marker in its message's text and is found wherever that text lands.
248
+ tag = uuid.uuid4().hex
249
+ marker = re.compile(f"<{tag}:(\\d+)>")
250
+ images: list[Image.Image | str] = []
251
+ marked = [_mark_images(m, tag, images) for m in messages]
252
+ with super()._conversation(marked) as shaped:
253
+ by_message: dict[int, list[Image.Image | str]] = {}
254
+ placed: list[Message] = []
255
+ for idx, message in enumerate(shaped):
256
+ content = message["content"]
257
+ if isinstance(content, str) and tag in content:
258
+ by_message[idx] = [images[int(n)] for n in marker.findall(content)]
259
+ message = {**message, "content": marker.sub(_DSV41_IMAGE, content)}
260
+ placed.append(message)
261
+ token = _DSV41_IMAGES.set(by_message)
262
+ try:
263
+ yield placed
264
+ finally:
265
+ _DSV41_IMAGES.reset(token)
266
+
267
+ def render_message(self, message: Message, ctx: RenderContext) -> RenderedMessage:
268
+ rendered = super().render_message(message, ctx)
269
+ images = iter((_DSV41_IMAGES.get() or {}).get(ctx.idx, []))
270
+ (image_token,) = self._encode(_DSV41_IMAGE)
271
+ output: list[tinker.types.ModelInputChunk] = []
272
+ for chunk in rendered.output:
273
+ if not isinstance(chunk, tinker.types.EncodedTextChunk):
274
+ output.append(chunk)
275
+ continue
276
+ text: list[int] = []
277
+ for token in chunk.tokens:
278
+ if token != image_token:
279
+ text.append(token)
280
+ continue
281
+ image = next(images, None)
282
+ if image is None:
283
+ raise RendererError(
284
+ f"Text contains {_DSV41_IMAGE}; pass images as image parts"
285
+ )
286
+ if text:
287
+ output.append(tinker.types.EncodedTextChunk(tokens=text))
288
+ text = []
289
+ output.append(image_to_chunk(image, _DSV41_IMAGE_TOKENS))
290
+ if text:
291
+ output.append(tinker.types.EncodedTextChunk(tokens=text))
292
+ return dataclasses.replace(rendered, output=output)
293
+
294
+ def __reduce__(self) -> tuple:
295
+ # Unpickling through this module registers the renderer names first.
296
+ return (_unpickle, (self._renderer_name, self._model_name))
297
+
298
+
299
+ class DeepSeekV4_1FlashLowReasoningRenderer(DeepSeekV4_1FlashRenderer):
300
+ reasoning_effort = DeepSeekV4_1LowReasoningRenderer.reasoning_effort
301
+
302
+
303
+ class DeepSeekV4_1FlashMaxReasoningRenderer(DeepSeekV4_1FlashRenderer):
304
+ reasoning_effort = DeepSeekV4_1MaxReasoningRenderer.reasoning_effort
305
+
306
+
307
+ class DeepSeekV4_1FlashDisableThinkingRenderer(DeepSeekV4_1FlashRenderer):
308
+ reasoning_effort = DeepSeekV4_1DisableThinkingRenderer.reasoning_effort
309
+
310
+
311
+ def _dsv41_1017_drop_reasoning_through(messages: list[Message]) -> int:
312
+ """The last user turn of DeepSeek-V4.1-Flash-1017's chat template.
313
+
314
+ V4.1's template starts a user turn at every user or tool message. 1017's does not
315
+ start one at a run of messages holding only tool results, so the reasoning of an
316
+ agentic turn's tool-calling assistant messages stays in the prompt until the next
317
+ user message.
318
+ """
319
+ last = -1
320
+ idx = 0
321
+ while idx < len(messages):
322
+ role = messages[idx]["role"]
323
+ if role == "system" and idx > 0:
324
+ last = idx
325
+ if role not in ("user", "tool"):
326
+ idx += 1
327
+ continue
328
+ end = idx
329
+ while end + 1 < len(messages) and messages[end + 1]["role"] in ("user", "tool"):
330
+ end += 1
331
+ if any(m["role"] == "user" for m in messages[idx : end + 1]):
332
+ last = end
333
+ idx = end + 1
334
+ return last
335
+
336
+
337
+ class DeepSeekV4_1Flash1017Renderer(DeepSeekV4_1FlashRenderer):
338
+ """DeepSeek-V4.1-Flash-1017: tool results alone do not end an agentic turn's reasoning."""
339
+
340
+ @contextmanager
341
+ def _conversation(self, messages: list[Message]) -> Iterator[list[Message]]:
342
+ # The base class re-enters with a prefix of the conversation; only the outermost
343
+ # call sees the whole conversation and may set where reasoning stops being dropped.
344
+ outermost = _DROP_REASONING_THROUGH.get() is None
345
+ with super()._conversation(messages) as shaped:
346
+ through = _DROP_REASONING_THROUGH.get()
347
+ if not outermost or through is None or through < 0: # nothing is dropped
348
+ yield shaped
349
+ return
350
+ token = _DROP_REASONING_THROUGH.set(
351
+ _dsv41_1017_drop_reasoning_through(shaped)
352
+ )
353
+ try:
354
+ yield shaped
355
+ finally:
356
+ _DROP_REASONING_THROUGH.reset(token)
357
+
358
+
359
+ class DeepSeekV4_1Flash1017LowReasoningRenderer(DeepSeekV4_1Flash1017Renderer):
360
+ reasoning_effort = DeepSeekV4_1LowReasoningRenderer.reasoning_effort
361
+
362
+
363
+ class DeepSeekV4_1Flash1017MaxReasoningRenderer(DeepSeekV4_1Flash1017Renderer):
364
+ reasoning_effort = DeepSeekV4_1MaxReasoningRenderer.reasoning_effort
365
+
366
+
367
+ class DeepSeekV4_1Flash1017DisableThinkingRenderer(DeepSeekV4_1Flash1017Renderer):
368
+ reasoning_effort = DeepSeekV4_1DisableThinkingRenderer.reasoning_effort
369
+
370
+
371
+ for _name, _cls in {
372
+ "baseten/glm5_3_flash_max_reasoning": Glm5_3FlashRenderer,
373
+ "baseten/glm5_3_flash_high_reasoning": Glm5_3FlashHighReasoningRenderer,
374
+ "baseten/glm5_3_flash_low_reasoning": Glm5_3FlashLowReasoningRenderer,
375
+ }.items():
376
+ register_renderer(_name, lambda tokenizer, _, cls=_cls: cls(tokenizer))
377
+
378
+ _DSV41_RENDERERS: dict[str, type[DeepSeekV4_1FlashRenderer]] = {
379
+ "baseten/deepseekv4_1_flash": DeepSeekV4_1FlashRenderer,
380
+ "baseten/deepseekv4_1_flash_low_reasoning": DeepSeekV4_1FlashLowReasoningRenderer,
381
+ "baseten/deepseekv4_1_flash_max_reasoning": DeepSeekV4_1FlashMaxReasoningRenderer,
382
+ "baseten/deepseekv4_1_flash_disable_thinking": (
383
+ DeepSeekV4_1FlashDisableThinkingRenderer
384
+ ),
385
+ "baseten/deepseekv4_1_flash_1017": DeepSeekV4_1Flash1017Renderer,
386
+ "baseten/deepseekv4_1_flash_1017_low_reasoning": (
387
+ DeepSeekV4_1Flash1017LowReasoningRenderer
388
+ ),
389
+ "baseten/deepseekv4_1_flash_1017_max_reasoning": (
390
+ DeepSeekV4_1Flash1017MaxReasoningRenderer
391
+ ),
392
+ "baseten/deepseekv4_1_flash_1017_disable_thinking": (
393
+ DeepSeekV4_1Flash1017DisableThinkingRenderer
394
+ ),
395
+ }
396
+ for _name, _dsv41 in _DSV41_RENDERERS.items():
397
+ register_renderer(_name, lambda tokenizer, _, cls=_dsv41: cls(tokenizer))
398
+ register_renderer(
399
+ "baseten/deepseekv4_1_flash_preserve_thinking",
400
+ lambda tokenizer, _: DeepSeekV4_1FlashRenderer(
401
+ tokenizer, strip_thinking_from_history=False
402
+ ),
403
+ )
404
+ register_renderer(
405
+ "baseten/deepseekv4_1_flash_1017_preserve_thinking",
406
+ lambda tokenizer, _: DeepSeekV4_1Flash1017Renderer(
407
+ tokenizer, strip_thinking_from_history=False
408
+ ),
409
+ )
@@ -493,16 +493,33 @@ def tokenizer_source(
493
493
  ) -> tuple[str, str | None]:
494
494
  """The Hugging Face repo and revision to load a run's tokenizer from.
495
495
 
496
- A run on a custom base checkpoint (``hf://<org>/<repo>@<sha>``) tokenizes with the
496
+ A run on a Hugging Face base checkpoint (``hf://<org>/<repo>@<sha>``) tokenizes with the
497
497
  checkpoint's own files at its pinned commit: its sampler loads the same files, so the
498
- two can't disagree.
498
+ two can't disagree. A base checkpoint anywhere else (an object store or a Baseten
499
+ training job) can't be read from here, so the run tokenizes with ``base_model``'s
500
+ tokenizer; such a checkpoint must ship the same tokenizer files.
499
501
  """
500
502
  if base_checkpoint is None:
501
503
  return base_model, None
504
+ if not base_checkpoint.startswith("hf://"):
505
+ _warn_base_model_tokenizer(base_model, base_checkpoint)
506
+ return base_model, None
502
507
  repo_id, _, revision = base_checkpoint.removeprefix("hf://").partition("@")
503
508
  return repo_id, revision or None
504
509
 
505
510
 
511
+ @lru_cache(maxsize=None)
512
+ def _warn_base_model_tokenizer(base_model: str, base_checkpoint: str) -> None:
513
+ """Warn once per checkpoint: the sampler loads the checkpoint's own tokenizer."""
514
+ logger.warning(
515
+ "Tokenizing with %s's tokenizer: the SDK cannot read base checkpoint %s. "
516
+ "If the checkpoint's tokenizer or chat template differs, the SDK and the "
517
+ "sampler tokenize differently.",
518
+ base_model,
519
+ base_checkpoint,
520
+ )
521
+
522
+
506
523
  @lru_cache(maxsize=32)
507
524
  def _load_tokenizer(model_name: str, revision: str | None = None):
508
525
  """Load and cache a HuggingFace tokenizer, at ``revision`` when given."""
@@ -1253,8 +1270,6 @@ class SamplingClient:
1253
1270
  *,
1254
1271
  affinity_key: str | None = None,
1255
1272
  include_routed_experts: bool | None = None,
1256
- score_centering_samples: int = 0,
1257
- score_centering_top_k: int = 0,
1258
1273
  rollout_id: str | None = None,
1259
1274
  ) -> SampleResponse:
1260
1275
  """Generate text completions via the sampler's ``/sample`` endpoint.
@@ -1263,10 +1278,6 @@ class SamplingClient:
1263
1278
  enabled MoE models) on a recording client. Explicit capture requires
1264
1279
  ``record_stability_info=True``; ``None`` uses the sampler's default.
1265
1280
 
1266
- ``score_centering_samples`` captures independent behavior draws;
1267
- ``score_centering_top_k`` captures a head for tail-modeled centering.
1268
- Choose at most one on a recording client. Neither changes rollout top_k.
1269
-
1270
1281
  Routing fields go in request headers (``X-Checkpoint-Path``,
1271
1282
  ``X-Min-Policy-Version``); the sampler reads them and decides
1272
1283
  which adapter to serve. Returns 408 if the live adapter stays
@@ -1295,8 +1306,6 @@ class SamplingClient:
1295
1306
  topk_prompt_logprobs,
1296
1307
  affinity_key=affinity_key,
1297
1308
  include_routed_experts=include_routed_experts,
1298
- score_centering_samples=score_centering_samples,
1299
- score_centering_top_k=score_centering_top_k,
1300
1309
  rollout_id=rollout_id,
1301
1310
  )
1302
1311
  )
@@ -1311,8 +1320,6 @@ class SamplingClient:
1311
1320
  *,
1312
1321
  affinity_key: str | None = None,
1313
1322
  include_routed_experts: bool | None = None,
1314
- score_centering_samples: int = 0,
1315
- score_centering_top_k: int = 0,
1316
1323
  rollout_id: str | None = None,
1317
1324
  ) -> SampleResponse:
1318
1325
  """Async version of :meth:`sample` — issues the HTTP POST natively on
@@ -1326,20 +1333,6 @@ class SamplingClient:
1326
1333
  still queued request is cancelled and ``SampleTimeoutError`` is raised.
1327
1334
  Submit retries before the acceptance are bounded by ``ready_timeout``.
1328
1335
  """
1329
- for name, value, maximum in (
1330
- ("score_centering_samples", score_centering_samples, 64),
1331
- ("score_centering_top_k", score_centering_top_k, 256),
1332
- ):
1333
- if type(value) is not int or not 0 <= value <= maximum:
1334
- raise ValueError(f"{name} must be an integer between 0 and {maximum}")
1335
- if score_centering_samples and score_centering_top_k:
1336
- raise ValueError(
1337
- "choose one score-centering capture mode per sample request"
1338
- )
1339
- if (
1340
- score_centering_samples or score_centering_top_k
1341
- ) and not self._record_stability_info:
1342
- raise ValueError("score capture requires record_stability_info=True")
1343
1336
  if topk_prompt_logprobs < 0:
1344
1337
  raise ValueError("topk_prompt_logprobs must be non-negative")
1345
1338
  if affinity_key == "":
@@ -1359,18 +1352,12 @@ class SamplingClient:
1359
1352
  "logprobs": 0,
1360
1353
  "return_tokens_as_token_ids": True,
1361
1354
  }
1362
- if sp.top_k is not None and sp.top_k > 0:
1363
- body["top_k"] = sp.top_k
1364
1355
  if self._record_stability_info:
1365
1356
  body["record_stability_info"] = True
1366
1357
  # session_id in the sampling body is reserved for queue affinity.
1367
1358
  body["sampling_session_id"] = self._session_id
1368
1359
  if include_routed_experts is not None:
1369
1360
  body["include_routed_experts"] = include_routed_experts
1370
- if score_centering_samples:
1371
- body["score_centering_samples"] = score_centering_samples
1372
- if score_centering_top_k:
1373
- body["score_centering_top_k"] = score_centering_top_k
1374
1361
  if model_input_chunks is not None:
1375
1362
  body["model_input_chunks"] = model_input_chunks
1376
1363
  body["return_token_ids"] = True
@@ -1380,6 +1367,8 @@ class SamplingClient:
1380
1367
  body["max_tokens"] = sp.max_tokens
1381
1368
  if sp.seed is not None:
1382
1369
  body["seed"] = sp.seed
1370
+ if sp.top_k is not None and sp.top_k > 0:
1371
+ body["top_k"] = sp.top_k
1383
1372
  if sp.stop is not None:
1384
1373
  if (
1385
1374
  isinstance(sp.stop, list)