Skip to content

fix(llama): release a vision chat handler's mtmd context on close (#2342) - #2343

Merged
abetlen merged 2 commits into
abetlen:mainfrom
Anai-Guo:fix/close-chat-handler-mtmd
Aug 17, 2026
Merged

fix(llama): release a vision chat handler's mtmd context on close (#2342)#2343
abetlen merged 2 commits into
abetlen:mainfrom
Anai-Guo:fix/close-chat-handler-mtmd

Conversation

@Anai-Guo

@Anai-Guo Anai-Guo commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #2342.

  • Register MTMD context cleanup on the Llama instance whose model created it.
  • Release the context before model teardown and reset the handler for reuse.
  • Avoid making Llama own arbitrary resources from custom chat handlers.

Anai Guo and others added 2 commits August 17, 2026 00:22
…etlen#2342)

`Llama.close()` tore down the model and its context but left the chat
handler's `_exit_stack` untouched, so the mtmd/clip context it built from
that model was never freed.

Handlers routinely outlive the `Llama` that initialized them -- callers
construct one handler and reuse it across loads -- and
`_init_mtmd_context()` returns early while `mtmd_ctx` is set. After the
first `close()` the handler therefore kept a context bound to an
already-freed model and handed it back on the next load, where it
surfaces as a null `mtmd_ctx` on the C++ side.

Register the handler's exit stack on the Llama's `_stack`. It unwinds
LIFO, so the mtmd context is released ahead of the model teardown
registered earlier in `__init__`, and `mtmd_free` resets `mtmd_ctx` to
`None` so the next load re-initializes cleanly. Duck-typed on
`_exit_stack`, which both `Llava15ChatHandler` and `MTMDChatHandler`
(and every subclass) expose.
@abetlen
abetlen force-pushed the fix/close-chat-handler-mtmd branch from dbededa to 11aeacd Compare August 17, 2026 07:23
@abetlen
abetlen merged commit 9dd3950 into abetlen:main Aug 17, 2026
15 checks passed
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.

Llama.close() doesn't clean up chat_handler causing null pointer on second load of a vision model

2 participants