Repository navigation
[RunInference] Retry failed model loads in multi-model KeyedModelHandler - #41405
Conversation
There was a problem hiding this comment.
📋 Review Summary
This PR fixes a bug in _ModelHandlerManager.load where a failure during shared_handle.acquire() left a stale tag in _tag_map without a corresponding entry in _proxy_map. Cleaning up self._tag_map[key] on exception ensures subsequent batches properly retry and cache the model load and prevents KeyError during LRU eviction or model updates.
🔍 General Feedback
- The fix in
sdks/python/apache_beam/ml/inference/base.pyis minimal, targeted, and directly addresses the root cause of #41404. - The unit test
test_model_handler_manager_retries_failed_loadthoroughly covers failed initial loads, subsequent retry and caching behavior, and LRU eviction after recovery.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
|
Assigning reviewers: R: @claudevdm for label python. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
| try: | ||
| model_reference = shared_handle.acquire() | ||
| except Exception: | ||
| # Forget the tag so that the next call loads the model again instead of | ||
| # returning a tag that has no model behind it. | ||
| del self._tag_map[key] | ||
| raise | ||
| self._proxy_map[tag] = (shared_handle, model_reference) |
There was a problem hiding this comment.
Thanks for catching and fixing this! Instead of inserting self._tag_map[key] before loading and rolling it back on exception, could we defer setting self._tag_map[key] = tag until right after shared_handle.acquire() succeeds (next to self._proxy_map[tag] = (shared_handle, model_reference)) and adjust the LRU check above to self._max_models <= len(self._tag_map) and self._tag_map?
if key in self._tag_map:
self._tag_map.move_to_end(key)
return _ModelLoadStats(self._tag_map[key], None, None)
tag = uuid.uuid4().hex
mh = self._mh_map[key]
if (self._max_models is not None and
self._max_models <= len(self._tag_map) and self._tag_map):
# If we're about to exceed our LRU size, release the last used model.
tag_to_remove = self._tag_map.popitem(last=False)[1]
shared_handle, model_to_remove = self._proxy_map[tag_to_remove]
shared_handle.release(model_to_remove)
del self._proxy_map[tag_to_remove]
# Load the new model
memory_before = _get_current_process_memory_in_bytes()
start_time = _to_milliseconds(time.time_ns())
shared_handle = multi_process_shared.MultiProcessShared(
mh.load_model, tag=tag)
model_reference = shared_handle.acquire()
self._tag_map[key] = tag
self._proxy_map[tag] = (shared_handle, model_reference)That keeps _tag_map and _proxy_map strictly in sync while acquire() is in flight (avoiding a window on the multi-threaded MultiProcessShared manager where a concurrent load(key) sees a tag with no model behind it or an eviction/update_model_handler hits KeyError on _proxy_map[tag]), and also covers failures outside acquire() (e.g., self._mh_map[key] or BaseException) without needing a try/except rollback.
There was a problem hiding this comment.
Thanks for the review! I tried this version, but it changes one thing the current code relies on. load() gets called from several threads at once, since the shared manager serves calls on separate threads. Today, if a second load(key) comes in while the first one is still loading, it gets the same tag, and both share one model load. If _tag_map[key] is only set after acquire(), the second call doesn't see the key yet, so it loads its own copy under a new tag. When both finish, the first tag's proxy stays in _proxy_map and is never released. I checked this with two threads loading the same key: 1 load_model call and 1 proxy with the current code, and 2 calls and 2 proxies with the deferred insert. I also found two related cases: concurrent loads of different keys can go over max_models, and an update_model_handler call made while the key is loading gets lost, so the old model is kept.
So I kept reserving the tag before the load and covered the points you raised:
self._mh_map[key]is looked up before the tag is reserved, so an unknown key leaves nothing in_tag_map.- The rollback catches
BaseExceptionand only removes the tag if it still belongs to this call. - Eviction and
update_model_handlernow go through_release_tag, which skips a model that's still loading instead of raisingKeyErroron_proxy_map[tag]. When that load finishes,load()sees its tag was removed and releases the model instead of keeping it. - I used your
max_models == 0guard, so a new key never evicts itself.
I added tests for each of these, including two threads loading the same key and evicting or updating a model while it's loading. I also merged master to fix the conflict. If you'd still prefer the deferred insert, I'm happy to switch to it.
|
Also, please resolve the conflicts. Otherwise, this LGTM |
…d-model-load-failure # Conflicts: # CHANGES.md
61b7dc8 to
1345a6f
Compare
| if self._tag_map.get(key) == tag: | ||
| self._proxy_map[tag] = (shared_handle, model_reference) | ||
| else: | ||
| # The model was evicted or updated while it was loading, so don't keep | ||
| # a reference to it. | ||
| shared_handle.release(model_reference) |
There was a problem hiding this comment.
Good catch on preserving shared in-flight loads — keeping the tag reservation before acquire() makes sense.
Since _ModelHandlerManager serves concurrent calls across threads (and already uses self._max_models_lock for that reason), could we also guard the short _tag_map / _proxy_map / _mh_map reads & updates with a lock (releasing the lock before calling shared_handle.acquire() and shared_handle.release())? Without a lock, there are still a few narrow TOCTOU races:
- Between
if self._tag_map.get(key) == tag:andself._proxy_map[tag] = (shared_handle, model_reference): if another thread evicts or updateskeyin that window,_release_tag(tag)popsNoneandload()then insertstaginto_proxy_mapwith no_tag_mapentry, leaking the model reference. - Between
if key in self._tag_map:andmove_to_end(key)/_tag_map[key]inload()(orself._tag_map.pop(key)inupdate_model_handler), a concurrent eviction/update can raiseKeyError. - Two threads hitting a cold
load(same_key)before_tag_map[key] = tagcan both miss and double-load (and concurrent loads of different keys can overshoot_max_models).
Reusing self._max_models_lock (e.g., as self._lock) for the in-memory dict/LRU state and doing acquire() / release() outside the lock keeps shared in-flight loads intact with no deadlock risk and closes all of these cleanly.
There was a problem hiding this comment.
Thanks, done. All map and counter reads and writes now happen under _lock, and acquire() and release() always run outside it, so concurrent loads of the same key still share one model.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #41405 +/- ##
=========================================
Coverage 58.05% 58.05%
Complexity 2842 2842
=========================================
Files 1210 1210
Lines 173310 173339 +29
Branches 2329 2329
=========================================
+ Hits 100617 100635 +18
- Misses 69978 69989 +11
Partials 2715 2715
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
damccorm
left a comment
There was a problem hiding this comment.
Thanks - I'll merge once checks pass
Fixes #41404
_ModelHandlerManager.loadstored a key's tag in_tag_mapbefore loading the model. Ifload_model()raised, for example on a transient GCS error, the tag stayed in_tag_mapwith no entry in_proxy_map. After that, everyload(key)returned the stale tag, so the model was reloaded on every batch, and evicting or updating that key failed withKeyError: '<uuid>'.This removes the key from
_tag_mapwhen the load fails, so the next batch loads the model again and it is cached like any other key.Testing: added
test_model_handler_manager_retries_failed_load, which fails on master and passes with the fix. The_ModelHandlerManager,KeyedModelHandlerandModelManagerTesttests pass. yapf and ruff are clean.R: @damccorm