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


##########
sdks/python/apache_beam/ml/inference/base.py:
##########
@@ -707,26 +707,38 @@ def load(self, key: str) -> _ModelLoadStats:
     if key in self._tag_map:
       self._tag_map.move_to_end(key)
       return _ModelLoadStats(self._tag_map[key], None, None)
-    else:
-      self._tag_map[key] = uuid.uuid4().hex
 
-    tag = self._tag_map[key]
     mh = self._mh_map[key]
+    tag = uuid.uuid4().hex
+    # Reserve the tag before loading the model, so that a concurrent load(key)
+    # returns this tag and shares this model instead of loading another copy.
+    self._tag_map[key] = tag
 
-    if self._max_models is not None and self._max_models < len(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]
+    if (self._max_models is not None and
+        len(self._tag_map) > max(self._max_models, 1)):
+      # If we're about to exceed our LRU size, release the least recently used
+      # model. The new key is the most recently used one, so it is kept.
+      self._release_tag(self._tag_map.popitem(last=False)[1])
 
     # 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._proxy_map[tag] = (shared_handle, model_reference)
+    try:
+      model_reference = shared_handle.acquire()
+    except BaseException:
+      # Forget the tag so that the next call loads the model again instead of
+      # returning a tag that has no model behind it.
+      if self._tag_map.get(key) == tag:
+        del self._tag_map[key]
+      raise
+    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)

Review 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.



-- 
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