# 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

import mindspore.nn as nn
from mindspore import Tensor, Parameter
from mindspore import context
from mindspore.common.api import _executor
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from tests.ut.python.ops.test_math_ops import VirtualLoss


grad_all = C.GradOperation(get_all=True)


class NetWithLoss(nn.Cell):
    def __init__(self, network):
        super(NetWithLoss, self).__init__()
        self.loss = VirtualLoss()
        self.network = network

    def construct(self, x):
        predict = self.network(x)
        return self.loss(predict)


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

    def construct(self, x):
        return grad_all(self.network)(x)


class CustomDense(nn.Cell):
    def __init__(self, row, column):
        super(CustomDense, self).__init__()
        self.weight = Parameter(Tensor(np.ones([row, column]).astype(np.float32) * 0.01), "w", requires_grad=True)
        self.bias = Parameter(Tensor(np.zeros([row, column]).astype(np.float32)), "b", requires_grad=True)
        self.matmul1 = P.MatMul()
        self.add2 = P.TensorAdd()
        self.activation3 = nn.ReLU()

    def construct(self, x):
        mat_output = self.matmul1(x, self.weight)
        add_output = self.add2(mat_output, self.bias)
        output = self.activation3(add_output)

        return output


class DenseMutMulNet(nn.Cell):
    def __init__(self):
        super(DenseMutMulNet, self).__init__()
        self.fc1 = CustomDense(4096, 4096)
        self.fc2 = CustomDense(4096, 4096)
        self.fc3 = CustomDense(4096, 4096)
        self.fc4 = CustomDense(4096, 4096)
        self.relu4 = nn.ReLU()
        self.relu5 = nn.ReLU()
        self.transpose = P.Transpose()
        self.matmul1 = P.MatMul()
        self.matmul2 = P.MatMul()

    def construct(self, x):
        q = self.fc1(x)
        k = self.fc2(x)
        v = self.fc3(x)
        k = self.transpose(k, (1, 0))
        c = self.relu4(self.matmul1(q, k))
        s = self.relu5(self.matmul2(c, v))
        s = self.fc4(s)
        return s


class MultiTransformer(nn.Cell):
    def __init__(self, layer_nums=1):
        super(MultiTransformer, self).__init__()
        self.layer = self._make_layer(layer_nums)

    def _make_layer(self, layer_num):
        layers = []
        for _ in range(0, layer_num):
            layers.append(DenseMutMulNet())

        return nn.SequentialCell(layers)

    def construct(self, x):
        out = self.layer(x)
        return out


def test_dmnet_train_step():
    size = 8
    context.set_auto_parallel_context(device_num=size, global_rank=0)

    input_ = Tensor(np.ones([4096, 4096]).astype(np.float32) * 0.01)
    net = GradWrap(NetWithLoss(MultiTransformer()))
    context.set_auto_parallel_context(parallel_mode="auto_parallel")
    net.set_auto_parallel()
    _executor.compile(net, input_)

[((26, 11, 26, 40), 'mindspore.ops.composite.GradOperation', 'C.GradOperation', (), '', True, 'from mindspore.ops import composite as C\n'), ((109, 4, 109, 69), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', (), '', False, 'from mindspore import context\n'), ((113, 4, 113, 68), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', (), '', False, 'from mindspore import context\n'), ((115, 4, 115, 34), 'mindspore.common.api._executor.compile', '_executor.compile', ({(115, 22, 115, 25): 'net', (115, 27, 115, 33): 'input_'}, {}), '(net, input_)', False, 'from mindspore.common.api import _executor\n'), ((32, 20, 32, 33), 'tests.ut.python.ops.test_math_ops.VirtualLoss', 'VirtualLoss', ({}, {}), '()', False, 'from tests.ut.python.ops.test_math_ops import VirtualLoss\n'), ((54, 23, 54, 33), 'mindspore.ops.operations.MatMul', 'P.MatMul', ({}, {}), '()', True, 'from mindspore.ops import operations as P\n'), ((55, 20, 55, 33), 'mindspore.ops.operations.TensorAdd', 'P.TensorAdd', ({}, {}), '()', True, 'from mindspore.ops import operations as P\n'), ((56, 27, 56, 36), 'mindspore.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import mindspore.nn as nn\n'), ((73, 21, 73, 30), 'mindspore.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import mindspore.nn as nn\n'), ((74, 21, 74, 30), 'mindspore.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import mindspore.nn as nn\n'), ((75, 25, 75, 38), 'mindspore.ops.operations.Transpose', 'P.Transpose', ({}, {}), '()', True, 'from mindspore.ops import operations as P\n'), ((76, 23, 76, 33), 'mindspore.ops.operations.MatMul', 'P.MatMul', ({}, {}), '()', True, 'from mindspore.ops import operations as P\n'), ((77, 23, 77, 33), 'mindspore.ops.operations.MatMul', 'P.MatMul', ({}, {}), '()', True, 'from mindspore.ops import operations as P\n'), ((100, 15, 100, 40), 'mindspore.nn.SequentialCell', 'nn.SequentialCell', ({(100, 33, 100, 39): 'layers'}, {}), '(layers)', True, 'import mindspore.nn as nn\n'), ((111, 20, 111, 41), 'numpy.ones', 'np.ones', ({(111, 28, 111, 40): '[4096, 4096]'}, {}), '([4096, 4096])', True, 'import numpy as np\n'), ((53, 37, 53, 60), 'numpy.zeros', 'np.zeros', ({(53, 46, 53, 59): '[row, column]'}, {}), '([row, column])', True, 'import numpy as np\n'), ((52, 39, 52, 61), 'numpy.ones', 'np.ones', ({(52, 47, 52, 60): '[row, column]'}, {}), '([row, column])', True, 'import numpy as np\n')]