fix memleak when input contain large image data#4610
Merged
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
This PR introduces a temporary workaround to mitigate host-memory growth when serving requests that include large multimodal (image) inputs, by periodically forcing Python GC + libc malloc trimming after a configurable number of multimodal sessions end. It also adds a small quality-of-life change to rename the ZMQ MP engine process for easier identification.
Changes:
- Add
LMDEPLOY_MULTIMODAL_SESSION_TRIM_COUNTenv var to control how often memory trimming runs. - Track ended multimodal sessions in the PyTorch
Engineand triggergc.collect()+malloc_trim()after the configured threshold. - Route disaggregation “cache free” teardown through
Engine.end_session()(instead of directly callingscheduler.end_session) so trimming logic can run; rename the ZMQ MP engine process viaprctl.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
lmdeploy/pytorch/envs.py |
Adds env var for controlling multimodal-session trim frequency. |
lmdeploy/pytorch/engine/engine.py |
Implements multimodal session detection/counter and memory trimming via GC + malloc_trim. |
lmdeploy/pytorch/engine/mp_engine/zmq_engine.py |
Attempts to rename the MP process using prctl for easier debugging. |
lmdeploy/pytorch/disagg/conn/engine_conn.py |
Uses Engine.end_session() so teardown can trigger the new trim behavior. |
Comments suppressed due to low confidence (3)
lmdeploy/pytorch/engine/engine.py:350
gc.collect()/malloc_trim()are invoked synchronously in the request-processing path (e.g.,end_session()and ZMQ free handling). Full GC + malloc trimming can stall the asyncio loop and introduce latency spikes. Consider offloading the trim to a background thread/task (or rate-limit it with time-based throttling) so session teardown doesn’t block the engine loop.
def _maybe_trim_multimodal_session(self, has_multimodal: bool):
"""Trim host memory after enough multimodal sessions have ended."""
if not has_multimodal or self._multimodal_session_trim_count <= 0:
return
self._multimodal_session_end_count += 1
if self._multimodal_session_end_count < self._multimodal_session_trim_count:
return
self._multimodal_session_end_count = 0
self._try_mem_trim()
lmdeploy/pytorch/engine/engine.py:337
_has_multimodal_session()relies onHistoryMultiModals.empty(), but that method currently iterates over the dict keys (seeHistoryMultiModals.emptyinlmdeploy/pytorch/messages.py) and can report non-empty incorrectly. That can cause_maybe_trim_multimodal_sessionto trigger trims unexpectedly or miss them in edge cases. Either fixHistoryMultiModals.empty()to checkself.multimodals.values()or avoid using it here by checking for any non-empty modal data directly.
def _has_multimodal_session(session) -> bool:
"""Check whether session has multimodal history."""
return any(not seq.history_multimodals.empty() for seq in session.sequences.values())
lmdeploy/pytorch/engine/engine.py:349
- This introduces new behavior gated by
LMDEPLOY_MULTIMODAL_SESSION_TRIM_COUNT, but there’s no unit test ensuring the counter resets and_try_mem_trimis invoked only after the configured number of multimodal session endings. Since there are existing Engine unit tests undertests/pytorch/engine/, consider adding a focused test around_maybe_trim_multimodal_session(mocking_try_mem_trim).
def _maybe_trim_multimodal_session(self, has_multimodal: bool):
"""Trim host memory after enough multimodal sessions have ended."""
if not has_multimodal or self._multimodal_session_trim_count <= 0:
return
self._multimodal_session_end_count += 1
if self._multimodal_session_end_count < self._multimodal_session_trim_count:
return
self._multimodal_session_end_count = 0
self._try_mem_trim()
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+326
to
+332
| def _try_mem_trim(): | ||
| """Try to trim memory.""" | ||
| try: | ||
| gc.collect() | ||
| ctypes.CDLL('libc.so.6').malloc_trim(0) | ||
| except Exception as e: | ||
| logger.debug(f'Memory trim failed: {e}') |
| # try rename the process | ||
| try: | ||
| import ctypes | ||
| ctypes.CDLL(None).prctl(15, b'ZMQMPEngine', 0, 0, 0) |
CUHKSZzxy
approved these changes
May 26, 2026
lvhan028
pushed a commit
to lvhan028/lmdeploy
that referenced
this pull request
May 27, 2026
* fix memleak when input contain large image data * fix sleep
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.
This is a temp work around.
A better fix is making a sharemem pool and pass data handle to the engine.