test_gather_v2_primitive.py 7.8 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
import numpy as np
J
jinyaohui 已提交
16

Z
zhunaipan 已提交
17 18 19
import mindspore as ms
import mindspore.nn as nn
from mindspore import Tensor
J
jinyaohui 已提交
20
from mindspore import context
Z
zhunaipan 已提交
21
from mindspore.common import dtype as mstype
J
jinyaohui 已提交
22 23
from mindspore.common.parameter import ParameterTuple
from mindspore.communication.management import init
Z
zhunaipan 已提交
24
from mindspore.nn import Dense, Cell
J
jinyaohui 已提交
25 26 27 28 29 30
from mindspore.nn.loss.loss import _Loss
from mindspore.nn.optim import Momentum
from mindspore.ops import composite as C
from mindspore.ops import functional as F
from mindspore.ops import operations as P
from mindspore.train import Model, ParallelMode
Z
zhunaipan 已提交
31 32

context.set_context(mode=context.GRAPH_MODE)
33 34
device_number = 32
batch_size_per_device = 128
Z
zhunaipan 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62


class Dataset():
    def __init__(self, predict, length=3):
        self.predict = predict
        self.index = 0
        self.length = length

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= self.length:
            raise StopIteration
        self.index += 1
        return (self.predict,)

    def reset(self):
        self.index = 0

    def get_dataset_size(self):
        return 128

    def get_repeat_count(self):
        return 1


class GatherV2(_Loss):
63
    def __init__(self, index_dim, strategy, index_size=16):
Z
zhunaipan 已提交
64 65
        super(GatherV2, self).__init__()
        self.pow = P.Pow()
66 67 68 69 70 71 72
        emb1_list = 21
        emb2_list = 2
        if index_dim == 1:
            emb_list = list(range(index_size))
            emb1_list = emb_list[0::2]
            emb2_list = emb_list[1::2]
        if index_dim == 2:
J
jinyaohui 已提交
73 74 75
            emb_list = np.arange(index_size * 16)
            emb1_list = np.reshape(emb_list[0::2], (int(index_size / 2), 16))
            emb2_list = np.reshape(emb_list[1::2], (int(index_size / 2), 16))
Z
zhunaipan 已提交
76 77
        self.emb1_param = Tensor(emb1_list, dtype=mstype.int32)
        self.emb2_param = Tensor(emb2_list, dtype=mstype.int32)
L
lichenever 已提交
78
        self.gatherv2 = P.GatherV2().set_strategy(strategy).add_prim_attr("data_parallel", True)
Z
zhunaipan 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    def construct(self, nembeddings):
        emb1 = self.gatherv2(nembeddings, self.emb1_param, 0)
        emb2 = self.gatherv2(nembeddings, self.emb2_param, 0)
        return self.pow((emb1 - emb2), 2.0)


def fc_with_initialize(input_channels, out_channels):
    return Dense(input_channels, out_channels)


class BuildTrainNetwork(nn.Cell):
    def __init__(self, network, criterion):
        super(BuildTrainNetwork, self).__init__()
        self.network = network
        self.criterion = criterion

    def construct(self, input_data):
        embeddings = self.network(input_data)
        loss = self.criterion(embeddings)
        return loss


class TrainOneStepCell(Cell):
    def __init__(self, network, optimizer, sens=1.0):
        super(TrainOneStepCell, self).__init__(auto_prefix=False)
        self.network = network
        self.network.add_flags(defer_inline=True)
        self.weights = ParameterTuple(network.trainable_params())
        self.optimizer = optimizer
        self.grad = C.GradOperation('grad',
                                    get_by_list=True,
                                    sens_param=True)
        self.sens = sens

    def construct(self, data):
        weights = self.weights
        loss = self.network(data)
        sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens)
        grads = self.grad(self.network, weights)(data, sens)

        return F.depend(loss, self.optimizer(grads))


Y
Yi Huaijie 已提交
123
def net_trains(criterion, rank):
Z
zhunaipan 已提交
124 125 126 127 128 129
    init()
    lr = 0.1
    momentum = 0.9
    max_epoch = 20
    input_channels = 256
    out_channels = 512
130
    context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
Z
zhunaipan 已提交
131
    context.reset_auto_parallel_context()
132 133
    context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=device_number,
                                      global_rank=rank)
Z
zhunaipan 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    predict = Tensor(np.ones([batch_size_per_device, input_channels]), dtype=ms.float32)
    dataset = Dataset(predict, 4)

    network = fc_with_initialize(input_channels, out_channels)
    network.set_train()

    train_network = BuildTrainNetwork(network, criterion)
    train_network.set_train()
    opt = Momentum(train_network.trainable_params(), lr, momentum)
    train_net = TrainOneStepCell(train_network, opt).set_train()

    model = Model(train_net)
    model.train(max_epoch, dataset, dataset_sink_mode=False)
    context.reset_auto_parallel_context()

149 150 151 152 153

def test_auto_batch_parallel():
    gather_v2_strategy = None
    criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
    rank = 2
Y
Yi Huaijie 已提交
154
    net_trains(criterion, rank)
155 156 157 158 159 160


def test_2d_index_auto_batch_parallel():
    gather_v2_strategy = None
    criterion = GatherV2(2, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
    rank = 2
Y
Yi Huaijie 已提交
161
    net_trains(criterion, rank)
162 163 164 165 166 167


def test_batch_parallel():
    gather_v2_strategy = ((device_number, 1),)
    criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
    rank = 2
Y
Yi Huaijie 已提交
168
    net_trains(criterion, rank)
169 170 171 172 173 174


def test_strategy1():
    gather_v2_strategy = ((16, 2),)
    rank = 2
    criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
Y
Yi Huaijie 已提交
175
    net_trains(criterion, rank)
176 177 178 179 180 181


def test_strategy2():
    gather_v2_strategy = ((1, device_number),)
    rank = 2
    criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
Y
Yi Huaijie 已提交
182
    net_trains(criterion, rank)
183 184 185 186 187 188


def test_strategy3():
    gather_v2_strategy = ((8, 1),)
    rank = 2
    criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
Y
Yi Huaijie 已提交
189
    net_trains(criterion, rank)
190 191 192 193 194 195 196 197 198 199 200 201 202


class GatherV2Axis1(_Loss):
    def __init__(self, index_dim, strategy, index_size=16):
        super(GatherV2Axis1, self).__init__()
        self.pow = P.Pow()
        emb1_list = 21
        emb2_list = 2
        if index_dim == 1:
            emb_list = list(range(index_size))
            emb1_list = emb_list[0::2]
            emb2_list = emb_list[1::2]
        if index_dim == 2:
J
jinyaohui 已提交
203 204 205
            emb_list = np.arange(index_size * index_size)
            emb1_list = np.reshape(emb_list[0::2], (int(index_size / 2), index_size))
            emb2_list = np.reshape(emb_list[1::2], (int(index_size / 2), index_size))
206 207 208 209 210 211 212 213 214 215 216 217 218 219
        self.emb1_param = Tensor(emb1_list, dtype=mstype.int32)
        self.emb2_param = Tensor(emb2_list, dtype=mstype.int32)
        self.gatherv2 = P.GatherV2().set_strategy(strategy)

    def construct(self, nembeddings):
        emb1 = self.gatherv2(nembeddings, self.emb1_param, 1)
        emb2 = self.gatherv2(nembeddings, self.emb2_param, 1)
        return self.pow((emb1 - emb2), 2.0)


def test_axis1_auto_batch_parallel():
    gather_v2_strategy = None
    criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
    rank = 2
Y
Yi Huaijie 已提交
220
    net_trains(criterion, rank)
221 222 223


def test_axis1_batch_parallel():
224
    gather_v2_strategy = ((device_number, 1), (1,))
225 226
    criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
    rank = 2
Y
Yi Huaijie 已提交
227
    net_trains(criterion, rank)
228 229 230


def test_axis1_strategy1():
231
    gather_v2_strategy = ((16, 2), (1,))
232 233
    rank = 17
    criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
Y
Yi Huaijie 已提交
234
    net_trains(criterion, rank)