Skip to content
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

[BEAM-5878] support DoFns with Keyword-only arguments #9237

Merged
merged 6 commits into from
Sep 3, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions sdks/python/apache_beam/internal/pickler.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,32 @@ def _reject_generators(unused_pickler, unused_obj):

dill.dill.Pickler.dispatch[types.GeneratorType] = _reject_generators

if sys.version_info[0] > 2:
# Monkey patch for dill._dill.Pickler to pickle functions
tvalentyn marked this conversation as resolved.
Show resolved Hide resolved
# with keyword-only args
_create_function = dill.dill._create_function

def _create_function_has_kwdefaults(fcode, fglobals, fname=None,
fdefaults=None, fclosure=None, fdict=None,
fkwdefaults=None):
func = _create_function(fcode, fglobals, fname, fdefaults, fclosure, fdict)
if fkwdefaults is not None:
tvalentyn marked this conversation as resolved.
Show resolved Hide resolved
func.__kwdefaults__ = fkwdefaults
return func

def new_save_reduce(self, func, args, state=None, listitems=None,
Copy link
Contributor

@tvalentyn tvalentyn Aug 26, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use a more generic signature of new_save_reduce, for example def new_save_reduce(self, func, args, **kwargs)? The problem is that we assume a particular version of the API for pickle.save_reduce here, and we can see that it will change in Python 3.8, see https://github.com/python/cpython/blob/c75f0e5bdee3cfaba9fd5b3a8549dec0aba01ebe/Lib/pickle.py#L619.

I think with a generic definition of new_save_reduce we can still update args list , and pass **kwargs to pickler.save_reduce.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quite so. I'll work on.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @lazylynx . It would be nice to add this to next Beam release that is not be cut in ~2 weeks. Thanks for your help.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tvalentyn Sorry for late. PTAL

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries, and thanks a lot, @lazylynx ! The change looks good to me. I'm going to re-run a few tests to make sure that they still pass with this change combined with a recent upgrade of dill version (#9419).

dictitems=None, obj=None):
pickler = super(dill.dill.Pickler, self)
if func is _create_function and \
tvalentyn marked this conversation as resolved.
Show resolved Hide resolved
getattr(obj, '__kwdefaults__', None) is not None:
pickler.save_reduce(func=_create_function_has_kwdefaults,
args=args + (getattr(obj, '__kwdefaults__', None),),
state=state, listitems=listitems, dictitems=dictitems,
obj=obj)
else:
pickler.save_reduce(func, args, state, listitems, dictitems, obj)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would not this call back into new_save_reduce since you patched it in L164?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This call back calls save_reduce function of pickle.Pickler, super class of dill.dill.Pickler.
So new_save_reduce would not be called.


dill._dill.Pickler.save_reduce = new_save_reduce

# This if guards against dill not being full initialized when generating docs.
if 'save_module' in dir(dill.dill):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#
# 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.
#

"""Unit tests for side inputs."""

from __future__ import absolute_import

import logging
import sys
import unittest

import apache_beam as beam # pylint: disable=unused-import
from apache_beam.testing.test_pipeline import TestPipeline # pylint: disable=unused-import
from apache_beam.testing.util import assert_that # pylint: disable=unused-import
from apache_beam.testing.util import equal_to # pylint: disable=unused-import

IS_PYTHON_2 = sys.version_info[0] == 2


# pylint: disable=exec-used
@unittest.skipIf(IS_PYTHON_2, 'test only in python 3 with kwonly args')
tvalentyn marked this conversation as resolved.
Show resolved Hide resolved
class KeywordOnlyArgsTests(unittest.TestCase):
# TODO(BEAM-7836): using `exec` as work around must be avoided

# Enable nose tests running in parallel
_multiprocess_can_split_ = True

def test_side_input_keyword_only_args(self):
exec('''
pipeline = TestPipeline()

def sort_with_side_inputs(x, *s, reverse=False):
for y in s:
yield sorted([x] + y, reverse=reverse)

pcol = pipeline | 'start' >> beam.Create([1, 2])
side = pipeline | 'side' >> beam.Create([3, 4]) # 2 values in side input.
result1 = pcol | 'compute1' >> beam.FlatMap(
sort_with_side_inputs,
beam.pvalue.AsList(side), reverse=True)
assert_that(result1, equal_to([[4,3,1], [4,3,2]]), label='assert1')

result2 = pcol | 'compute2' >> beam.FlatMap(
sort_with_side_inputs,
beam.pvalue.AsList(side))
assert_that(result2, equal_to([[1,3,4], [2,3,4]]), label='assert2')

result3 = pcol | 'compute3' >> beam.FlatMap(
sort_with_side_inputs)
assert_that(result3, equal_to([]), label='assert3')

result4 = pcol | 'compute4' >> beam.FlatMap(
sort_with_side_inputs, reverse=True)
assert_that(result4, equal_to([]), label='assert4')

pipeline.run()''')

def test_combine_keyword_only_args(self):
exec('''
pipeline = TestPipeline()

def bounded_sum(values, *s, bound=500):
return min(sum(values) + sum(s), bound)

pcoll = pipeline | 'start' >> beam.Create([6, 3, 1])
result1 = pcoll | 'sum1' >> beam.CombineGlobally(bounded_sum, 5, 8, bound=20)
result2 = pcoll | 'sum2' >> beam.CombineGlobally(bounded_sum, 5, 8)
result3 = pcoll | 'sum3' >> beam.CombineGlobally(bounded_sum)
result4 = pcoll | 'sum4' >> beam.CombineGlobally(bounded_sum, bound=5)

assert_that(result1, equal_to([20]), label='assert1')
assert_that(result2, equal_to([49]), label='assert2')
assert_that(result3, equal_to([10]), label='assert3')
assert_that(result4, equal_to([5]), label='assert4')

pipeline.run()''')

def test_do_fn_keyword_only_args(self):
exec('''
pipeline = TestPipeline()

class MyDoFn(beam.DoFn):
def process(self, element, *s, bound=500):
return [min(sum(s) + element, bound)]

pcoll = pipeline | 'start' >> beam.Create([6, 3, 1])
result1 = pcoll | 'sum1' >> beam.ParDo(MyDoFn(), 5, 8, bound=15)
result2 = pcoll | 'sum2' >> beam.ParDo(MyDoFn(), 5, 8)
result3 = pcoll | 'sum3' >> beam.ParDo(MyDoFn())
result4 = pcoll | 'sum4' >> beam.ParDo(MyDoFn(), bound=5)

assert_that(result1, equal_to([15,15,14]), label='assert1')
assert_that(result2, equal_to([19,16,14]), label='assert2')
assert_that(result3, equal_to([6,3,1]), label='assert3')
assert_that(result4, equal_to([5,3,1]), label='assert4')
pipeline.run()''')


if __name__ == '__main__':
logging.getLogger().setLevel(logging.DEBUG)
unittest.main()