diff --git a/example/mnist.cpp b/example/mnist.cpp index 614b2b0..324d080 100644 --- a/example/mnist.cpp +++ b/example/mnist.cpp @@ -135,7 +135,7 @@ int main(void) { std::ofstream saveFile(NETWORK_PATH, std::ios::out | std::ios::binary); - network_type::learning_state* state = new network_type::learning_state(); + auto* state = new network_type::learning_state(); for (std::size_t epoch = 0; epoch <= MAX_EPOCHS; ++epoch) { shuffle_dataset(trainSet); diff --git a/include/cenet/layers/convolutional.hpp b/include/cenet/layers/convolutional.hpp index 0652c57..beb5b30 100644 --- a/include/cenet/layers/convolutional.hpp +++ b/include/cenet/layers/convolutional.hpp @@ -7,6 +7,7 @@ #include "./layer_fwd.hpp" #include "./layer_traits.hpp" #include "cenet/layers/retained.hpp" +#include "cenet/optim/adam.hpp" #include #include @@ -184,8 +185,50 @@ struct conv2d final : public layer_tag { return backpropErr; } + }; - void apply(data& data, double divisor, double rate) { + template + struct optim { + static_assert(false, "unsupported optimizer"); + }; + + template + struct optim { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + static_assert(math::is_tensor_v); + 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 = + math::tensor, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>; + using biases_type = math::tensor, OUT_CHANS>; + + std::size_t time = 0; + + weights_type momentumWeights{}; + biases_type momentumBiases{}; + weights_type varianceWeights{}; + biases_type varianceBiases{}; + + void apply(data& data, grad& grad, double divisor, double rate) { ++time; constexpr double beta1 = 0.9; @@ -196,7 +239,7 @@ struct conv2d final : public layer_tag { 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 = weights[oc][ic][ky][kx] / divisor; + double avgGrad = grad.weights[oc][ic][ky][kx] / divisor; momentumWeights[oc][ic][ky][kx] = (beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad); @@ -212,7 +255,7 @@ struct conv2d final : public layer_tag { } } - auto avgGrad = biases[oc] / divisor; + 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); @@ -330,8 +373,11 @@ struct maxpool final : public layer_tag { return backpropErr; } + }; - void apply(data&, double, double) {} + template + struct optim { + void apply(data&, grad&, double, double) {} }; }; @@ -377,8 +423,11 @@ struct flatten final : public layer_tag { auto backward(const data& data, R, Error&& prevErr) { return std::forward(prevErr).template reshape(); } + }; - void apply(data&, double, double) {} + template + struct optim { + void apply(data&, grad&, double, double) {} }; }; diff --git a/include/cenet/layers/dense.hpp b/include/cenet/layers/dense.hpp index 41578c1..e26600c 100644 --- a/include/cenet/layers/dense.hpp +++ b/include/cenet/layers/dense.hpp @@ -10,6 +10,7 @@ #include "./layer_fwd.hpp" #include "./layer_traits.hpp" #include "./retained.hpp" +#include "cenet/optim/adam.hpp" #include #include @@ -77,14 +78,6 @@ struct dense final : public layer_tag { 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(); @@ -97,8 +90,51 @@ struct dense final : public layer_tag { return std::forward(prevErr).matmul(data.weights.transpose()); } + }; - void apply(data& data, double divisor, double rate) { + template + struct optim { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + using value_type = typename input_type::value_type; + using output_type = math::matrix; + + static constexpr auto input_cols = input_type::shape_type::template sget<1>(); + + using weights_type = math::matrix, input_cols, Features>; + using biases_type = math::matrix, 1, Features>; + + weights_type weigths; + biases_type biases; + + void apply(data& data, grad& grad, double divisor, double rate) { + data.weights -= (grad.weights / divisor) * rate; + data.biases -= (grad.biases / divisor) * rate; + } + }; + + template + struct optim { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + using value_type = typename input_type::value_type; + using output_type = math::matrix; + + static constexpr auto input_cols = input_type::shape_type::template sget<1>(); + + using weights_type = math::matrix, input_cols, Features>; + using biases_type = math::matrix, 1, Features>; + + std::size_t time = 0; + + weights_type momentumWeights; + biases_type momentumBiases; + weights_type varianceWeights; + biases_type varianceBiases; + + void apply(data& data, grad& grad, double divisor, double rate) { ++time; constexpr double beta1 = 0.9; @@ -107,7 +143,7 @@ struct dense final : public layer_tag { for (std::size_t row = 0; row < input_cols; ++row) { for (std::size_t col = 0; col < Features; ++col) { - auto avgGrad = weights[row][col] / divisor; + auto avgGrad = grad.weights[row][col] / divisor; momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad); varianceWeights[row][col] = @@ -121,7 +157,7 @@ struct dense final : public layer_tag { } for (std::size_t col = 0; col < Features; ++col) { - double avgGrad = biases[0][col] / divisor; + 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)); @@ -172,8 +208,11 @@ struct sigmoid final : public layer_tag { return std::forward(prevErr) * retained * (static_cast(1) - retained); } + }; - void apply(data&, double, double) {} + template + struct optim { + void apply(data&, grad&, double, double) {} }; }; @@ -213,8 +252,11 @@ struct relu final : public layer_tag { return std::forward(prevErr).apply(retained, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); } + }; - void apply(data&, double, double) {} + template + struct optim { + void apply(data&, grad&, double, double) {} }; }; diff --git a/include/cenet/network.hpp b/include/cenet/network.hpp index 48ec15b..c818323 100644 --- a/include/cenet/network.hpp +++ b/include/cenet/network.hpp @@ -4,6 +4,7 @@ #include "./network_traits.hpp" #include "cenet/layers/retained.hpp" #include "cenet/math/expr.hpp" +#include "cenet/optim/sgd.hpp" #include #include @@ -61,7 +62,6 @@ private: } } private: - // TODO: pass in the optimizer struct layers_grad_gen { template struct impl { @@ -76,7 +76,24 @@ private: using type = typename impl<0, Layers...>::type; }; + + template + struct layers_optim_gen { + template + struct impl { + using type = decltype(std::tuple_cat(std::tuple>{}, + std::declval::type>())); + }; + + template + struct impl { + using type = std::tuple>; + }; + + using type = typename impl<0, Layers...>::type; + }; public: + template struct learning_state final { friend class network; @@ -130,14 +147,18 @@ public: private: std::size_t m_count = 0; - detail::network_retained_t m_retained; // TODO: move retained state to its own struct - typename layers_grad_gen::type m_layers; + detail::network_retained_t m_retained; // TODO: move retained state to its own struct + typename layers_grad_gen::type m_layers; + typename layers_optim_gen::type m_optimizer; }; public: - output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); } + template + output_type feed(input_type input, learning_state& state) { + return feed_impl<0>(std::move(input), state); + } private: - template - auto feed_impl(Current&& current, learning_state& state) { + template + auto feed_impl(Current&& current, learning_state& state) { if constexpr (I == sizeof...(Layers)) { return std::forward(current); } else { @@ -155,13 +176,14 @@ private: } } public: - void apply(learning_state& state, double learningRate) { + template + void apply(learning_state& state, double learningRate) { apply(state, learningRate, std::make_index_sequence{}); } private: - template - void apply(learning_state& state, double rate, std::index_sequence) { - (std::get(state.m_layers).apply(at(), state.count(), rate), ...); + template + void apply(learning_state& state, double rate, std::index_sequence) { + (std::get(state.m_optimizer).apply(at(), std::get(state.m_layers), state.count(), rate), ...); } public: template diff --git a/include/cenet/optim/adam.hpp b/include/cenet/optim/adam.hpp new file mode 100644 index 0000000..d4b5800 --- /dev/null +++ b/include/cenet/optim/adam.hpp @@ -0,0 +1,12 @@ +#ifndef CENET_OPTIM_ADAM_HPP +#define CENET_OPTIM_ADAM_HPP + +namespace cenet { +namespace optim { + +class adam {}; + +} // namespace optim +} // namespace cenet + +#endif // CENET_OPTIM_ADAM_HPP diff --git a/include/cenet/optim/sgd.hpp b/include/cenet/optim/sgd.hpp new file mode 100644 index 0000000..e1a4ddd --- /dev/null +++ b/include/cenet/optim/sgd.hpp @@ -0,0 +1,12 @@ +#ifndef CENET_OPTIM_SGD_HPP +#define CENET_OPTIM_SGD_HPP + +namespace cenet { +namespace optim { + +class sgd {}; + +} // namespace optim +} // namespace cenet + +#endif // CENET_OPTIM_SGD_HPP diff --git a/mnist-conv.nn b/mnist-conv.nn index 996a730..a4760cf 100644 Binary files a/mnist-conv.nn and b/mnist-conv.nn differ