concurrency.py 15.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed 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.

15 16
from __future__ import print_function

17
from .layers.control_flow import BlockGuard, equal
18
from .framework import Operator
19 20 21
from .layer_helper import LayerHelper, unique_name
from .layers import fill_constant
from . import core
T
Thuan Nguyen 已提交
22

23
__all__ = [
W
Wu Yi 已提交
24
    'make_channel', 'channel_send', 'channel_recv', 'channel_close', 'Select'
25 26 27 28 29 30 31 32 33 34 35 36 37 38
]


class Go(BlockGuard):
    def __init__(self, name=None):
        self.helper = LayerHelper("go", name=name)
        super(Go, self).__init__(self.helper.main_program)

    def __enter__(self):
        super(Go, self).__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            return False
W
Wu Yi 已提交
39
        self._construct_go_op()
40 41
        return super(Go, self).__exit__(exc_type, exc_val, exc_tb)

W
Wu Yi 已提交
42
    def _construct_go_op(self):
43 44 45 46 47
        main_program = self.helper.main_program
        go_block = main_program.current_block()
        parent_block = main_program.block(main_program.current_block()
                                          .parent_idx)

T
Thuan Nguyen 已提交
48
        inner_outputs = set()
49 50 51 52 53 54
        x_name_list = set()
        for op in go_block.ops:
            # Iterate over all operators, get all the inputs
            # and add as input to the Go operator.
            for iname in op.input_names:
                for in_var_name in op.input(iname):
T
Thuan Nguyen 已提交
55 56
                    if in_var_name not in inner_outputs:
                        x_name_list.add(in_var_name)
57 58 59

            for oname in op.output_names:
                for out_var_name in op.output(oname):
T
Thuan Nguyen 已提交
60 61 62 63 64 65 66 67 68
                    inner_outputs.add(out_var_name)

        # Iterate over all operators , get all the outputs
        # add to the output list of Go operator only if
        # they exist in the parent block.
        out_vars = []
        for inner_out_name in inner_outputs:
            if inner_out_name in parent_block.vars:
                out_vars.append(parent_block.var(inner_out_name))
69 70 71

        parent_block.append_op(
            type='go',
T
Thuan Nguyen 已提交
72
            inputs={
W
Wu Yi 已提交
73 74 75 76
                'X': [
                    parent_block._var_recursive(x_name)
                    for x_name in x_name_list
                ]
T
Thuan Nguyen 已提交
77 78
            },
            outputs={},
79 80 81
            attrs={'sub_block': go_block})


82 83 84 85 86 87
class SelectCase(object):
    DEFAULT = 0
    SEND = 1
    RECEIVE = 2

    def __init__(self,
88
                 select,
89 90 91 92
                 case_idx,
                 case_to_execute,
                 channel_action_fn=None,
                 channel=None,
93 94 95
                 value=None,
                 is_copy=False):
        self.select = select
96 97 98 99 100 101 102 103 104 105 106 107
        self.helper = LayerHelper('conditional_block')
        self.main_program = self.helper.main_program
        self.is_scalar_condition = True

        self.case_to_execute = case_to_execute
        self.idx = case_idx

        # Since we aren't going to use the `channel_send` or `channel_recv`
        # functions directly, we just need to capture the name.
        self.action = (self.SEND
                       if channel_action_fn.__name__ == ('channel_send') else
                       self.RECEIVE) if channel_action_fn else self.DEFAULT
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

        X = value
        if self.action == self.SEND and is_copy:
            # We create of copy of the data we want to send
            copied_X = self.select.parent_block.create_var(
                name=unique_name.generate(value.name + '_copy'),
                type=value.type,
                dtype=value.dtype,
                shape=value.shape,
                lod_level=value.lod_level,
                capacity=value.capacity
                if hasattr(value, 'capacity') else None, )

            self.select.parent_block.append_op(
                type="assign", inputs={"X": value}, outputs={"Out": copied_X})
            X = copied_X

        self.value = X
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        self.channel = channel

    def __enter__(self):
        self.block = self.main_program.create_block()

    def construct_op(self):
        main_program = self.helper.main_program
        cases_block = main_program.current_block()

        inner_outputs = set()
        input_set = set()
        params = set()

        for op in self.block.ops:
            # Iterate over all operators, get all the inputs
            # and add as input to the SelectCase operator.
            for iname in op.input_names:
                for in_var_name in op.input(iname):
                    if in_var_name not in inner_outputs:
                        input_set.add(in_var_name)

            for oname in op.output_names:
                for out_var_name in op.output(oname):
                    inner_outputs.add(out_var_name)

        param_list = [
            cases_block.var(each_name) for each_name in params
            if each_name not in input_set
        ]

        # Iterate over all operators, get all the outputs
        # add to the output list of SelectCase operator only if
        # they exist in the parent block.
        out_vars = []
        for inner_out_name in inner_outputs:
            if inner_out_name in cases_block.vars:
                out_vars.append(cases_block.var(inner_out_name))

        # First, create an op that will determine whether or not this is the
        # conditional variable to execute.
        should_execute_block = equal(
            fill_constant(
                shape=[1], dtype=core.VarDesc.VarType.INT32, value=self.idx),
            self.case_to_execute)

        step_scope = cases_block.create_var(
            type=core.VarDesc.VarType.STEP_SCOPES)

        cases_block.append_op(
            type='conditional_block',
            inputs={'X': [should_execute_block],
                    'Params': param_list},
            outputs={'Out': out_vars,
                     'Scope': [step_scope]},
            attrs={
                'sub_block': self.block,
                'is_scalar_condition': self.is_scalar_condition
            })

        return '%s,%s,%s,%s' % (self.idx, self.action, self.channel.name
                                if self.channel else '', self.value.name
                                if self.value else '')

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.main_program.rollback()
        if exc_type is not None:
            return False  # re-raise exception
        return True


class Select(BlockGuard):
    def __init__(self, name=None):
        self.helper = LayerHelper('select', name=name)
199
        self.parent_block = self.helper.main_program.current_block()
200 201 202 203 204 205 206 207 208 209
        self.cases = []

        super(Select, self).__init__(self.helper.main_program)
        self.case_to_execute = fill_constant(
            shape=[1], dtype=core.VarDesc.VarType.INT32, value=-1)

    def __enter__(self):
        super(Select, self).__enter__()
        return self

210
    def case(self, channel_action_fn, channel, value, is_copy=False):
211 212
        """Create a new block for this condition.
        """
213 214 215
        select_case = SelectCase(self,
                                 len(self.cases), self.case_to_execute,
                                 channel_action_fn, channel, value, is_copy)
216 217 218 219 220 221 222 223

        self.cases.append(select_case)

        return select_case

    def default(self):
        """Create a default case block for this condition.
        """
224
        default_case = SelectCase(self, len(self.cases), self.case_to_execute)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

        self.cases.append(default_case)

        return default_case

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            return False

        # Create a select op and another block to wrap its
        # case blocks.
        select_block = self.helper.main_program.current_block()
        parent_block = self.helper.main_program.block(select_block.parent_idx)

        # Construct each case op, inside the newly created select block.
        serialized_cases = []
        for case in self.cases:
            serialized_cases.append(case.construct_op())

        intermediate = set()
        params = set()

        for case_block in select_block.ops:
            if case_block.attrs and 'sub_block' in case_block.attrs:
                for each_op in case_block.attrs['sub_block'].ops:
                    assert isinstance(each_op, Operator)
                    for iname in each_op.input_names:
                        for in_var_name in each_op.input(iname):
                            if in_var_name not in intermediate:
                                params.add(in_var_name)

                    for oname in each_op.output_names:
                        for out_var_name in each_op.output(oname):
                            intermediate.add(out_var_name)

        out_list = [
            parent_block.var(var_name) for var_name in parent_block.vars
            if var_name in intermediate
        ]

W
Wu Yi 已提交
265
        X = [select_block._var_recursive(x_name) for x_name in params]
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

        # Needs to be used by `equal` inside the cases block.
        X.append(self.case_to_execute)

        # Construct the select op.
        parent_block.append_op(
            type='select',
            inputs={'X': X,
                    'case_to_execute': self.case_to_execute},
            attrs={'sub_block': select_block,
                   'cases': serialized_cases},
            outputs={'Out': out_list})

        return super(Select, self).__exit__(exc_type, exc_val, exc_tb)


282 283 284 285 286 287
def make_channel(dtype, capacity=0):
    """
    Helps implementation of a concurrent program by creating a "channel" of
    a defined data type. Channels allow for the passing of data in
    concurrent scenarios - such as when using threads to divide computation.
    Channels can be used to "send" and "receive" such data concurrently.
288

289 290 291
    There are two kinds of channels: unbuffered and buffered. Unbuffered
    channels have no capacity - and thus, block on send and only unblock only
    once what they have sent has been received.
292

293 294 295 296 297 298 299
    On the other hand, buffered channels are initialized with a capacity -
    and do not block on sends.

    Use this method in combination with `channel_send`, `channel_recv`,
    `channel_close`, and `Go` to design a concurrent Paddle program.

    Args:
T
Thuan Nguyen 已提交
300 301
        dtype (ParamAttr|string): Data type of the data sent in the channel.
        This data type should be the string name of a numpy data type.
302 303 304 305 306 307 308 309 310
        capacity (ParamAttr|int): Size of the channel. Defaults to 0 for
        to create an unbuffered channel.

    Returns:
        Variable: The channel variable that can be used to send an receive data
                  of the defined dtype.

    Examples:
        .. code-block:: python
311

312 313 314 315 316 317
          ch = fluid.make_channel(dtype='int32', capacity=10)
          ...
          # Code to execute in a Go block, which receives the channel data.
          fluid.channel_send(ch, 100)
          fluid.channel_close(ch)
    """
T
Thuan Nguyen 已提交
318
    helper = LayerHelper('channel_create', **locals())
319 320
    main_program = helper.main_program
    make_channel_block = main_program.current_block()
321

322 323 324
    # Make a channel variable (using the channel data type) and make sure it
    # persists into the global scope.
    channel = helper.create_variable(
T
Thuan Nguyen 已提交
325 326 327
        name=unique_name.generate('channel'),
        type=core.VarDesc.VarType.CHANNEL,
        persistable=True)
328 329 330 331 332 333 334

    create_channel_op = make_channel_block.append_op(
        type="channel_create",
        outputs={"Out": channel},
        attrs={"data_type": dtype,
               "capacity": capacity})

T
Thuan Nguyen 已提交
335
    return channel
336 337


338
def channel_send(channel, value, is_copy=False):
339 340 341 342 343 344 345 346
    """
    Sends a value through a channel variable. Used by an unbuffered or buffered
    channel to pass data from within or to a concurrent Go block, where
    `channel_recv` to used to get the passed value.

    Args:
        channel (Variable|Channel): Channel variable created using
        `make_channel`.
T
Thuan Nguyen 已提交
347
        value (Variable): Value to send to channel
348 349
        is_copy (bool): Copy data while channel send. If False, then data
        is moved. The input cannot be used after move. (default False)
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    Returns:
        Variable: The boolean status on whether or not the channel
                  successfully sent the passed value.

    Examples:
        .. code-block:: python

          ch = fluid.make_channel(dtype='int32', capacity=10)
          ...
          # Code to execute in a Go block, which receives the channel data.
          fluid.channel_send(ch, 100)
    """
    helper = LayerHelper('channel_send', **locals())
    main_program = helper.main_program
    channel_send_block = main_program.current_block()
T
Thuan Nguyen 已提交
365

366 367
    X = value

368
    if is_copy:
369 370 371 372 373 374
        copied_X = helper.create_variable(
            name=unique_name.generate(value.name + '_copy'),
            type=value.type,
            dtype=value.dtype,
            shape=value.shape,
            lod_level=value.lod_level,
375
            capacity=value.capacity if hasattr(value, 'capacity') else None)
376 377

        assign_op = channel_send_block.append_op(
378
            type="assign", inputs={"X": value}, outputs={"Out": copied_X})
379 380
        X = copied_X

381 382
    channel_send_block.append_op(
        type="channel_send", inputs={
383
            "Channel": channel,
384
            "X": X,
385
        })
386 387


T
Thuan Nguyen 已提交
388
def channel_recv(channel, return_value):
389 390 391 392 393 394 395 396 397
    """
    Receives a value through a channel variable. Used by an unbuffered or
    buffered channel within a concurrent Go block to get data from originally
    sent using `channel_send`, or from outside such a block where
    `channel_send` is used to send the value.

    Args:
        channel (Variable|Channel): Channel variable created using
        `make_channel`.
T
Thuan Nguyen 已提交
398
        return_value (Variable): Variable to set as a result of running channel_recv_op
399 400

    Returns:
T
Thuan Nguyen 已提交
401
        Variable: The received value from the channel.
402 403 404 405 406 407 408 409
        Variable: The boolean status on whether or not the channel
                  successfully received the passed value.

    Examples:
        .. code-block:: python

          ch = fluid.make_channel(dtype='int32', capacity=10)
          with fluid.Go():
T
Thuan Nguyen 已提交
410
            returned_value, return_status = fluid.channel_recv(ch, 'int32')
411 412 413 414 415 416 417

          # Code to send data through the channel.
    """
    helper = LayerHelper('channel_recv', **locals())
    main_program = helper.main_program
    channel_recv_block = main_program.current_block()

T
Thuan Nguyen 已提交
418 419 420 421
    status = helper.create_variable(
        name=unique_name.generate('status'),
        type=core.VarDesc.VarType.LOD_TENSOR,
        dtype=core.VarDesc.VarType.BOOL)
422 423 424 425 426 427 428

    channel_recv_op = channel_recv_block.append_op(
        type="channel_recv",
        inputs={"Channel": channel},
        outputs={"Out": return_value,
                 "Status": status})

T
Thuan Nguyen 已提交
429
    return return_value, status
430 431 432


def channel_close(channel):
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    """
    Closes a channel created using `make_channel`.

    Args:
        channel (Variable|Channel): Channel variable created using
        `make_channel`.

    Examples:
        .. code-block:: python

          ch = fluid.make_channel(dtype='int32', capacity=10)
          ...
          # Code to receive and send data through a channel
          ...
          fluid.channel_close(ch)
    """
    helper = LayerHelper('channel_close', **locals())
    main_program = helper.main_program
    channel_close_block = main_program.current_block()

    channel_close_op = channel_close_block.append_op(
        type="channel_close", inputs={"Channel": channel})