Skip to content
Snippets Groups Projects
Forked from Eclipse Projects / aidge / aidge_core
2490 commits behind the upstream repository.
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
AvgPooling.hpp 7.54 KiB
/********************************************************************************
 * Copyright (c) 2023 CEA-List
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 ********************************************************************************/

#ifndef AIDGE_CORE_OPERATOR_AVGPOOLING_H_
#define AIDGE_CORE_OPERATOR_AVGPOOLING_H_

#include <array>
#include <numeric>
#include <vector>
#include <cmath>

#include "aidge/data/Tensor.hpp"
#include "aidge/graph/Node.hpp"
#include "aidge/operator/Operator.hpp"
#include "aidge/operator/Producer.hpp"
#include "aidge/utils/Parameter.hpp"
#include "aidge/utils/Registrar.hpp"
#include "aidge/utils/Types.h"

namespace Aidge {
enum class AvgPoolingParam { StrideDims, KernelDims, PaddingDims };

template <DimIdx_t DIM>
class AvgPooling_Op : public Operator,
                public Registrable<AvgPooling_Op<DIM>, std::string, std::unique_ptr<OperatorImpl>(const AvgPooling_Op<DIM> &)>,
                public Parameterizable<AvgPoolingParam,
                                       std::array<DimSize_t, DIM>,
                                       std::array<DimSize_t, DIM>,
                                       std::array<DimSize_t, (DIM<<1) >> {
private:
    // FIXME: change accessibility
    std::shared_ptr<Tensor> mInput = std::make_shared<Tensor>();
    const std::shared_ptr<Tensor> mOutput = std::make_shared<Tensor>();

public:
    static constexpr const char *Type = "AvgPooling";

    AvgPooling_Op() = delete;

    using Parameterizable_ = Parameterizable<AvgPoolingParam,
                                             std::array<DimSize_t, DIM>,
                                             std::array<DimSize_t, DIM>,
                                             std::array<DimSize_t, (DIM<<1)> >;
    template <AvgPoolingParam e>
    using param = typename Parameterizable_::template param<e>;

    constexpr AvgPooling_Op(const std::array<DimSize_t, DIM> &kernel_dims,
                            const std::array<DimSize_t, DIM> &stride_dims = create_array<DimSize_t,DIM>(1),
                            const std::array<DimSize_t, (DIM<<1)> &padding_dims = create_array<DimSize_t,(DIM<<1)>(0))
        : Operator(Type),
          Parameterizable_(param<AvgPoolingParam::StrideDims>(stride_dims),
                           param<AvgPoolingParam::KernelDims>(kernel_dims),
                           param<AvgPoolingParam::PaddingDims>(padding_dims)),
          mOutput(std::make_shared<Tensor>()) {
        setDatatype(DataType::Float32);
    }

    constexpr void associateInput(__attribute__((unused)) const IOIndex_t inputIdx, std::shared_ptr<Data> data) override final {
        assert(inputIdx < 1 && "operators supports only 3 inputs");
        assert(strcmp(data->type(), Tensor::Type) == 0 && "input data must be of Tensor type");

        mInput = std::dynamic_pointer_cast<Tensor>(data);
    }

    constexpr void computeOutputDims() override final {
        if (!mInput->empty()) {
            std::array<DimSize_t, DIM + 2> outputDims = {};

            for (std::size_t dim = 0; dim < this->template get<AvgPoolingParam::KernelDims>().size() ; ++dim) {
                outputDims[dim+2] = 1 + static_cast<DimSize_t>(
                                            std::floor(static_cast<float>(mInput->dims()[dim+2] -
                                                                    this->template get<AvgPoolingParam::KernelDims>()[dim] +
                                                                    this->template get<AvgPoolingParam::PaddingDims>()[dim] +
                                                                    this->template get<AvgPoolingParam::PaddingDims>()[dim+DIM]) /
                                            static_cast<float>(this->template get<AvgPoolingParam::StrideDims>()[dim])));
            }
            outputDims[1] = mInput->dims()[1];
            outputDims[0] = mInput->dims()[0];
            mOutput->resize(outputDims);
        }
    }

    bool outputDimsForwarded() const override final { return !(mOutput->empty()); }


    inline Tensor& input(__attribute__((unused)) const IOIndex_t inputIdx) const override final {
        assert(inputIdx == 0 && "operators supports only 1 inputs");
        return *(mInput.get());
    }
    inline Tensor& output(__attribute__((unused)) const IOIndex_t outputIdx) const override final { return *(mOutput.get()); }


    inline std::shared_ptr<Tensor> getInput(__attribute__((unused)) const IOIndex_t inputIdx) const override final {
        assert(inputIdx == 0 && "AvgPooling Operators supports only 1 inputs");
        return mInput;
    }
    inline std::shared_ptr<Tensor> getOutput(__attribute__((unused)) const IOIndex_t outputIdx) const override final {
        assert(outputIdx == 0 && "AvgPooling Operators has only 1 outputs");
        return mOutput;
    }


    std::shared_ptr<Data> getRawInput(__attribute__((unused)) const IOIndex_t inputIdx) const override final {
        assert(inputIdx == 0 && "operators supports only 1 inputs");
        return std::static_pointer_cast<Data>(mInput);
    }
    std::shared_ptr<Data> getRawOutput(__attribute__((unused)) const IOIndex_t outputIdx) const override final {
        assert(outputIdx == 0 && "operator supports only 1 output");
        return std::static_pointer_cast<Data>(mOutput);
    }


    void setBackend(const std::string &name) {
        mImpl = Registrar<AvgPooling_Op<DIM>>::create(name)(*this);
        mOutput->setBackend(name);

        // FIXME: temporary workaround
        mInput->setBackend(name);
    }

    void setDatatype(const DataType &datatype) {
        mOutput->setDatatype(datatype);

        // FIXME: temporary workaround
        mInput->setDatatype(datatype);
    }

    inline IOIndex_t nbInputs() const noexcept override final { return 1; }
    inline IOIndex_t nbDataInputs() const noexcept override final { return 1; }
    inline IOIndex_t nbOutputs() const noexcept override final { return 1; }
};
template <std::array<DimSize_t, 1>::size_type DIM>
inline std::shared_ptr<Node> AvgPooling(const std::array<DimSize_t, DIM> &kernel_dims,
                                           const char *name = nullptr,
                                           const std::array<DimSize_t, DIM> &stride_dims = create_array<DimSize_t,DIM>(1),
                                           const std::array<DimSize_t, (DIM<<1)> &padding_dims = create_array<DimSize_t,(DIM<<1)>(0)) {
    // FIXME: properly handle default w&b initialization in every cases
    static_assert(DIM<=MaxDim,"Too many kernel dimensions required by AvgPooling, not supported");
    auto avgPool = std::make_shared<Node>(std::make_shared<AvgPooling_Op<static_cast<DimIdx_t>(DIM)>>(kernel_dims, stride_dims, padding_dims), name);
    return avgPool;
}

template <DimSize_t DIM>
inline std::shared_ptr<Node> AvgPooling(
    DimSize_t const (&kernel_dims)[DIM],
    const char *name = nullptr,
    const std::array<DimSize_t, DIM> &stride_dims = create_array<DimSize_t,DIM>(1),
    const std::array<DimSize_t, (DIM<<1)> &padding_dims = create_array<DimSize_t,(DIM<<1)>(0)) {
    static_assert(DIM<=MaxDim,"Too many kernel dimensions required by AvgPooling, not supported");
    return AvgPooling(to_array(kernel_dims), name, stride_dims, padding_dims);
}
}  // namespace Aidge

namespace {
template <>
const char *const EnumStrings<Aidge::AvgPoolingParam>::data[] = {"StrideDims",
                                                          "KernelDims", "PaddingDims"};
}

#endif /* AIDGE_CORE_OPERATOR_AVGPOOLING_H_ */