refactor(network): separate optimizer state

This commit is contained in:
2026-11-22 12:03:04 +01:00
parent 2f24260cbf
commit 14292b1d97
7 changed files with 166 additions and 29 deletions
+1 -1
View File
@@ -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<cenet::optim::adam>();
for (std::size_t epoch = 0; epoch <= MAX_EPOCHS; ++epoch) {
shuffle_dataset(trainSet);
+54 -5
View File
@@ -7,6 +7,7 @@
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "cenet/layers/retained.hpp"
#include "cenet/optim/adam.hpp"
#include <cmath>
#include <iostream>
@@ -184,8 +185,50 @@ struct conv2d final : public layer_tag {
return backpropErr;
}
};
void apply(data<N, I>& data, double divisor, double rate) {
template <class N, std::size_t I, class Optim>
struct optim {
static_assert(false, "unsupported optimizer");
};
template <class N, std::size_t I>
struct optim<N, I, cenet::optim::adam> {
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
using input_type = typename traits::input_type;
static_assert(math::is_tensor_v<input_type>);
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<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
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;
@@ -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<N, I>&, double, double) {}
template <typename N, std::size_t I, class Optim>
struct optim {
void apply(data<N, I>&, grad<N, I>&, double, double) {}
};
};
@@ -377,8 +423,11 @@ struct flatten final : public layer_tag {
auto backward(const data<N, I>& data, R, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
}
};
void apply(data<N, I>&, double, double) {}
template <typename N, std::size_t I, class Optim>
struct optim {
void apply(data<N, I>&, grad<N, I>&, double, double) {}
};
};
+55 -13
View File
@@ -10,6 +10,7 @@
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "./retained.hpp"
#include "cenet/optim/adam.hpp"
#include <cmath>
#include <iostream>
@@ -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<Error>(prevErr).matmul(data.weights.transpose());
}
};
void apply(data<N, I>& data, double divisor, double rate) {
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 = 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 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 = 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>;
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;
@@ -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<Error>(prevErr) * retained *
(static_cast<typename output_type::value_type>(1) - retained);
}
};
void apply(data<N, I>&, double, double) {}
template <class N, std::size_t I, class Optim>
struct optim {
void apply(data<N, I>&, grad<N, I>&, double, double) {}
};
};
@@ -213,8 +252,11 @@ struct relu final : public layer_tag {
return std::forward<Error>(prevErr).apply(retained,
[](auto in, auto check) { return check > 0.0 ? in : 0.0; });
}
};
void apply(data<N, I>&, double, double) {}
template <class N, std::size_t I, class Optim>
struct optim {
void apply(data<N, I>&, grad<N, I>&, double, double) {}
};
};
+30 -8
View File
@@ -4,6 +4,7 @@
#include "./network_traits.hpp"
#include "cenet/layers/retained.hpp"
#include "cenet/math/expr.hpp"
#include "cenet/optim/sgd.hpp"
#include <cstddef>
#include <istream>
@@ -61,7 +62,6 @@ private:
}
}
private:
// TODO: pass in the optimizer
struct layers_grad_gen {
template <std::size_t I, typename LF, typename... LR>
struct impl {
@@ -76,7 +76,24 @@ private:
using type = typename impl<0, Layers...>::type;
};
template <class Optim>
struct layers_optim_gen {
template <std::size_t I, typename LF, typename... LR>
struct impl {
using type = decltype(std::tuple_cat(std::tuple<typename LF::template optim<network, I, Optim>>{},
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 optim<network, I, Optim>>;
};
using type = typename impl<0, Layers...>::type;
};
public:
template <class Optim = optim::sgd>
struct learning_state final {
friend class network;
@@ -132,12 +149,16 @@ public:
detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct
typename layers_grad_gen::type m_layers;
typename layers_optim_gen<Optim>::type m_optimizer;
};
public:
output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); }
template <class Optim>
output_type feed(input_type input, learning_state<Optim>& state) {
return feed_impl<0>(std::move(input), state);
}
private:
template <std::size_t I, typename Current>
auto feed_impl(Current&& current, learning_state& state) {
template <std::size_t I, typename Current, class Optim>
auto feed_impl(Current&& current, learning_state<Optim>& state) {
if constexpr (I == sizeof...(Layers)) {
return std::forward<Current>(current);
} else {
@@ -155,13 +176,14 @@ private:
}
}
public:
void apply(learning_state& state, double learningRate) {
template <class Optim>
void apply(learning_state<Optim>& 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>(state.m_layers).apply(at<I>(), state.count(), rate), ...);
template <std::size_t... I, class Optim>
void apply(learning_state<Optim>& state, double rate, std::index_sequence<I...>) {
(std::get<I>(state.m_optimizer).apply(at<I>(), std::get<I>(state.m_layers), state.count(), rate), ...);
}
public:
template <std::size_t I>
+12
View File
@@ -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
+12
View File
@@ -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
BIN
View File
Binary file not shown.