karthik-0306 commented on code in PR #41405:
URL: https://github.com/apache/beam/pull/41405#discussion_r4697589399


##########
sdks/python/apache_beam/ml/inference/base.py:
##########
@@ -725,7 +725,13 @@ def load(self, key: str) -> _ModelLoadStats:
     start_time = _to_milliseconds(time.time_ns())
     shared_handle = multi_process_shared.MultiProcessShared(
         mh.load_model, tag=tag)
-    model_reference = shared_handle.acquire()
+    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)

Review 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 `BaseException` and only removes the tag if it still 
belongs to this call.
   - Eviction and `update_model_handler` now go through `_release_tag`, which 
skips a model that's still loading instead of raising `KeyError` on 
`_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 == 0` guard, 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.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to