#include "./algo.h"

using namespace megdnn;
using namespace cuda;
using namespace convolution;

namespace {
std::pair<TensorLayoutArray, Convolution::Param> sub_opr_config(
        const ConvolutionBackwardFilterImpl::AlgoBase::SizeArgs& args) {
    TensorLayout filter_pg = *args.grad_layout;
    TensorLayout src_pg = *args.src_layout;
    TensorLayout diff_pg = *args.diff_layout;

    filter_pg.remove_axis_inplace(0);
    auto nr_grp = args.grad_filter_meta.group;
    size_t c_pos = 1;
    src_pg.shape[c_pos] /= nr_grp;
    diff_pg.shape[c_pos] /= nr_grp;

    megdnn::param::Convolution param = args.opr->param();
    param.sparse = megdnn::param::ConvBias::Sparse::DENSE;
    std::pair<TensorLayoutArray, ConvolutionBackwardFilterImpl::Param> ret;
    ret.first = {src_pg, diff_pg, filter_pg};
    ret.second = param;

    return ret;
}

std::pair<TensorLayoutArray, std::unique_ptr<ConvolutionBackwardFilter>> prepare_sub_opr(
        const ConvolutionBackwardFilterImpl::AlgoBase::SizeArgs& args) {
    auto conv_bwd_filter_opr =
            args.handle->create_operator<ConvolutionBackwardFilter>();
    set_execution_policy<ConvolutionBackwardFilter, ConvolutionBackwardFilter*>(
            args.opr, conv_bwd_filter_opr.get());
    auto&& config = sub_opr_config(args);
    conv_bwd_filter_opr->param() = config.second;

    return {config.first, std::move(conv_bwd_filter_opr)};
}
}  // namespace

std::vector<Algorithm::SearchItem> ConvolutionBackwardFilterImpl::AlgoGroupConvGeneral::
        get_subopr_list(
                const TensorLayoutArray& layouts, const OperatorBase* opr) const {
    AlgoBase::SizeArgs args{
            static_cast<const ConvolutionBackwardFilterImpl*>(opr), layouts[0],
            layouts[1], layouts[2]};
    auto&& config = sub_opr_config(args);

    std::string param_str;
    Algorithm::serialize_write_pod(config.second, param_str);
    return {{Algorithm::OprType::CONVOLUTION_BACKWARD_FILTER, param_str, config.first}};
}

bool ConvolutionBackwardFilterImpl::AlgoGroupConvGeneral::is_available(
        const SizeArgs& args) const {
    if (args.src_layout->dtype == args.src_layout->dtype &&
        args.diff_layout->dtype == dtype::BFloat16()) {
        return false;
    }
    if (args.grad_filter_meta.group <= 1)
        return false;
    if (args.grad_filter_meta.format != megdnn::param::Convolution::Format::NCHW) {
        return false;
    }

    auto config = prepare_sub_opr(args);

    return has_available_algo<ConvolutionBackwardFilterImpl>(
            static_cast<ConvolutionBackwardFilterImpl*>(config.second.get()),
            config.first[0], config.first[1], config.first[2]);
}

WorkspaceBundle ConvolutionBackwardFilterImpl::AlgoGroupConvGeneral::
        get_workspace_bundle(void* ptr, const SizeArgs& args) const {
    auto config = prepare_sub_opr(args);
    size_t sizes = config.second->get_workspace_in_bytes(
            config.first[0], config.first[1], config.first[2]);
    return {ptr, {sizes}};
}

size_t ConvolutionBackwardFilterImpl::AlgoGroupConvGeneral::get_workspace_in_bytes(
        const SizeArgs& args) const {
    return get_workspace_bundle(nullptr, args).total_size_in_bytes();
}

void ConvolutionBackwardFilterImpl::AlgoGroupConvGeneral::exec(
        const ExecArgs& args) const {
    auto bundle = get_workspace_bundle(args.workspace.raw_ptr, args);

    {
        auto config = prepare_sub_opr(args);
        TensorND tsrc{args.src_tensor->raw_ptr(), config.first[0]};
        TensorND tdiff{args.diff_tensor->raw_ptr(), config.first[1]};
        TensorND tgrad{args.grad_tensor->raw_ptr(), config.first[2]};

        size_t c_pos = 1;

        auto&& fm = args.grad_filter_meta;

        auto strd_src = tsrc.layout.stride[c_pos] * fm.icpg * tsrc.layout.dtype.size(),
             strd_diff =
                     tdiff.layout.stride[c_pos] * fm.ocpg * tdiff.layout.dtype.size(),
             strd_grad = fm.icpg * fm.ocpg * fm.spatial[0] * fm.spatial[1] *
                         tgrad.layout.dtype.size();

        auto grp = fm.group;
        for (uint32_t g = 0; g < grp; ++g) {
            config.second->exec(tsrc, tdiff, tgrad, bundle.get_workspace(0));
            incr_refp(tsrc.get_ref_ptr(), strd_src);
            incr_refp(tdiff.get_ref_ptr(), strd_diff);
            incr_refp(tgrad.get_ref_ptr(), strd_grad);
        }
    }
}

// vim: syntax=cpp.doxygen
