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 @@ -162,6 +162,7 @@

## Bugfixes

* (Python) Fixed RunInference failing with `TypeError: cannot create weak reference to 'dict' object` when `ModelHandler.load_model()` returns a model that can't be weakly referenced, such as a `dict` or `list` ([#41351](https://github.com/apache/beam/issues/41351)).
* (Java) Flink `OrderedListState` now preserves multiple values with the same timestamp when reading state or clearing a different timestamp range ([#39782](https://github.com/apache/beam/issues/39782)).
* (Python) Fixed `DecimalCoder` silently rounding decimals with more than 28 significant digits ([#41706](https://github.com/apache/beam/issues/41706)).
* (Python) Fixed `WriteToBigQuery` rejecting string schemas that include spaces around field names or types, for example `name: STRING` ([#25704](https://github.com/apache/beam/issues/25704)).
Expand Down
33 changes: 32 additions & 1 deletion sdks/python/apache_beam/ml/inference/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import threading
import time
import uuid
import weakref
from abc import ABC
from abc import abstractmethod
from collections import OrderedDict
Expand Down Expand Up @@ -2089,6 +2090,17 @@ def __call__(self):
return unique_tag


class _WeakRefableModelHolder():
"""Holds a model that can't be weakly referenced, such as a dict or list.

shared.Shared caches objects through weak references, which several
built-in types don't support, so models of those types are cached inside
this holder instead.
"""
def __init__(self, model: Any):
self.model = model


class _SharedModelWrapper():
"""A router class to map incoming calls to the correct model.

Expand Down Expand Up @@ -2181,6 +2193,10 @@ def __init__(
"""
self._model_handler = model_handler
self._shared_model_handle = shared.Shared()
# Strong reference to the object cached in _shared_model_handle, which is
# a _WeakRefableModelHolder rather than the model itself for models that
# can't be weakly referenced.
self._shared_model = None
self._clock = clock
self._model = None
self._metrics_namespace = metrics_namespace
Expand Down Expand Up @@ -2258,7 +2274,22 @@ def load():
spawn_process=True).acquire())
model_wrapper = _SharedModelWrapper(models, self._cur_tag)
else:
model = self._shared_model_handle.acquire(load, tag=self._cur_tag)

def load_weakrefable():
model = load()
if model is None:
return None
try:
weakref.ref(model)
except TypeError:
return _WeakRefableModelHolder(model)
return model

self._shared_model = self._shared_model_handle.acquire(
load_weakrefable, tag=self._cur_tag)
model = self._shared_model
if isinstance(model, _WeakRefableModelHolder):
model = model.model
model_wrapper = _SharedModelWrapper([model], self._cur_tag)
# since shared_model_handle is shared across threads, the model path
# might not get updated in the model handler
Expand Down
40 changes: 40 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,20 @@ def run_inference(self, batch, model, inference_args=None):
return [model.predict(x) for x in batch]


class DictModelHandler(base.ModelHandler[int, int, dict[str, int]]):
"""Returns a dict, which can't be weakly referenced, from load_model()."""
def __init__(self, key: Optional[str] = None):
self._key = key

def load_model(self):
if self._key is not None:
_LOAD_COUNTS[self._key] = _LOAD_COUNTS.get(self._key, 0) + 1
return {'increment': 1}

def run_inference(self, batch, model, inference_args=None):
return [x + model['increment'] 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):
Expand Down Expand Up @@ -424,6 +438,14 @@ def test_run_inference_impl_simple_examples(self):
actual = pcoll | base.RunInference(FakeModelHandler())
assert_that(actual, equal_to(expected), label='assert:inferences')

def test_run_inference_impl_dict_model(self):
with TestPipeline() as pipeline:
examples = [1, 5, 3, 10]
expected = [example + 1 for example in examples]
pcoll = pipeline | 'start' >> beam.Create(examples)
actual = pcoll | base.RunInference(DictModelHandler())
assert_that(actual, equal_to(expected), label='assert:inferences')

def test_run_inference_impl_simple_examples_multi_process_shared(self):
with TestPipeline() as pipeline:
examples = [1, 5, 3, 10]
Expand Down Expand Up @@ -2494,6 +2516,24 @@ def test_new_dofn_instances_reuse_previously_loaded_models(self):

self.assertEqual(1, _LOAD_COUNTS[model_tag])

def test_new_dofn_instances_reuse_previously_loaded_dict_models(self):
model_tag = 'tag3' + uuid.uuid4().hex
handler = DictModelHandler(model_tag)
dofn = base._RunInferenceDoFn(
handler, clock=FakeClock(), metrics_namespace=None, model_tag=model_tag)
serialized_dofn = pickle.dumps(dofn)

dofn_instance = pickle.loads(serialized_dofn)
dofn_instance.setup()
del dofn_instance
gc.collect()

dofn_instance = pickle.loads(serialized_dofn)
dofn_instance.setup()

self.assertEqual(1, _LOAD_COUNTS[model_tag])
self.assertEqual({'increment': 1}, dofn_instance._model.next_model())

def test_model_status_provides_valid_garbage_collection(self):
ms = base._ModelStatus(True)

Expand Down
Loading