438 lines
19 KiB
C++
438 lines
19 KiB
C++
#ifndef CENET_LAYERS_CONVOLUTIONAL_HPP
|
|
#define CENET_LAYERS_CONVOLUTIONAL_HPP
|
|
|
|
#include "../optim/adam.hpp"
|
|
#include "./layer_fwd.hpp"
|
|
#include "./layer_traits.hpp"
|
|
#include "./retained.hpp"
|
|
|
|
#include <cmath>
|
|
#include <iostream>
|
|
#include <tulip/tensor_fwd.hpp>
|
|
#include <tulip/tensor_shape.hpp>
|
|
#include <tulip/tensor_traits.hpp>
|
|
|
|
namespace cenet {
|
|
namespace layers {
|
|
|
|
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
|
|
struct conv2d final : public layer_tag {
|
|
static constexpr auto retain = retain::Input;
|
|
|
|
template <class N, std::size_t I>
|
|
struct data final {
|
|
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
static_assert(tulip::is_tensor_v<input_type>);
|
|
static_assert(input_type::shape_type::rank == 3);
|
|
|
|
using value_type = typename input_type::value_type;
|
|
|
|
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
|
|
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
|
|
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
|
|
|
|
static_assert(!input_type::traits::dynamic, "dynamic input to conv2d is currently unsupported");
|
|
|
|
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
|
|
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
|
|
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
|
|
static constexpr std::size_t OUT_CHANS = OutChannels;
|
|
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
|
|
using output_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
|
|
|
using weights_type =
|
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
|
using biases_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS>;
|
|
|
|
weights_type weights{};
|
|
biases_type biases{};
|
|
|
|
void dump(std::ostream& os) const {
|
|
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(value_type) * weights.size());
|
|
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
|
|
}
|
|
|
|
void load(std::istream& is) {
|
|
is.read(reinterpret_cast<char*>(weights.data()), sizeof(value_type) * weights.size());
|
|
is.read(reinterpret_cast<char*>(biases.data()), sizeof(value_type) * biases.size());
|
|
}
|
|
|
|
template <typename Dist>
|
|
void fill_random(const Dist& dist) {
|
|
constexpr value_type fanIn = static_cast<value_type>(IN_CHANS * KernelSize * KernelSize);
|
|
|
|
const value_type scale = std::sqrt(6.0 / fanIn);
|
|
|
|
weights.view().fill_random(dist);
|
|
weights = weights.apply([scale](auto val) { return val * scale; });
|
|
biases.view().fill();
|
|
}
|
|
|
|
auto feed(const input_type& input) {
|
|
typename output_type::template with_storage<tulip::heap_storage_tag> output;
|
|
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
|
|
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
auto value = biases[oc];
|
|
|
|
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
|
|
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
|
|
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
|
|
std::ptrdiff_t iy = static_cast<std::ptrdiff_t>((oy * Stride) + ky) -
|
|
static_cast<std::ptrdiff_t>(Padding);
|
|
std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
|
|
static_cast<std::ptrdiff_t>(Padding);
|
|
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
|
|
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
|
|
value += input[ic][iy][ix] * weights[oc][ic][ky][kx];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
output[oc][oy][ox] = value;
|
|
}
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
};
|
|
|
|
template <class N, std::size_t I>
|
|
struct grad final {
|
|
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
static_assert(tulip::is_tensor_v<input_type>);
|
|
static_assert(input_type::shape_type::rank == 3);
|
|
|
|
using value_type = typename input_type::value_type;
|
|
|
|
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
|
|
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
|
|
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
|
|
|
|
static_assert(!input_type::traits::dynamic, "dynamic input to conv2d is currently unsupported");
|
|
|
|
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
|
|
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
|
|
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
|
|
static constexpr std::size_t OUT_CHANS = OutChannels;
|
|
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
|
|
using weights_type =
|
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
|
using biases_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS>;
|
|
|
|
weights_type weights{};
|
|
biases_type biases{};
|
|
|
|
weights_type momentumWeights{};
|
|
biases_type momentumBiases{};
|
|
weights_type varianceWeights{};
|
|
biases_type varianceBiases{};
|
|
|
|
std::size_t time = 0;
|
|
|
|
void reset() {
|
|
weights.view().fill();
|
|
biases.view().fill();
|
|
}
|
|
|
|
template <typename Error>
|
|
auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
|
|
typename input_type::template with_storage<tulip::heap_storage_tag> backpropErr;
|
|
backpropErr.view().fill();
|
|
|
|
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
|
|
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
const auto err = prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(oc, oy, ox)));
|
|
|
|
biases[oc] += err;
|
|
|
|
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
|
|
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
|
|
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
|
|
const std::ptrdiff_t iy = static_cast<std::ptrdiff_t>((oy * Stride) + ky) -
|
|
static_cast<std::ptrdiff_t>(Padding);
|
|
|
|
const std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
|
|
static_cast<std::ptrdiff_t>(Padding);
|
|
|
|
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
|
|
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
|
|
|
|
weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err;
|
|
|
|
backpropErr[ic][iy][ix] += data.weights[oc][ic][ky][kx] * err;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return backpropErr;
|
|
}
|
|
};
|
|
|
|
template <class N, std::size_t I, class Optim>
|
|
struct optim {
|
|
static_assert(false, "unsupported optimizer");
|
|
};
|
|
|
|
template <class N, std::size_t I>
|
|
struct optim<N, I, cenet::optim::adam> {
|
|
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
static_assert(tulip::is_tensor_v<input_type>);
|
|
static_assert(input_type::shape_type::rank == 3);
|
|
|
|
using value_type = typename input_type::value_type;
|
|
|
|
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
|
|
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
|
|
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
|
|
|
|
static_assert(!input_type::traits::dynamic, "dynamic input to conv2d is currently unsupported");
|
|
|
|
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
|
|
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
|
|
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
|
|
|
|
static constexpr std::size_t OUT_CHANS = OutChannels;
|
|
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
|
|
|
|
using weights_type =
|
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
|
using biases_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS>;
|
|
|
|
std::size_t time = 0;
|
|
|
|
weights_type momentumWeights{};
|
|
biases_type momentumBiases{};
|
|
weights_type varianceWeights{};
|
|
biases_type varianceBiases{};
|
|
|
|
void apply(data<N, I>& data, grad<N, I>& grad, double divisor, double rate) {
|
|
++time;
|
|
|
|
constexpr double beta1 = 0.9;
|
|
constexpr double beta2 = 0.999;
|
|
constexpr double epsilon = 1e-8;
|
|
|
|
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
|
|
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
|
|
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
|
|
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
|
|
double avgGrad = grad.weights[oc][ic][ky][kx] / divisor;
|
|
|
|
momentumWeights[oc][ic][ky][kx] =
|
|
(beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad);
|
|
varianceWeights[oc][ic][ky][kx] =
|
|
(beta2 * varianceWeights[oc][ic][ky][kx]) + ((1.0 - beta2) * avgGrad * avgGrad);
|
|
|
|
auto momentumCorrected = momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, time));
|
|
auto varianceCorrected = varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, time));
|
|
|
|
data.weights[oc][ic][ky][kx] -=
|
|
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
|
}
|
|
}
|
|
}
|
|
|
|
auto avgGrad = grad.biases[oc] / divisor;
|
|
|
|
momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad);
|
|
varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad);
|
|
|
|
auto momentumCorrected = momentumBiases[oc] / (1.0 - std::pow(beta1, time));
|
|
auto varianceCorrected = varianceBiases[oc] / (1.0 - std::pow(beta2, time));
|
|
|
|
data.biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
|
}
|
|
}
|
|
};
|
|
};
|
|
|
|
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
|
|
struct maxpool final : public layer_tag {
|
|
static constexpr auto retain = retain::Input;
|
|
|
|
template <class N, std::size_t I>
|
|
struct data final {
|
|
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
static_assert(tulip::is_tensor_v<input_type>);
|
|
static_assert(input_type::shape_type::rank == 3);
|
|
static_assert(!input_type::traits::dynamic, "dynamic input to maxpool is currently unsupported");
|
|
|
|
using value_type = typename input_type::value_type;
|
|
|
|
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
|
|
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
|
|
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
|
|
|
|
static constexpr std::size_t OUT_CHANS = IN_CHANS;
|
|
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
|
|
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
|
|
|
|
using output_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
|
|
|
void dump(std::ostream& os) const {}
|
|
|
|
void load(std::istream& is) {}
|
|
|
|
template <typename Dist>
|
|
void fill_random(const Dist& dist) {}
|
|
|
|
auto feed(const input_type& input) {
|
|
output_type output;
|
|
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
|
|
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
auto maxValue = input[ch][oy * Stride][ox * Stride];
|
|
|
|
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
|
|
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
|
|
maxValue = std::max(maxValue, input[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
|
|
}
|
|
}
|
|
|
|
output[ch][oy][ox] = maxValue;
|
|
}
|
|
}
|
|
}
|
|
|
|
return output;
|
|
}
|
|
};
|
|
|
|
template <class N, std::size_t I>
|
|
struct grad final {
|
|
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
|
|
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
|
|
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
|
|
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
|
|
|
|
static constexpr std::size_t OUT_CHANS = IN_CHANS;
|
|
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
|
|
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
|
|
|
|
void reset() {}
|
|
|
|
template <typename Error>
|
|
auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
|
|
input_type backpropErr;
|
|
backpropErr.view().fill();
|
|
|
|
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
|
|
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
std::size_t maxY = oy * Stride;
|
|
std::size_t maxX = ox * Stride;
|
|
|
|
auto maxValue = retained[ch][maxY][maxX];
|
|
|
|
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
|
|
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
|
|
const std::size_t yIdx = (oy * Stride) + ky;
|
|
const std::size_t xIdx = (ox * Stride) + kx;
|
|
|
|
if (retained[ch][yIdx][xIdx] > maxValue) {
|
|
maxValue = retained[ch][yIdx][xIdx];
|
|
maxY = yIdx;
|
|
maxX = xIdx;
|
|
}
|
|
}
|
|
}
|
|
|
|
backpropErr[ch][maxY][maxX] +=
|
|
prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(ch, oy, ox)));
|
|
}
|
|
}
|
|
}
|
|
|
|
return backpropErr;
|
|
}
|
|
};
|
|
|
|
template <typename N, std::size_t I, class Optim>
|
|
struct optim {
|
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
|
};
|
|
};
|
|
|
|
struct flatten final : public layer_tag {
|
|
static constexpr auto retain = retain::None;
|
|
|
|
template <class N, std::size_t I>
|
|
struct data final {
|
|
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
static_assert(tulip::is_tensor_v<input_type>);
|
|
static_assert(!input_type::traits::dynamic, "dynamic input to flatten is currently unsupported");
|
|
|
|
using value_type = typename input_type::value_type;
|
|
|
|
static constexpr auto FEATURES = input_type::shape_type::size;
|
|
|
|
using output_type = tulip::matrix<value_type, 1, FEATURES>;
|
|
|
|
void dump(std::ostream& os) const {}
|
|
|
|
void load(std::istream& is) {}
|
|
|
|
template <typename Dist>
|
|
void fill_random(const Dist& dist) {}
|
|
|
|
template <typename Fwd>
|
|
auto feed(Fwd&& fwd) {
|
|
return std::forward<Fwd>(fwd).template reshape<tulip::shape_of<1, FEATURES>>();
|
|
}
|
|
};
|
|
|
|
template <class N, std::size_t I>
|
|
struct grad final {
|
|
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
|
|
|
|
using input_type = typename traits::input_type;
|
|
|
|
void reset() {}
|
|
|
|
template <typename Error, typename R>
|
|
auto backward(const data<N, I>& data, R, Error&& prevErr) {
|
|
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
|
|
}
|
|
};
|
|
|
|
template <typename N, std::size_t I, class Optim>
|
|
struct optim {
|
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
|
};
|
|
};
|
|
|
|
} // namespace layers
|
|
} // namespace cenet
|
|
|
|
#endif // CENET_LAYERS_CONVOLUTIONAL_HPP
|