refactor: restructure the project
This commit is contained in:
@@ -0,0 +1,528 @@
|
||||
#ifndef CENET_LAYER_HPP
|
||||
#define CENET_LAYER_HPP
|
||||
|
||||
#include "input.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <tuple>
|
||||
|
||||
namespace cenet {
|
||||
|
||||
struct layer_info {
|
||||
protected:
|
||||
template <class NN, std::size_t I>
|
||||
struct input_type_s {
|
||||
using type = std::tuple_element_t<I - 1, typename NN::layer_types>::output_type;
|
||||
};
|
||||
|
||||
template <class NN>
|
||||
struct input_type_s<NN, 0> {
|
||||
using type = typename NN::input_type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
using input_inner_t = typename T::inner;
|
||||
};
|
||||
|
||||
template <std::size_t Features>
|
||||
class dense_layer final : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
static_assert(input_type::TAG == layer_input::DENSE_TAG);
|
||||
|
||||
using output_type = input_inner_t<dense_input<Features>>;
|
||||
|
||||
static constexpr std::size_t INPUT_FEATURES = input_type::FEATURES;
|
||||
static constexpr std::size_t OUTPUT_FEATURES = Features;
|
||||
|
||||
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES>;
|
||||
using biases_type = mat<1, OUTPUT_FEATURES>;
|
||||
|
||||
struct gradient final {
|
||||
using parent_type = inner;
|
||||
|
||||
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 = weights_type{};
|
||||
biases = biases_type{};
|
||||
}
|
||||
};
|
||||
|
||||
weights_type weights;
|
||||
biases_type biases;
|
||||
output_type output;
|
||||
|
||||
void dump(std::ostream& os) const {
|
||||
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size());
|
||||
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size());
|
||||
}
|
||||
|
||||
void load(std::istream& is) {
|
||||
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size());
|
||||
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size());
|
||||
}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {
|
||||
double scale = std::sqrt(2.0 / static_cast<double>(INPUT_FEATURES));
|
||||
weights = decltype(weights)::random(dist) * scale;
|
||||
biases = decltype(biases)::random(dist) * scale;
|
||||
}
|
||||
|
||||
auto& forward(const input_type& input) { return output = (input.get() * weights) + biases; }
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) {
|
||||
grad.weights += input.get().transpose() * prevErr;
|
||||
grad.biases += prevErr;
|
||||
|
||||
return prevErr * weights.transpose();
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {
|
||||
++grad.time;
|
||||
|
||||
constexpr double beta1 = 0.9;
|
||||
constexpr double beta2 = 0.999;
|
||||
constexpr double epsilon = 1e-8;
|
||||
|
||||
for (std::size_t row = 0; row < INPUT_FEATURES; ++row) {
|
||||
for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) {
|
||||
double avgGrad = grad.weights[row][col] / divisor;
|
||||
|
||||
grad.momentumWeights[row][col] = beta1 * grad.momentumWeights[row][col] + (1.0 - beta1) * avgGrad;
|
||||
grad.varianceWeights[row][col] =
|
||||
beta2 * grad.varianceWeights[row][col] + (1.0 - beta2) * (avgGrad * avgGrad);
|
||||
|
||||
double momentumCorrected = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time));
|
||||
double varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time));
|
||||
|
||||
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||
}
|
||||
}
|
||||
|
||||
for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) {
|
||||
double avgGrad = grad.biases[0][col] / divisor;
|
||||
|
||||
grad.momentumBiases[0][col] = beta1 * grad.momentumBiases[0][col] + (1.0 - beta1) * avgGrad;
|
||||
grad.varianceBiases[0][col] = beta2 * grad.varianceBiases[0][col] + (1.0 - beta2) * (avgGrad * avgGrad);
|
||||
|
||||
double momentumCorrected = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time));
|
||||
double varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time));
|
||||
|
||||
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
class sigmoid_layer final : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
static_assert(input_type::TAG == layer_input::DENSE_TAG);
|
||||
using output_type = input_type;
|
||||
|
||||
output_type output;
|
||||
|
||||
struct gradient {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
static double sigmoid(double in) { return 1 / (1 + std::exp(-in)); }
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {}
|
||||
|
||||
auto& forward(const input_type& input) {
|
||||
output.get().apply(input, [](double unusd, double in) { return sigmoid(in); });
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
|
||||
return prevErr.hadamard(output.get().hadamard(1.0 - output.get()));
|
||||
}
|
||||
|
||||
void apply_grad(gradient&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
class relu_layer final : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
using output_type = input_type;
|
||||
|
||||
input_type savedInput;
|
||||
output_type output;
|
||||
|
||||
struct gradient {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {}
|
||||
|
||||
auto& forward(const input_type& input) {
|
||||
savedInput = input;
|
||||
output.get().apply(input, [](double unusd, double in) { return in > 0.0 ? in : 0.0; });
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
|
||||
return prevErr.apply(savedInput, [](double in, double check) { return check > 0.0 ? in : 0.0; });
|
||||
}
|
||||
|
||||
void apply_grad(gradient&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
|
||||
class conv2d_layer final : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
|
||||
|
||||
using input_tensor = input_type::type;
|
||||
static_assert(input_tensor::RANK == 3);
|
||||
|
||||
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
|
||||
static constexpr std::size_t IN_HEIGHT = input_tensor::template dimension<1>();
|
||||
static constexpr std::size_t IN_WIDTH = input_tensor::template dimension<2>();
|
||||
|
||||
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 = input_inner_t<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
|
||||
|
||||
using weights_type = tensor<double, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||
using biases_type = tensor<double, OUT_CHANS>;
|
||||
|
||||
struct gradient final {
|
||||
using parent_type = inner;
|
||||
|
||||
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 = weights_type{};
|
||||
biases = biases_type{};
|
||||
}
|
||||
};
|
||||
|
||||
weights_type weights;
|
||||
biases_type biases;
|
||||
output_type output;
|
||||
|
||||
void dump(std::ostream& os) const {
|
||||
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size());
|
||||
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size());
|
||||
}
|
||||
|
||||
void load(std::istream& is) {
|
||||
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size());
|
||||
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size());
|
||||
}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {
|
||||
constexpr double fanIn = static_cast<double>(IN_CHANS * KernelSize * KernelSize);
|
||||
|
||||
const double scale = std::sqrt(2.0 / fanIn);
|
||||
|
||||
weights = decltype(weights)::random(dist);
|
||||
weights *= scale;
|
||||
biases = decltype(biases){};
|
||||
}
|
||||
|
||||
auto& forward(const input_type& input) {
|
||||
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) {
|
||||
double 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.get()[ic][iy][ix] * weights[oc][ic][ky][kx];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
output.get()[oc][oy][ox] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) {
|
||||
typename input_type::type backpropErr;
|
||||
|
||||
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 double err = prevErr[oc][oy][ox];
|
||||
|
||||
grad.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)) {
|
||||
|
||||
grad.weights[oc][ic][ky][kx] += input.get()[ic][iy][ix] * err;
|
||||
|
||||
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return backpropErr;
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {
|
||||
++grad.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;
|
||||
|
||||
grad.momentumWeights[oc][ic][ky][kx] =
|
||||
beta1 * grad.momentumWeights[oc][ic][ky][kx] + (1.0 - beta1) * avgGrad;
|
||||
grad.varianceWeights[oc][ic][ky][kx] =
|
||||
beta2 * grad.varianceWeights[oc][ic][ky][kx] + (1.0 - beta2) * avgGrad * avgGrad;
|
||||
|
||||
double momentumCorrected =
|
||||
grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time));
|
||||
double varianceCorrected =
|
||||
grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time));
|
||||
|
||||
weights[oc][ic][ky][kx] -=
|
||||
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double avgGrad = grad.biases[oc] / divisor;
|
||||
|
||||
grad.momentumBiases[oc] = beta1 * grad.momentumBiases[oc] + (1.0 - beta1) * avgGrad;
|
||||
grad.varianceBiases[oc] = beta2 * grad.varianceBiases[oc] + (1.0 - beta2) * avgGrad * avgGrad;
|
||||
|
||||
double momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time));
|
||||
double varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time));
|
||||
|
||||
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
|
||||
class maxpool_layer : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
|
||||
|
||||
using input_tensor = input_type::type;
|
||||
static_assert(input_tensor::RANK == 3);
|
||||
|
||||
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
|
||||
static constexpr std::size_t IN_HEIGHT = input_tensor::template dimension<1>();
|
||||
static constexpr std::size_t IN_WIDTH = input_tensor::template dimension<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 = input_inner_t<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
|
||||
output_type output;
|
||||
|
||||
struct gradient final {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {}
|
||||
|
||||
auto& forward(const input_type& input) {
|
||||
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) {
|
||||
double maxValue = input.get()[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.get()[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
|
||||
}
|
||||
}
|
||||
|
||||
output.get()[ch][oy][ox] = maxValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) {
|
||||
typename input_type::type backpropErr;
|
||||
|
||||
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;
|
||||
|
||||
double maxValue = input.get()[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 (input.get()[ch][yIdx][xIdx] > maxValue) {
|
||||
maxValue = input.get()[ch][yIdx][xIdx];
|
||||
maxY = yIdx;
|
||||
maxX = xIdx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
backpropErr[ch][maxY][maxX] += prevErr[ch][oy][ox];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return backpropErr;
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {}
|
||||
};
|
||||
};
|
||||
|
||||
class flatten_layer : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = input_type_s<NN, I>::type;
|
||||
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
|
||||
|
||||
using input_tensor = input_type::type;
|
||||
|
||||
static constexpr std::size_t FEATURES = input_tensor::SIZE;
|
||||
|
||||
using output_type = input_inner_t<dense_input<FEATURES>>;
|
||||
output_type output;
|
||||
|
||||
struct gradient final {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(const Dist& dist) {}
|
||||
|
||||
auto& forward(const input_type& input) {
|
||||
std::copy(input.get().begin(), input.get().end(), output.xs.data());
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const input_type& input, gradient& grad, Error prevErr) {
|
||||
typename input_type::type backpropErr;
|
||||
|
||||
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
|
||||
|
||||
return backpropErr;
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {}
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace cenet
|
||||
|
||||
#endif // CENET_LAYER_HPP
|
||||
Reference in New Issue
Block a user