Files
cenet/include/cenet/layers/dense.hpp
T

266 lines
9.3 KiB
C++

/**
* The "dense" layer class.
*/
#ifndef CENET_LAYERS_DENSE_HPP
#define CENET_LAYERS_DENSE_HPP
#include "../optim/adam.hpp"
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "./retained.hpp"
#include <cmath>
#include <iostream>
#include <tulip/tensor.hpp>
namespace cenet {
namespace layers {
template <std::size_t Features>
struct dense 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<dense, N, I>>;
using input_type = typename traits::input_type;
using value_type = typename input_type::value_type;
using output_type = tulip::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
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) {
value_type scale = std::sqrt(2.0 / static_cast<value_type>(input_cols));
weights.view().fill_random(dist);
weights = weights.apply([scale](auto val) { return val * scale; });
biases.view().fill();
}
template <typename Fwd>
auto feed(Fwd&& fwd) {
return std::forward<Fwd>(fwd).matmul(weights) + biases;
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
using input_type = typename traits::input_type;
using value_type = typename input_type::value_type;
using output_type = tulip::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
weights_type weights;
biases_type biases;
void reset() {
weights.view().fill();
biases.view().fill();
}
template <typename Error>
auto backward(const data<N, I>& data, const input_type& retained, Error&& prevErr) {
weights += retained.transpose().matmul(prevErr);
biases += prevErr;
return std::forward<Error>(prevErr).matmul(data.weights.transpose());
}
};
template <class N, std::size_t I, class Optim>
struct optim {
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
using input_type = typename traits::input_type;
using value_type = typename input_type::value_type;
using output_type = tulip::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
weights_type weigths;
biases_type biases;
void apply(data<N, I>& data, grad<N, I>& grad, double divisor, double rate) {
data.weights -= (grad.weights / divisor) * rate;
data.biases -= (grad.biases / divisor) * rate;
}
};
template <class N, std::size_t I>
struct optim<N, I, cenet::optim::adam> {
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
using input_type = typename traits::input_type;
using value_type = typename input_type::value_type;
using output_type = tulip::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
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 row = 0; row < input_cols; ++row) {
for (std::size_t col = 0; col < Features; ++col) {
auto avgGrad = grad.weights[row][col] / divisor;
momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad);
varianceWeights[row][col] =
(beta2 * varianceWeights[row][col]) + ((1.0 - beta2) * (avgGrad * avgGrad));
auto momentumCorrected = momentumWeights[row][col] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceWeights[row][col] / (1.0 - std::pow(beta2, time));
data.weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
}
for (std::size_t col = 0; col < Features; ++col) {
double avgGrad = grad.biases[0][col] / divisor;
momentumBiases[0][col] = (beta1 * momentumBiases[0][col]) + ((1.0 - beta1) * avgGrad);
varianceBiases[0][col] = (beta2 * varianceBiases[0][col]) + ((1.0 - beta2) * (avgGrad * avgGrad));
auto momentumCorrected = momentumBiases[0][col] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceBiases[0][col] / (1.0 - std::pow(beta2, time));
data.biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
}
};
};
struct sigmoid final : public layer_tag {
static constexpr auto retain = retain::Output;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<sigmoid, N, I>>;
using input_type = typename traits::input_type;
using output_type = input_type;
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).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<sigmoid, N, I>>;
using input_type = typename traits::input_type;
using output_type = input_type;
void reset() {}
template <typename Error>
auto backward(const data<N, I>&, const output_type& retained, Error&& prevErr) const {
return std::forward<Error>(prevErr) * retained *
(static_cast<typename output_type::value_type>(1) - retained);
}
};
template <class N, std::size_t I, class Optim>
struct optim {
void apply(data<N, I>&, grad<N, I>&, double, double) {}
};
};
struct relu 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<relu, N, I>>;
using input_type = typename traits::input_type;
using output_type = input_type;
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).apply([](auto in) { return in > 0.0 ? in : 0.0; });
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<relu, N, I>>;
using input_type = typename traits::input_type;
void reset() {}
template <typename Error>
auto backward(const data<N, I>&, const input_type& retained, Error&& prevErr) const {
return std::forward<Error>(prevErr).apply(retained,
[](auto in, auto check) { return check > 0.0 ? in : 0.0; });
}
};
template <class 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_DENSE_HPP