refactor: move backward to learning_state
This commit is contained in:
@@ -6,23 +6,23 @@
|
||||
#define CENET_LAYERS_DENSE_HPP
|
||||
|
||||
#include "../math/tensor_fwd.hpp"
|
||||
#include "../network.hpp"
|
||||
#include "./layer_fwd.hpp"
|
||||
#include "./layer_traits.hpp"
|
||||
#include "./retained.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
|
||||
namespace cenet {
|
||||
namespace layers {
|
||||
|
||||
// TODO: redesign the layer interface after porting the old layers
|
||||
template <std::size_t Features>
|
||||
class dense final : public layer_tag {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class ::cenet::network;
|
||||
private:
|
||||
struct dense final : public layer_tag {
|
||||
static constexpr auto retain = retain::Input;
|
||||
|
||||
template <class N, std::size_t I>
|
||||
struct inner final {
|
||||
struct data final {
|
||||
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
@@ -34,31 +34,9 @@ private:
|
||||
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
|
||||
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
|
||||
|
||||
struct gradient final {
|
||||
using parent_type = inner;
|
||||
|
||||
weights_type weights;
|
||||
biases_type biases;
|
||||
|
||||
// TODO: move Adam into optimizer state
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
weights_type weights;
|
||||
biases_type biases;
|
||||
|
||||
typename input_type::template with_storage<math::inline_storage_tag> retained;
|
||||
|
||||
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());
|
||||
@@ -79,20 +57,49 @@ private:
|
||||
|
||||
template <typename Fwd>
|
||||
auto feed(Fwd&& fwd) {
|
||||
retained = std::forward<Fwd>(fwd);
|
||||
return retained.matmul(weights) + biases;
|
||||
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 = math::matrix<value_type, 1, Features>;
|
||||
|
||||
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||
|
||||
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
|
||||
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
|
||||
|
||||
weights_type weights;
|
||||
biases_type biases;
|
||||
|
||||
// TODO: move Adam into optimizer state
|
||||
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(gradient& grad, Error&& prevErr) {
|
||||
grad.weights += retained.transpose().matmul(prevErr);
|
||||
grad.biases += prevErr;
|
||||
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(weights.transpose());
|
||||
return std::forward<Error>(prevErr).matmul(data.weights.transpose());
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {
|
||||
++grad.time;
|
||||
void apply(data<N, I>& data, double divisor, double rate) {
|
||||
++time;
|
||||
|
||||
constexpr double beta1 = 0.9;
|
||||
constexpr double beta2 = 0.999;
|
||||
@@ -100,53 +107,44 @@ private:
|
||||
|
||||
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;
|
||||
auto avgGrad = 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));
|
||||
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 = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time));
|
||||
auto varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time));
|
||||
auto momentumCorrected = momentumWeights[row][col] / (1.0 - std::pow(beta1, time));
|
||||
auto varianceCorrected = varianceWeights[row][col] / (1.0 - std::pow(beta2, time));
|
||||
|
||||
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||
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;
|
||||
double avgGrad = 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));
|
||||
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 = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time));
|
||||
auto varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time));
|
||||
auto momentumCorrected = momentumBiases[0][col] / (1.0 - std::pow(beta1, time));
|
||||
auto varianceCorrected = varianceBiases[0][col] / (1.0 - std::pow(beta2, time));
|
||||
|
||||
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||
data.biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
class sigmoid final : public layer_tag {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class ::cenet::network;
|
||||
private:
|
||||
struct sigmoid final : public layer_tag {
|
||||
static constexpr auto retain = retain::Output;
|
||||
|
||||
template <class N, std::size_t I>
|
||||
struct inner final {
|
||||
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;
|
||||
|
||||
typename output_type::template with_storage<math::inline_storage_tag> retained;
|
||||
|
||||
struct gradient {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
@@ -156,36 +154,39 @@ private:
|
||||
|
||||
template <typename Fwd>
|
||||
auto feed(Fwd&& fwd) {
|
||||
return retained = std::forward<Fwd>(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
|
||||
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(gradient& grad, Error&& prevErr) const {
|
||||
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);
|
||||
}
|
||||
|
||||
void apply_grad(gradient&, double, double) {}
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
class relu final : public layer_tag {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class ::cenet::network;
|
||||
private:
|
||||
struct relu final : public layer_tag {
|
||||
static constexpr auto retain = retain::Input;
|
||||
|
||||
template <class N, std::size_t I>
|
||||
struct inner final {
|
||||
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;
|
||||
|
||||
typename input_type::template with_storage<math::inline_storage_tag> retained;
|
||||
|
||||
struct gradient {
|
||||
void reset() {}
|
||||
};
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
void load(std::istream& is) {}
|
||||
@@ -195,17 +196,25 @@ private:
|
||||
|
||||
template <typename Fwd>
|
||||
auto feed(Fwd&& fwd) {
|
||||
retained = std::forward<Fwd>(fwd);
|
||||
return retained.apply([](auto in) { return in > 0.0 ? in : 0.0; });
|
||||
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(gradient& grad, Error&& prevErr) const {
|
||||
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; });
|
||||
}
|
||||
|
||||
void apply_grad(gradient&, double, double) {}
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#ifndef CENET_LAYERS_LAYER_TRAITS_HPP
|
||||
#define CENET_LAYERS_LAYER_TRAITS_HPP
|
||||
|
||||
#include "layer_fwd.hpp"
|
||||
#include "../network_fwd.hpp"
|
||||
#include "./layer_fwd.hpp"
|
||||
#include "cenet/network_traits.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
@@ -20,13 +22,17 @@ template <typename T>
|
||||
static constexpr auto is_layer_v = is_layer<T>::value;
|
||||
|
||||
template <typename N, std::size_t I>
|
||||
struct layer_input {
|
||||
using type = typename N::template layer<I - 1>::output_type;
|
||||
struct layer_input {};
|
||||
|
||||
template <typename In, typename... LR, std::size_t I>
|
||||
struct layer_input<network<In, LR...>, I> {
|
||||
using type = typename ::cenet::detail::
|
||||
layer_for_t<::cenet::detail::layer_at_t<I - 1, network<In, LR...>>, network<In, LR...>, I - 1>::output_type;
|
||||
};
|
||||
|
||||
template <typename N>
|
||||
struct layer_input<N, 0> {
|
||||
using type = typename N::input_type;
|
||||
template <typename In, typename... LR>
|
||||
struct layer_input<network<In, LR...>, 0> {
|
||||
using type = In;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#ifndef CENET_LAYERS_RETAINED_HPP
|
||||
#define CENET_LAYERS_RETAINED_HPP
|
||||
|
||||
namespace cenet {
|
||||
namespace layers {
|
||||
|
||||
enum class retain {
|
||||
None,
|
||||
Input,
|
||||
Output,
|
||||
};
|
||||
|
||||
} // namespace layers
|
||||
} // namespace cenet
|
||||
|
||||
#endif // CENET_LAYERS_RETAINED_HPP
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef CENET_MATH_EXPR_HPP
|
||||
#define CENET_MATH_EXPR_HPP
|
||||
|
||||
#include "cenet/math/tensor_traits.hpp"
|
||||
#include "ops.hpp"
|
||||
#include "type_traits.hpp"
|
||||
|
||||
@@ -28,31 +29,63 @@ struct ops_provider {
|
||||
return { self(), std::forward<R>(rhs) };
|
||||
}
|
||||
|
||||
template <typename R>
|
||||
binary_expression<CRTP, R, ops::matmul> matmul(R&& rhs) const {
|
||||
if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<R>(rhs) };
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
unary_expression<CRTP, ops::apply<Func>> apply(Func&& func) {
|
||||
if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
unary_expression<CRTP, ops::apply<Func>> apply(Func&& func) const {
|
||||
if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
template <typename R, typename Func>
|
||||
binary_expression<CRTP, R, ops::apply<Func>> apply(R&& rhs, Func&& func) {
|
||||
if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<R>(rhs), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
template <typename R, typename Func>
|
||||
binary_expression<CRTP, R, ops::apply<Func>> apply(R&& rhs, Func&& func) const {
|
||||
if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<R>(rhs), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
unary_expression<CRTP, ops::transpose> transpose() {
|
||||
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self() };
|
||||
}
|
||||
|
||||
unary_expression<CRTP, ops::transpose> transpose() const {
|
||||
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self() };
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
unary_expression<CRTP, ops::reshape<S>> reshape() {
|
||||
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self() };
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
unary_expression<CRTP, ops::reshape<S>> reshape() const {
|
||||
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self() };
|
||||
}
|
||||
private:
|
||||
decltype(auto) self() & { return reinterpret_cast<CRTP&>(*this); }
|
||||
decltype(auto) self() && { return reinterpret_cast<CRTP&&>(*this); }
|
||||
|
||||
decltype(auto) self() const& { return reinterpret_cast<const CRTP&>(*this); }
|
||||
decltype(auto) self() const&& { return reinterpret_cast<const CRTP&&>(*this); }
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
@@ -152,6 +185,17 @@ binary_expression<L, R, Op> operator/(L&& lhs, R&& rhs) {
|
||||
return { std::forward<L>(lhs), std::forward<R>(rhs) };
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
constexpr decltype(auto) eval(T&& fwd) {
|
||||
if constexpr (detail::is_expression_v<T>) {
|
||||
auto tensor = tensor_from_shape<decltype(fwd.coeff(std::declval<std::size_t>()))>(fwd.shape());
|
||||
tensor = std::forward<T>(fwd);
|
||||
return tensor;
|
||||
} else {
|
||||
return std::forward<T>(fwd);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
|
||||
|
||||
@@ -111,11 +111,9 @@ public:
|
||||
tensor& operator=(E&& exprFwd) {
|
||||
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
|
||||
|
||||
if constexpr (!traits::inline_storage) {
|
||||
if constexpr (traits::dynamic) {
|
||||
if constexpr (traits::dynamic) {
|
||||
if (m_shape != exprFwd.shape()) {
|
||||
set_dimensions(exprFwd.shape());
|
||||
} else {
|
||||
m_items = new value_type[traits::size];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef CENET_MATH_TENSOR_TRAITS_HPP
|
||||
#define CENET_MATH_TENSOR_TRAITS_HPP
|
||||
|
||||
#include "cenet/math/tensor_shape.hpp"
|
||||
#include "cenet/math/type_traits.hpp"
|
||||
#include "tensor_fwd.hpp"
|
||||
|
||||
#include <type_traits>
|
||||
@@ -90,6 +92,19 @@ struct tensor_with_storage<inline_storage_tag> {
|
||||
using type = tensor<inline_storage<detach_storage_t<T>>, Dims...>;
|
||||
};
|
||||
|
||||
template <typename T, typename Shape>
|
||||
struct tensor_from_shape {};
|
||||
|
||||
template <typename T, std::size_t... Dims>
|
||||
struct tensor_from_shape<T, static_shape<Dims...>> {
|
||||
using type = tensor<T, Dims...>;
|
||||
};
|
||||
|
||||
template <typename T, std::size_t... Dims>
|
||||
struct tensor_from_shape<T, dynamic_shape<Dims...>> {
|
||||
using type = tensor<T, Dims...>;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template <typename T>
|
||||
@@ -115,6 +130,15 @@ struct tensor_traits<tensor<T, Dims...>> {
|
||||
using with_storage_t = typename detail::tensor_with_storage<ST>::template type<T, Dims...>;
|
||||
};
|
||||
|
||||
template <typename T, typename Shape>
|
||||
constexpr decltype(auto) tensor_from_shape(const Shape& shape) {
|
||||
typename detail::tensor_from_shape<T, remove_cvref_t<Shape>>::type tensor;
|
||||
if constexpr (!detail::is_static_shape_v<Shape>) {
|
||||
tensor.set_dimensions(shape);
|
||||
}
|
||||
return tensor;
|
||||
}
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
|
||||
|
||||
+118
-64
@@ -1,6 +1,10 @@
|
||||
#ifndef CENET_NETWORK_HPP
|
||||
#define CENET_NETWORK_HPP
|
||||
|
||||
#include "./network_traits.hpp"
|
||||
#include "cenet/layers/retained.hpp"
|
||||
#include "cenet/math/expr.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
@@ -12,36 +16,11 @@ namespace cenet {
|
||||
template <typename Input, typename... Layers>
|
||||
class network {
|
||||
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<network, 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:
|
||||
template <std::size_t I>
|
||||
using layer = std::tuple_element_t<I, layer_types>;
|
||||
public:
|
||||
using input_type = Input;
|
||||
using output_type = typename output_layer_type::output_type;
|
||||
using traits = network_traits<network>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
using output_type = typename traits::output_type;
|
||||
public:
|
||||
const output_type& get_output() const { return m_output; }
|
||||
public:
|
||||
@@ -53,14 +32,14 @@ public:
|
||||
private:
|
||||
template <std::size_t... I>
|
||||
void dump_network(std::ostream& os, std::index_sequence<I...>) const {
|
||||
(get_layer<I>().dump(os), ...);
|
||||
(at<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), ...);
|
||||
(at<I>().load(is), ...);
|
||||
}
|
||||
public:
|
||||
template <typename Dist>
|
||||
@@ -70,7 +49,7 @@ public:
|
||||
private:
|
||||
template <typename Dist, std::size_t... I>
|
||||
void fill_random(const Dist& dist, std::index_sequence<I...>) {
|
||||
(get_layer<I>().fill_random(dist), ...);
|
||||
(at<I>().fill_random(dist), ...);
|
||||
}
|
||||
public:
|
||||
output_type feed(input_type input) { return feed_impl<0>(std::move(input)); }
|
||||
@@ -80,76 +59,151 @@ private:
|
||||
if constexpr (I == sizeof...(Layers)) {
|
||||
return std::forward<Current>(current);
|
||||
} else {
|
||||
return feed_impl<I + 1>(get_layer<I>().feed(std::forward<Current>(current)));
|
||||
return feed_impl<I + 1>(at<I>().feed(std::forward<Current>(current)));
|
||||
}
|
||||
}
|
||||
private:
|
||||
// TODO: pass in the optimizer
|
||||
struct layers_grad_gen {
|
||||
template <std::size_t I, typename LF, typename... LR>
|
||||
struct impl {
|
||||
using type = decltype(std::tuple_cat(std::tuple<typename LF::template grad<network, I>>{},
|
||||
std::declval<typename impl<I + 1, LR...>::type>()));
|
||||
};
|
||||
|
||||
template <std::size_t I, typename LF>
|
||||
struct impl<I, LF> {
|
||||
using type = std::tuple<typename LF::template grad<network, I>>;
|
||||
};
|
||||
|
||||
using type = typename impl<0, Layers...>::type;
|
||||
};
|
||||
public:
|
||||
struct learning_state final {
|
||||
friend class network;
|
||||
|
||||
void reset() {
|
||||
m_count = 0;
|
||||
reset(std::make_index_sequence<sizeof...(Layers)>{});
|
||||
}
|
||||
|
||||
template <std::size_t I, typename = std::enable_if_t<(I < sizeof...(Layers))>>
|
||||
decltype(auto) get() {
|
||||
template <std::size_t I>
|
||||
decltype(auto) at() {
|
||||
return std::get<I>(m_layers);
|
||||
}
|
||||
|
||||
void increment() { ++m_count; }
|
||||
|
||||
auto count() const { return m_count; }
|
||||
|
||||
template <typename Loss>
|
||||
void backward(const network& network, const Loss& loss) {
|
||||
at<0>().backward(network.template at<0>(),
|
||||
retained_for<0>(),
|
||||
backward_chain<sizeof...(Layers) - 1>(network, loss.gradient));
|
||||
++m_count;
|
||||
}
|
||||
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, typename Error>
|
||||
auto backward_chain(const network& network, Error&& error) {
|
||||
if constexpr (I != 0) {
|
||||
return backward_chain<I - 1>(network,
|
||||
at<I>().backward(network.template at<I>(), retained_for<I>(), std::forward<Error>(error)));
|
||||
} else {
|
||||
return std::forward<Error>(error);
|
||||
}
|
||||
}
|
||||
|
||||
template <std::size_t... I>
|
||||
struct gen<std::index_sequence<I...>> {
|
||||
using type = std::tuple<typename Layers::template inner<network, I>::gradient...>;
|
||||
};
|
||||
struct empty {};
|
||||
|
||||
template <std::size_t I>
|
||||
decltype(auto) retained_for() const {
|
||||
if constexpr (detail::layer_retains_v<network, I, layers::retain::Input>) {
|
||||
return std::get<I>(m_retained);
|
||||
} else if constexpr (detail::layer_retains_v<network, I, layers::retain::Output>) {
|
||||
return std::get<I + 1>(m_retained);
|
||||
} else {
|
||||
return empty{};
|
||||
}
|
||||
}
|
||||
private:
|
||||
std::size_t m_count = 0;
|
||||
|
||||
typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
|
||||
detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct
|
||||
typename layers_grad_gen::type m_layers;
|
||||
};
|
||||
public:
|
||||
template <typename Loss, typename LState>
|
||||
void backward(const Loss& loss, LState& state) {
|
||||
get_layer<0>().backward(state.template get<0>(), backward_chain<sizeof...(Layers) - 1>(state, loss.gradient));
|
||||
state.increment();
|
||||
}
|
||||
output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); }
|
||||
private:
|
||||
template <std::size_t I, typename LState, typename ErrorType>
|
||||
auto backward_chain(LState& state, ErrorType error) {
|
||||
if constexpr (I != 0) {
|
||||
auto next = get_layer<I>().backward(state.template get<I>(), error);
|
||||
return backward_chain<I - 1>(state, next);
|
||||
template <std::size_t I, typename Current>
|
||||
auto feed_impl(Current&& current, learning_state& state) {
|
||||
if constexpr (I == sizeof...(Layers)) {
|
||||
return std::forward<Current>(current);
|
||||
} else {
|
||||
return error;
|
||||
if constexpr (detail::layer_retains_v<network, I, layers::retain::Input>) {
|
||||
std::get<I>(state.m_retained) = current;
|
||||
}
|
||||
|
||||
auto next = at<I>().feed(std::forward<Current>(current));
|
||||
|
||||
if constexpr (detail::layer_retains_v<network, I, layers::retain::Output>) {
|
||||
std::get<I + 1>(state.m_retained) = next;
|
||||
}
|
||||
|
||||
return feed_impl<I + 1>(std::move(next), state);
|
||||
}
|
||||
}
|
||||
public:
|
||||
void apply(learning_state& state, double rate) {
|
||||
apply(state, rate, std::make_index_sequence<sizeof...(Layers)>{});
|
||||
void apply(learning_state& state, double learningRate) {
|
||||
apply(state, learningRate, 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(state.template get<I>(), state.count(), rate), ...);
|
||||
(std::get<I>(state.m_layers).apply(at<I>(), state.count(), rate), ...);
|
||||
}
|
||||
public:
|
||||
void train(const input_type& input, const output_type& expected, double learningRate) {
|
||||
learning_state state;
|
||||
backward(input, expected, state);
|
||||
apply(state, learningRate);
|
||||
template <std::size_t I>
|
||||
decltype(auto) at() {
|
||||
return std::get<I>(m_layers);
|
||||
}
|
||||
|
||||
template <std::size_t I>
|
||||
decltype(auto) at() const {
|
||||
return std::get<I>(m_layers);
|
||||
}
|
||||
private:
|
||||
layer_types m_layers;
|
||||
output_type m_output;
|
||||
struct layers_data_gen {
|
||||
template <std::size_t I, typename LF, typename... LR>
|
||||
struct impl {
|
||||
using type = decltype(std::tuple_cat(std::tuple<typename LF::template data<network, I>>{},
|
||||
std::declval<typename impl<I + 1, LR...>::type>()));
|
||||
};
|
||||
|
||||
template <std::size_t I, typename LF>
|
||||
struct impl<I, LF> {
|
||||
using type = std::tuple<typename LF::template data<network, I>>;
|
||||
};
|
||||
|
||||
template <std::size_t I, std::size_t J, typename LF, typename... LR>
|
||||
struct at : at<I - 1, J, LR...> {};
|
||||
|
||||
template <std::size_t J, typename LF, typename... LR>
|
||||
struct at<0, J, LF, LR...> {
|
||||
using type = typename LF::template data<network, J>;
|
||||
};
|
||||
|
||||
using type = typename impl<0, Layers...>::type;
|
||||
};
|
||||
public:
|
||||
template <std::size_t I>
|
||||
using layer = typename layers_data_gen::template at<I, I, Layers...>::type;
|
||||
private:
|
||||
typename layers_data_gen::type m_layers;
|
||||
output_type m_output;
|
||||
};
|
||||
|
||||
} // namespace cenet
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
#ifndef CENET_NETWORK_FWD_HPP
|
||||
#define CENET_NETWORK_FWD_HPP
|
||||
|
||||
namespace cenet {
|
||||
|
||||
template <typename I, typename... Layers>
|
||||
class network;
|
||||
|
||||
}
|
||||
|
||||
#endif // CENET_NETWORK_FWD_HPP
|
||||
@@ -0,0 +1,102 @@
|
||||
#ifndef CENET_NETWORK_TRAITS_HPP
|
||||
#define CENET_NETWORK_TRAITS_HPP
|
||||
|
||||
#include "./layers/retained.hpp"
|
||||
#include "./network_fwd.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace cenet {
|
||||
|
||||
namespace detail {
|
||||
|
||||
template <std::size_t At, typename T>
|
||||
struct layer_at {};
|
||||
|
||||
template <std::size_t At, typename I, typename LF, typename... LR>
|
||||
struct layer_at<At, network<I, LF, LR...>> {
|
||||
static_assert(At <= sizeof...(LR));
|
||||
using type = typename layer_at<At - 1, network<I, LR...>>::type;
|
||||
};
|
||||
|
||||
template <typename I, typename LF, typename... LR>
|
||||
struct layer_at<0, network<I, LF, LR...>> {
|
||||
using type = LF;
|
||||
};
|
||||
|
||||
template <std::size_t At, typename T>
|
||||
using layer_at_t = typename layer_at<At, T>::type;
|
||||
|
||||
template <typename L, typename N, std::size_t I>
|
||||
using layer_for_t = typename L::template data<N, I>;
|
||||
|
||||
template <typename N, std::size_t At, layers::retain Retain>
|
||||
struct layer_retains : std::conditional_t<layer_at_t<At, N>::retain == Retain, std::true_type, std::false_type> {};
|
||||
|
||||
template <typename N, std::size_t At, layers::retain Retain>
|
||||
inline constexpr auto layer_retains_v = layer_retains<N, At, Retain>::value;
|
||||
|
||||
template <typename N>
|
||||
struct network_retained {};
|
||||
|
||||
template <typename In, typename... Ls>
|
||||
struct network_retained<network<In, Ls...>> {
|
||||
private:
|
||||
using network_type = network<In, Ls...>;
|
||||
|
||||
struct empty {};
|
||||
|
||||
template <std::size_t... Is>
|
||||
static constexpr auto generate(std::index_sequence<Is...>) {
|
||||
if constexpr (layer_retains_v<network_type, 0, layers::retain::Input>) {
|
||||
return std::tuple_cat(std::tuple<In>{}, generate_layer<Is>()...);
|
||||
} else {
|
||||
return std::tuple_cat(std::tuple<empty>{}, generate_layer<Is>()...);
|
||||
}
|
||||
}
|
||||
|
||||
template <std::size_t I>
|
||||
static constexpr auto generate_layer() {
|
||||
if constexpr (I + 1 >= sizeof...(Ls)) { // Last layer
|
||||
if constexpr (layer_retains_v<network_type, I, layers::retain::Output>) {
|
||||
return std::tuple<typename layer_for_t<layer_at_t<I, network_type>, network_type, I>::output_type>{};
|
||||
} else {
|
||||
return std::tuple<empty>{};
|
||||
}
|
||||
} else {
|
||||
if constexpr (layer_retains_v<network_type, I, layers::retain::Output> ||
|
||||
layer_retains_v<network_type, I + 1, layers::retain::Input>) {
|
||||
return std::tuple<typename layer_for_t<layer_at_t<I, network_type>, network_type, I>::output_type>{};
|
||||
} else {
|
||||
return std::tuple<empty>{};
|
||||
}
|
||||
}
|
||||
}
|
||||
public:
|
||||
using type = decltype(generate(std::make_index_sequence<sizeof...(Ls)>{}));
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
using network_retained_t = typename network_retained<T>::type;
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template <typename T>
|
||||
struct network_traits {};
|
||||
|
||||
template <typename I, typename... Layers>
|
||||
struct network_traits<network<I, Layers...>> {
|
||||
using network_type = network<I, Layers...>;
|
||||
|
||||
using input_type = I;
|
||||
using output_layer = detail::layer_at_t<sizeof...(Layers) - 1, network_type>;
|
||||
using output_type =
|
||||
typename detail::layer_for_t<output_layer, network<I, Layers...>, sizeof...(Layers) - 1>::output_type;
|
||||
};
|
||||
|
||||
} // namespace cenet
|
||||
|
||||
#endif // CENET_NETWORK_TRAITS_HPP
|
||||
Reference in New Issue
Block a user