concurrency.py 8.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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.

from layers.control_flow import BlockGuard
T
Thuan Nguyen 已提交
16 17
from layer_helper import LayerHelper, unique_name
from layers import fill_constant
18
import core
T
Thuan Nguyen 已提交
19

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
__all__ = [
    'Go',
    'make_channel',
    'channel_send',
    'channel_recv',
    'channel_close',
]


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
        self.construct_go_op()
        return super(Go, self).__exit__(exc_type, exc_val, exc_tb)

    def construct_go_op(self):
        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 已提交
49
        inner_outputs = set()
50 51 52 53 54 55
        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 已提交
56 57
                    if in_var_name not in inner_outputs:
                        x_name_list.add(in_var_name)
58 59 60

            for oname in op.output_names:
                for out_var_name in op.output(oname):
T
Thuan Nguyen 已提交
61 62 63 64 65 66 67 68 69
                    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))
70 71 72

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


81 82 83 84 85 86
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.
87

88 89 90
    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.
91

92 93 94 95 96 97 98
    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 已提交
99 100
        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.
101 102 103 104 105 106 107 108 109
        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
110

111 112 113 114 115 116
          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 已提交
117
    helper = LayerHelper('channel_create', **locals())
118 119
    main_program = helper.main_program
    make_channel_block = main_program.current_block()
120

121 122 123
    # 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 已提交
124 125 126
        name=unique_name.generate('channel'),
        type=core.VarDesc.VarType.CHANNEL,
        persistable=True)
127 128 129 130 131 132 133

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

T
Thuan Nguyen 已提交
134
    return channel
135 136 137 138 139 140 141 142 143 144 145


def channel_send(channel, value):
    """
    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 已提交
146
        value (Variable): Value to send to channel
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    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 已提交
162 163 164 165 166

    status = helper.create_variable(
        name=unique_name.generate('status'),
        type=core.VarDesc.VarType.LOD_TENSOR,
        dtype=core.VarDesc.VarType.BOOL)
167 168 169 170 171 172 173 174 175

    channel_send_op = channel_send_block.append_op(
        type="channel_send",
        inputs={
            "Channel": channel,
            "X": value,
        },
        outputs={"Status": status})

T
Thuan Nguyen 已提交
176
    return status
177 178


T
Thuan Nguyen 已提交
179
def channel_recv(channel, return_value):
180 181 182 183 184 185 186 187 188
    """
    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 已提交
189
        return_value (Variable): Variable to set as a result of running channel_recv_op
190 191

    Returns:
T
Thuan Nguyen 已提交
192
        Variable: The received value from the channel.
193 194 195 196 197 198 199 200
        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 已提交
201
            returned_value = fluid.channel_recv(ch, 'int32')
202 203 204 205 206 207 208

          # 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 已提交
209 210 211 212
    status = helper.create_variable(
        name=unique_name.generate('status'),
        type=core.VarDesc.VarType.LOD_TENSOR,
        dtype=core.VarDesc.VarType.BOOL)
213 214 215 216 217 218 219

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

T
Thuan Nguyen 已提交
220
    return return_value, status
221 222 223


def channel_close(channel):
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    """
    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})