Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@
* (Python) Fixed the DataFrame API `skew()` and `kurtosis()` failing with `UnboundLocalError` when all of the data is in one partition ([#41283](https://github.com/apache/beam/issues/41283)).
* (Python) Fixed anomaly detection `MajorityVote` ignoring a custom `normal_label` when votes tie: `tie_breaker` now defaults to `normal_label` instead of the constant 0 ([#41232](https://github.com/apache/beam/issues/41232)).
* (Java) Fixed IcebergIO's CDC sink and AddFiles ignoring a requested `format-version` when creating tables, and AddFiles failing the run when a file adds a v3-only column to a v2 table ([#41582](https://github.com/apache/beam/pull/41582)).
* (Python) A multi-model `KeyedModelHandler` now retries a model load that failed. Before, one failed `load_model` call made it reload that model on every batch and fail with a `KeyError` when the model was evicted or updated. Evicting or updating a model that is still loading also no longer fails with a `KeyError` ([#41404](https://github.com/apache/beam/issues/41404)).
* Fixed X (Java/Python) ([#X](https://github.com/apache/beam/issues/X)).
* (Python) Fixed MLTransform embeddings created with `columns=`, the RAG embedding transforms and `VertexAIMultiModalEmbeddings` modifying their input elements, so that other transforms reading the same PCollection could see the embeddings ([#41233](https://github.com/apache/beam/issues/41233)).
* (Python) Dataflow runner: artifacts from different environments that share a name but have different content (for example each environment's `requirements.txt` in a Beam YAML pipeline with a `pythonPackage` provider) are now staged to distinct objects in the staging location instead of overwriting each other, which made workers fail the staged-file integrity check ([#40699](https://github.com/apache/beam/issues/40699)).
Expand Down
101 changes: 68 additions & 33 deletions sdks/python/apache_beam/ml/inference/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,9 +676,10 @@ def __init__(self, mh_map: dict[str, ModelHandler]):
self._max_models = None
# Process ids that have already contributed to _max_models
self._incremented_process_ids: set[int] = set()
# Guards _max_models and _incremented_process_ids, since the shared
# manager serves calls from several processes on separate threads.
self._max_models_lock = threading.Lock()
# Guards the maps and counters below, since the shared manager serves calls
# from several processes on separate threads. Models are never loaded or
# released while holding it, so a slow load doesn't block other keys.
self._lock = threading.Lock()
# Map keys to model handlers
self._mh_map: dict[str, ModelHandler] = mh_map
# Map keys to the last updated model path for that key
Expand All @@ -704,29 +705,48 @@ def load(self, key: str) -> _ModelLoadStats:
# is released. This needs to be unique between releasing/reacquiring th
# model because otherwise the ProxyManager will try to reuse the model that
# has been released and deleted.
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]

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]
with self._lock:
if key in self._tag_map:
self._tag_map.move_to_end(key)
return _ModelLoadStats(self._tag_map[key], None, None)

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

evicted = None
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.
evicted = self._pop_proxy(self._tag_map.popitem(last=False)[1])
self._release_proxy(evicted)

# 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.
with self._lock:
if self._tag_map.get(key) == tag:
del self._tag_map[key]
raise
with self._lock:
keep_model = self._tag_map.get(key) == tag
if keep_model:
self._proxy_map[tag] = (shared_handle, model_reference)
if not keep_model:
# The model was evicted or updated while it was loading, so don't keep
# a reference to it.
shared_handle.release(model_reference)
memory_after = _get_current_process_memory_in_bytes()
end_time = _to_milliseconds(time.time_ns())

Expand All @@ -745,7 +765,7 @@ def increment_max_models(
only the first increment from each process is applied, since many
copies of the model handler can share this manager within a process.
"""
with self._max_models_lock:
with self._lock:
if process_id is not None:
if process_id in self._incremented_process_ids:
return
Expand All @@ -767,18 +787,33 @@ def update_model_handler(self, key: str, model_path: str, previous_key: str):
we will want to keep both the old and new models to serve different
cohorts. In that case, the keys should be different.
"""
if self._key_to_last_update[key] == model_path:
return
self._key_to_last_update[key] = model_path
if key not in self._mh_map:
self._mh_map[key] = deepcopy(self._mh_map[previous_key])
self._mh_map[key].update_model_path(model_path)
if key in self._tag_map:
tag_to_remove = self._tag_map[key]
shared_handle, model_to_remove = self._proxy_map[tag_to_remove]
shared_handle.release(model_to_remove)
del self._tag_map[key]
del self._proxy_map[tag_to_remove]
with self._lock:
if self._key_to_last_update[key] == model_path:
return
self._key_to_last_update[key] = model_path
if key not in self._mh_map:
self._mh_map[key] = deepcopy(self._mh_map[previous_key])
self._mh_map[key].update_model_path(model_path)
old_model = None
if key in self._tag_map:
old_model = self._pop_proxy(self._tag_map.pop(key))
self._release_proxy(old_model)

def _pop_proxy(self, tag: str):
"""Removes the model for a tag that was removed from _tag_map.

Must be called while holding self._lock. Returns the model to pass to
_release_proxy() once the lock is released, or None if there is none.
"""
# A model that is still loading has no _proxy_map entry yet. load() releases
# it when it finishes, because its tag is no longer in _tag_map.
return self._proxy_map.pop(tag, None)

@staticmethod
def _release_proxy(proxy):
if proxy is not None:
shared_handle, model = proxy
shared_handle.release(model)


# Use a dataclass instead of named tuple because NamedTuples and generics don't
Expand Down
140 changes: 140 additions & 0 deletions sdks/python/apache_beam/ml/inference/base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,27 @@ def run_inference(self, batch, model, inference_args=None):
return [model.predict(x) for x in batch]


class BlockingLoadModelHandler(base.ModelHandler[int, int, FakeModel]):
"""load_model() waits until finish_load is set, to test in-flight loads."""
def __init__(self):
self.load_count = 0
self.load_started = threading.Event()
self.finish_load = threading.Event()

def load_model(self):
self.load_count += 1
self.load_started.set()
if not self.finish_load.wait(timeout=60):
raise TimeoutError('finish_load was never set')
return FakeModel()

def run_inference(self, batch, model, inference_args=None):
return [model.predict(x) for x in batch]

def update_model_path(self, model_path: Optional[str] = None):
pass


class FakeModelHandler(base.ModelHandler[int, int, FakeModel]):
def __init__(
self,
Expand Down Expand Up @@ -2189,6 +2210,125 @@ def test_model_handler_manager_increments_once_per_process(self):
mm.load('key1')
self.assertEqual(['key3', 'key1'], list(mm._tag_map.keys()))

def test_model_handler_manager_retries_failed_load(self):
# state=100 makes FakeStatefulModel raise when the model is loaded.
mh1 = FakeModelHandler(state=100)
mh2 = FakeModelHandler(state=2)
mm = base._ModelHandlerManager(mh_map={'key1': mh1, 'key2': mh2})
mm.increment_max_models(1)
with self.assertRaisesRegex(Exception, 'Oh no'):
mm.load('key1')
self.assertEqual([], list(mm._tag_map.keys()))

# The next load of key1 loads the model again and keeps it.
mh1._state = 1
stats = mm.load('key1')
self.assertIsNotNone(stats.load_latency)
# Use bad_mh's load function to make sure the model is already stored.
bad_mh = FakeModelHandler(state=100)
model1 = multi_process_shared.MultiProcessShared(
bad_mh.load_model, tag=stats.model_tag).acquire()
self.assertEqual(1, model1.predict(10))
self.assertIsNone(mm.load('key1').load_latency)

# Evicting key1 to load key2 works.
mm.load('key2')
self.assertEqual(['key2'], list(mm._tag_map.keys()))

def test_model_handler_manager_unknown_key_leaves_no_tag(self):
mm = base._ModelHandlerManager(mh_map={'key1': FakeModelHandler(state=1)})
with self.assertRaises(KeyError):
mm.load('missing')
self.assertEqual([], list(mm._tag_map.keys()))

def test_model_handler_manager_with_max_models_zero_keeps_new_model(self):
mm = base._ModelHandlerManager(
mh_map={
'key1': FakeModelHandler(state=1),
'key2': FakeModelHandler(state=2)
})
mm.increment_max_models(0)
tag1 = mm.load('key1').model_tag
self.assertEqual({'key1': tag1}, dict(mm._tag_map))
self.assertEqual([tag1], list(mm._proxy_map.keys()))
tag2 = mm.load('key2').model_tag
self.assertEqual({'key2': tag2}, dict(mm._tag_map))
self.assertEqual([tag2], list(mm._proxy_map.keys()))

def _start_blocking_load(self, mm, key):
"""Starts mm.load(key) on a thread and waits until load_model runs."""
mh = mm._mh_map[key]
results = []
thread = threading.Thread(target=lambda: results.append(mm.load(key)))
# Unblock the load even if the test fails, so the thread doesn't wait for
# the full timeout.
self.addCleanup(mh.finish_load.set)
thread.start()
Comment thread
damccorm marked this conversation as resolved.
Resolved
self.assertTrue(mh.load_started.wait(timeout=60))
return thread, results

def test_model_handler_manager_concurrent_loads_share_model(self):
mh = BlockingLoadModelHandler()
mm = base._ModelHandlerManager(mh_map={'key1': mh})
thread, results = self._start_blocking_load(mm, 'key1')

# A second load of the same key while the first one is still loading
# returns the same tag instead of loading another copy of the model.
tag = mm.load('key1').model_tag

mh.finish_load.set()
thread.join(timeout=60)
self.assertEqual(tag, results[0].model_tag)
self.assertEqual(1, mh.load_count)
self.assertEqual([tag], list(mm._proxy_map.keys()))

def test_model_handler_manager_evicts_model_that_is_loading(self):
mh1 = BlockingLoadModelHandler()
mm = base._ModelHandlerManager(
mh_map={
'key1': mh1, 'key2': FakeModelHandler(state=2)
})
mm.increment_max_models(1)
thread1, results1 = self._start_blocking_load(mm, 'key1')

# Loading key2 evicts key1 while key1's model is still loading. key2's own
# load then waits for key1's load, since models are created one at a time.
results2 = []
thread2 = threading.Thread(target=lambda: results2.append(mm.load('key2')))
thread2.start()
deadline = time.time() + 60
while 'key1' in mm._tag_map and time.time() < deadline:
time.sleep(0.01)
self.assertNotIn('key1', mm._tag_map)

mh1.finish_load.set()
thread1.join(timeout=60)
thread2.join(timeout=60)
self.assertEqual(1, len(results1))
self.assertEqual(1, len(results2))
tag2 = results2[0].model_tag
# key1's model is released when its load finishes, instead of being kept
# without an entry in _tag_map.
self.assertEqual({'key2': tag2}, dict(mm._tag_map))
self.assertEqual([tag2], list(mm._proxy_map.keys()))

def test_model_handler_manager_updates_model_that_is_loading(self):
mh1 = BlockingLoadModelHandler()
mm = base._ModelHandlerManager(mh_map={'key1': mh1})
thread, _ = self._start_blocking_load(mm, 'key1')

mm.update_model_handler('key1', 'new/path', 'key1')
self.assertEqual({}, dict(mm._tag_map))

mh1.finish_load.set()
thread.join(timeout=60)
self.assertEqual({}, dict(mm._tag_map))
self.assertEqual({}, mm._proxy_map)

# The next load uses the updated model handler.
mm.load('key1')
self.assertEqual(2, mh1.load_count)

def test_keyed_model_handler_max_models_hint_with_handler_copies(self):
mhs = [
base.KeyModelMapping([k],
Expand Down
Loading