Fix: model_dump(mode="json") falls back to __repr__#20
Open
slevental wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fix:
model_dump(mode="json")falls back to__repr__for ModelInput chunks, burning 97% CPU on token formattingProblem
Every
sample_async()call serializes theSampleRequestvia:This triggers pydantic v2's
model_dump(mode="json")on the full request,including
prompt: ModelInput→chunks: List[ModelInputChunk].ModelInputChunkis defined as:PropertyInfo(discriminator=...)is a tinker-internal annotation — pydantic v2does not recognize it as a discriminator for serialization. When pydantic's JSON-mode
serializer encounters the union variants, it cannot resolve their serialization schema
and falls back to
__repr__()on each chunk object.EncodedTextChunk.__repr__(inherited from pydantic's default) recursively formatsevery field, including
tokens: Sequence[int]— which typically containsthousands of token IDs. This turns every single LLM sampling call into an
O(n_tokens) string-formatting operation under the GIL.
Impact
Profiling an RL training loop (8 tasks × 4 rollouts, multi-turn agent with ~8K
context tokens per turn) showed:
97% of all CPU time was spent formatting token lists as strings that are
immediately discarded. The GIL was held at 94%, serializing all concurrent async
episodes on a single core.
Fix
Add cheap
__repr__overrides onEncodedTextChunkandModelInputso thefallback path is O(1) instead of O(n_tokens):
This is a targeted symptom fix. The underlying issue is that
ModelInputChunkuses
PropertyInfo(discriminator=...)instead of pydantic v2's nativepydantic.Discriminator, but changing the type alias has broader compatibilityimplications.
How to reproduce