-
Notifications
You must be signed in to change notification settings - Fork 4.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add sideinputs to the RunInference Transform #25200
Merged
Merged
Changes from 46 commits
Commits
Show all changes
54 commits
Select commit
Hold shift + click to select a range
e54a2de
Add model pcoll param to the RunInference Ptransform
AnandInguva 443120a
Add sklearn side input example
AnandInguva 50b58b1
Add ModeMetadata and some refactoring
AnandInguva 3cb7074
refactor _convert_to_result and add it to the utils.py
AnandInguva f614a3d
Add tag to the RunInference DoFn
AnandInguva 43b5ca6
Add enable_side_input_loading flag
AnandInguva c42b903
Add helper functions
AnandInguva e2c2833
Add doc string, refactor utils code
AnandInguva f4a6c2b
Fix pytorch inference tests
AnandInguva 530f61f
Fix up sklearn inference
AnandInguva 9bd8d8f
Remove logging
AnandInguva 676600a
Add thread Lock when there is an update to side input
AnandInguva 0a2a56e
Check if side input is EmptySideInput
AnandInguva 7a1ed15
Add unit test for side input loading
AnandInguva eae1837
Remove examples
AnandInguva af19536
Add log when side input path is updated
AnandInguva 3d0821e
Add test to Dataflow
AnandInguva fe434df
Refactor side input loading code
AnandInguva 2a3e6a4
Add documentation, changelog
AnandInguva dd6d494
Add Singleton view doc
AnandInguva 037c80a
Fix whitespace, tests
AnandInguva f9a61a1
fix weird spacing
AnandInguva d2edaa9
Remove beam website udpate
AnandInguva 73ed494
Revert "fix weird spacing"
AnandInguva ae91ffe
Add WatchFilePattern transform
AnandInguva b796560
undo changes to beam wesbite
AnandInguva ca178a2
Pass side inputs only in streaming mode
AnandInguva 0d96c77
Revert "Add WatchFilePattern transform"
AnandInguva 2d97fdb
Add lines to website page
AnandInguva cf3893f
Add test
AnandInguva 9295dce
Add unit test to catch --streaming flag and Singleton SideInput
AnandInguva 3ce25f8
Addressing PR comments
AnandInguva 912e36f
Add logic to detect windows on side inputs
AnandInguva 0191cdd
Add more tests
AnandInguva a860b98
Remove redundant code
AnandInguva fba66b3
Update test
AnandInguva babcd24
Fix lint
AnandInguva 016bbc5
Add postcommit markers.
AnandInguva 88cb09d
Remove `and`
AnandInguva 53f5a7c
fixup lint
AnandInguva d1abcc0
Modify message
AnandInguva b2c40db
Add check for default model
AnandInguva 60b33fa
Update message
AnandInguva 036f321
Add validates runner
AnandInguva 5b40d1f
Fix test
AnandInguva 0b58f10
Add PipelineVisitor for RunInference during construction time
AnandInguva bcdb871
Address comments based on PR
AnandInguva e6f8eaa
Remove restriction on the side inputs
AnandInguva ec3ca9b
Remove/add tests
AnandInguva 6d07b6f
Modify logging
AnandInguva 25c662c
Add tests
AnandInguva f7ab2d7
Merge branch 'master' into model-updates-api
damccorm 0d325fe
Add 2.46.0 change log
AnandInguva 637d3c3
fix typo
AnandInguva File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
168 changes: 168 additions & 0 deletions
168
sdks/python/apache_beam/examples/inference/run_inference_side_inputs.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
|
||
""" | ||
Used for internal testing. No backwards compatibility. | ||
""" | ||
|
||
import argparse | ||
import logging | ||
import time | ||
from typing import Iterable | ||
from typing import Optional | ||
from typing import Sequence | ||
|
||
import apache_beam as beam | ||
from apache_beam.ml.inference import base | ||
from apache_beam.options.pipeline_options import PipelineOptions | ||
from apache_beam.options.pipeline_options import SetupOptions | ||
from apache_beam.transforms import trigger | ||
from apache_beam.transforms import window | ||
from apache_beam.transforms.periodicsequence import PeriodicImpulse | ||
from apache_beam.transforms.userstate import CombiningValueStateSpec | ||
|
||
|
||
# create some fake models which returns different inference results. | ||
class FakeModelDefault: | ||
def predict(self, example: int) -> int: | ||
return example | ||
|
||
|
||
class FakeModelAdd(FakeModelDefault): | ||
def predict(self, example: int) -> int: | ||
return example + 1 | ||
|
||
|
||
class FakeModelSub(FakeModelDefault): | ||
def predict(self, example: int) -> int: | ||
return example - 1 | ||
|
||
|
||
class FakeModelHandlerReturnsPredictionResult( | ||
base.ModelHandler[int, base.PredictionResult, FakeModelDefault]): | ||
def __init__(self, clock=None, model_id='model_default'): | ||
self.model_id = model_id | ||
self._fake_clock = clock | ||
|
||
def load_model(self): | ||
if self._fake_clock: | ||
self._fake_clock.current_time_ns += 500_000_000 # 500ms | ||
if self.model_id == 'model_add.pkl': | ||
return FakeModelAdd() | ||
elif self.model_id == 'model_sub.pkl': | ||
return FakeModelSub() | ||
return FakeModelDefault() | ||
|
||
def run_inference( | ||
self, | ||
batch: Sequence[int], | ||
model: FakeModelDefault, | ||
inference_args=None) -> Iterable[base.PredictionResult]: | ||
for example in batch: | ||
yield base.PredictionResult( | ||
model_id=self.model_id, | ||
example=example, | ||
inference=model.predict(example)) | ||
|
||
def update_model_path(self, model_path: Optional[str] = None): | ||
self.model_id = model_path if model_path else self.model_id | ||
|
||
|
||
def run(argv=None, save_main_session=True): | ||
parser = argparse.ArgumentParser() | ||
first_ts = time.time() | ||
side_input_interval = 60 | ||
main_input_interval = 20 | ||
# give some time for dataflow to start. | ||
last_ts = first_ts + 1200 | ||
mid_ts = (first_ts + last_ts) / 2 | ||
|
||
_, pipeline_args = parser.parse_known_args(argv) | ||
options = PipelineOptions(pipeline_args) | ||
options.view_as(SetupOptions).save_main_session = save_main_session | ||
|
||
test_pipeline = beam.Pipeline(options=options) | ||
|
||
class GetModel(beam.DoFn): | ||
def process(self, element) -> Iterable[base.ModelMetdata]: | ||
if time.time() > mid_ts: | ||
yield base.ModelMetdata( | ||
model_id='model_add.pkl', model_name='model_add') | ||
else: | ||
yield base.ModelMetdata( | ||
model_id='model_sub.pkl', model_name='model_sub') | ||
|
||
class _EmitSingletonSideInput(beam.DoFn): | ||
COUNT_STATE = CombiningValueStateSpec('count', combine_fn=sum) | ||
|
||
def process(self, element, count_state=beam.DoFn.StateParam(COUNT_STATE)): | ||
_, path = element | ||
counter = count_state.read() | ||
if counter == 0: | ||
count_state.add(1) | ||
yield path | ||
|
||
def validate_prediction_result(x: base.PredictionResult): | ||
model_id = x.model_id | ||
if model_id == 'model_sub.pkl': | ||
assert (x.example == 1 and x.inference == 0) | ||
|
||
if model_id == 'model_add.pkl': | ||
assert (x.example == 1 and x.inference == 2) | ||
AnandInguva marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if model_id == 'model_default': | ||
assert (x.example == 1 and x.inference == 1) | ||
|
||
side_input = ( | ||
test_pipeline | ||
| "SideInputPColl" >> PeriodicImpulse( | ||
first_ts, last_ts, fire_interval=side_input_interval) | ||
| "GetModelId" >> beam.ParDo(GetModel()) | ||
| "AttachKey" >> beam.Map(lambda x: (x, x)) | ||
# due to periodic impulse, which has a start timestamp before | ||
# Dataflow pipeline process data, it can trigger in multiple | ||
# firings, causing an Iterable instead of singleton. So, using | ||
# the _EmitSingletonSideInput DoFn will ensure unique path will be | ||
# fired only once. | ||
| "GetSingleton" >> beam.ParDo(_EmitSingletonSideInput()) | ||
| "ApplySideInputWindow" >> beam.WindowInto( | ||
window.GlobalWindows(), | ||
trigger=trigger.Repeatedly(trigger.AfterProcessingTime(1)), | ||
accumulation_mode=trigger.AccumulationMode.DISCARDING)) | ||
|
||
model_handler = FakeModelHandlerReturnsPredictionResult() | ||
inference_pcoll = ( | ||
test_pipeline | ||
| "MainInputPColl" >> PeriodicImpulse( | ||
first_ts, | ||
last_ts, | ||
fire_interval=main_input_interval, | ||
apply_windowing=True) | ||
| beam.Map(lambda x: 1) | ||
| base.RunInference( | ||
model_handler=model_handler, model_metadata_pcoll=side_input)) | ||
|
||
_ = inference_pcoll | "AssertPredictionResult" >> beam.Map( | ||
validate_prediction_result) | ||
|
||
_ = inference_pcoll | "Logging" >> beam.Map(logging.info) | ||
|
||
test_pipeline.run().wait_until_finish() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. changed it. thanks |
||
|
||
|
||
if __name__ == '__main__': | ||
run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wait, actually this won't be released in 2.45 - could you please create a new section for 2.46? (same thing Luke did here - 8ec0568#diff-d975bf659606195d2165918f93e1cf680ef68ea3c9cab994f033705fea8238b2)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah yes, thanks for catching it.