Files
cenet/include/nn.hpp
T

321 lines
10 KiB
C++

#ifndef NN_HPP
#define NN_HPP
#include "mat.hpp"
#include <cmath>
#include <cstddef>
#include <istream>
#include <ostream>
#include <tuple>
#include <type_traits>
#include <utility>
enum class layer_type {
Dense,
};
struct layer_input {
static constexpr std::uint32_t DENSE_TAG = 0x444E5345;
};
template <std::size_t Features>
class dense_input : public layer_input {
template <typename Input, typename... Layers>
friend class nn;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = DENSE_TAG;
static constexpr std::size_t FEATURES = Features;
using type = mat<1, FEATURES>;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<type, Args...>>>
inner(Args&&... args)
: xs(std::forward<Args>(args)...) {}
operator type&() { return xs; }
operator const type&() const { return xs; }
type& get() { return xs; }
const type& get() const { return xs; }
type xs;
};
};
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 nn;
private:
template <class NN, std::size_t I>
struct inner final {
static constexpr layer_type TYPE = layer_type::Dense;
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;
static double sigmoid(double input) { return 1 / (1 + std::exp(-input)); }
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) {
output = (input.get() * weights) + biases;
for (std::size_t i = 0; i < OUTPUT_FEATURES; ++i) {
output.get()[0][i] = sigmoid(output.get()[0][i]);
}
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
grad.weights += input.get().transpose() * prevErr;
grad.biases += prevErr;
auto backpropErr = prevErr * weights.transpose();
if constexpr (I > 0) {
return backpropErr.hadamard(input.get().hadamard(1.0 - input.get()));
} else {
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 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);
}
}
};
};
template <typename Input, typename... Layers>
class nn {
friend class layer_info;
private:
template <typename Seq>
struct layer_types_gen {};
template <std::size_t... I>
struct layer_types_gen<std::index_sequence<I...>> {
using type = std::tuple<typename Layers::template inner<nn, I>...>;
};
using layer_types = typename layer_types_gen<std::make_index_sequence<sizeof...(Layers)>>::type;
using output_layer_type = std::tuple_element_t<sizeof...(Layers) - 1, layer_types>;
template <std::size_t I>
using layer_input_t = typename std::tuple_element_t<I, layer_types>::input_type;
private:
template <std::size_t I>
auto& get_layer() {
return std::get<I>(m_layers);
}
template <std::size_t I>
const auto& get_layer() const {
return std::get<I>(m_layers);
}
public:
using input_type = Input::inner;
using output_type = output_layer_type::output_type;
public:
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; }
public:
void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence<sizeof...(Layers)>{}); }
private:
template <std::size_t... I>
void dump_network(std::ostream& os, std::index_sequence<I...>) const {
(get_layer<I>().dump(os), ...);
}
public:
void load_network(std::istream& is) { load_network(is, std::make_index_sequence<sizeof...(Layers)>{}); }
private:
template <std::size_t... I>
void load_network(std::istream& is, std::index_sequence<I...>) {
(get_layer<I>().load(is), ...);
}
public:
template <typename Dist>
void fill_random(const Dist& dist) {
fill_random(dist, std::make_index_sequence<sizeof...(Layers)>{});
}
private:
template <typename Dist, std::size_t... I>
void fill_random(const Dist& dist, std::index_sequence<I...>) {
(get_layer<I>().fill_random(dist), ...);
}
public:
const output_type& feed(const input_type& input) {
feed<sizeof...(Layers) - 1>(input);
return get_layer<sizeof...(Layers) - 1>().output;
}
private:
template <std::size_t I>
auto feed(const input_type& input) {
if constexpr (I == 0) {
return get_layer<I>().forward(input);
} else {
return get_layer<I>().forward(feed<I - 1>(input));
}
}
public:
struct learning_state final {
friend class nn;
void reset() {
m_count = 0;
reset(std::make_index_sequence<sizeof...(Layers)>{});
}
private:
template <std::size_t... I>
void reset(std::index_sequence<I...>) {
(std::get<I>(m_layers).reset(), ...);
}
private:
template <typename Seq>
struct gen {};
template <std::size_t... I>
struct gen<std::index_sequence<I...>> {
using type = std::tuple<typename Layers::template inner<nn, I>::gradient...>;
};
private:
std::size_t m_count = 0;
gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
};
public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) {
feed(input);
auto outputErr = (get_output().get() - expected).hadamard(get_output()).hadamard(1.0 - get_output().get());
get_layer<0>().backward(input,
std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
state.m_count += 1;
}
private:
template <std::size_t I, typename ErrorType>
auto backprop_chain(learning_state& state, ErrorType error) {
if constexpr (I != 0) {
auto next = get_layer<I>().backward(get_layer<I - 1>().output, std::get<I>(state.m_layers), error);
return backprop_chain<I - 1>(state, next);
} else {
return error;
}
}
public:
void apply(learning_state& state, double rate) {
apply(state, rate, std::make_index_sequence<sizeof...(Layers)>{});
}
private:
template <std::size_t... I>
void apply(learning_state& state, double rate, std::index_sequence<I...>) {
(std::get<I>(m_layers).apply_grad(std::get<I>(state.m_layers), state.m_count, rate), ...);
}
public:
void train(const input_type& input, const output_type& expected, double learningRate) {
learning_state state;
backprop(input, expected, state);
apply(state, learningRate);
}
private:
layer_types m_layers;
};
#endif // NN_HPP