Skip to content

Cancel the generation when a response stream's consumer stops early - #202

Open
james-333i wants to merge 1 commit into
huggingface:mainfrom
james-333i:fix/stream-consumer-cancellation
Open

Cancel the generation when a response stream's consumer stops early#202
james-333i wants to merge 1 commit into
huggingface:mainfrom
james-333i:fix/stream-consumer-cancellation

Conversation

@james-333i

Copy link
Copy Markdown

streamResponse wraps the model's stream in a relay that appends the response to the transcript when generation completes. The relay had no termination handler, so a consumer that stopped iterating early, whether by breaking out of the loop, cancelling its task, or dropping the stream, left the relay consuming and the backend generating to its token limit in the background. That ghost generation kept the model weights and a growing KV cache alive for tens of seconds after the response visibly ended, which surfaces as multi-gigabyte memory spikes and delayed releases on device.

Cancel the relay task when the stream terminates by cancellation. The cancellation propagates through the upstream stream's own termination handler to the backend's generation task, releasing the model promptly. Natural completion still finishes the relay and records the transcript entry exactly as before.

Diagnosed from a memory graph capture showing the model module retained by two suspended task stacks (the relay and the backend generation) long after the consumer had stopped.

streamResponse wraps the model's stream in a relay that appends the
response to the transcript when generation completes. The relay had no
termination handler, so a consumer that stopped iterating early — a
break, a cancelled task, or a dropped stream — left the relay consuming
and the backend generating to its token limit in the background. That
ghost generation kept the model and its growing KV cache alive for tens
of seconds after the response visibly ended.

Cancel the relay task when the stream terminates by cancellation. The
cancellation propagates through the upstream stream's own termination
handler to the backend's generation task, releasing the model promptly.
Natural completion still finishes the relay and records the transcript
entry as before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant