#   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 __future__ import print_function

import unittest
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid.layers.control_flow import lod_rank_table
from paddle.fluid import Program, program_guard
import numpy
import functools


def convert_to_offset(lod):
    offset = [[0] for i in lod]
    for i, level in enumerate(lod):
        for seq_len in level:
            offset[i].append(offset[i][-1] + seq_len)
    return offset


class TestReorderLoDTensor(unittest.TestCase):
    num_seq = 5
    # [name, shape, lod_level] pair indicating data info of source and target
    data_desc = (['input', [9], 0], ['ref', [5], 1])

    @classmethod
    def setUpClass(cls):
        cls.set_program()

    @classmethod
    def set_program(cls):
        dat = fluid.layers.data(
            name=cls.data_desc[0][0], shape=cls.data_desc[0][1])
        dat.stop_gradient = False
        rank_dat = fluid.layers.data(
            name=cls.data_desc[1][0], shape=cls.data_desc[1][1])
        table = lod_rank_table(rank_dat)
        new_dat = fluid.layers.reorder_lod_tensor_by_rank(
            x=dat, rank_table=table)
        loss = fluid.layers.reduce_sum(new_dat)
        fluid.backward.append_backward(loss=loss)
        cls.fetch_list = [new_dat, cls.data_desc[0][0] + '@GRAD']

    def run_program(self):
        outputs = []
        input_grads = []
        places = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))
        for place in places:
            self.set_inputs(place)
            exe = fluid.Executor(place)
            output, input_grad = exe.run(fluid.default_main_program(),
                                         feed=self.inputs,
                                         fetch_list=self.fetch_list,
                                         return_numpy=False)
            outputs.append(output)
            input_grads.append(input_grad)
        self.actual_outputs = outputs