From 4b782a6619012009088f183dfa43c39c4873fd8c Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Sun, 1 Nov 2026 13:20:40 +0100 Subject: [PATCH] refactor(nn): start migrating layers to cenet::math --- example/xor.cpp | 40 ++++---- include/cenet/layers/dense.hpp | 166 +++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 18 deletions(-) create mode 100644 include/cenet/layers/dense.hpp diff --git a/example/xor.cpp b/example/xor.cpp index 06ee946..121a5a0 100644 --- a/example/xor.cpp +++ b/example/xor.cpp @@ -1,4 +1,6 @@ +#include "cenet/layers/dense.hpp" #include "cenet/loss/mse.hpp" +#include "cenet/math/tensor_fwd.hpp" #include #include @@ -17,11 +19,11 @@ int main(void) { }; // network net; - using network_type = cenet::network, - cenet::dense_layer<2>, - cenet::sigmoid_layer, - cenet::dense_layer<1>, - cenet::sigmoid_layer>; + using network_type = cenet::network, 1, 2>, + cenet::layers::dense<2>, + cenet::layers::sigmoid, + cenet::layers::dense<1>, + cenet::layers::sigmoid>; network_type xorNet; static constexpr const char* NETWORK_PATH = "./xor.nn"; @@ -32,36 +34,38 @@ int main(void) { else xorNet.fill_random(dist); - static constexpr double EPSILON = 0.5; + static constexpr double learning_late = 0.001; std::size_t gen = 0; + network_type::learning_state state; while (gen <= 10'000'000) { - for (std::size_t i = 0; i < 4; ++i) { - cenet::mat<1, 2, float> xs; - xs[0][0] = static_cast(i & 1); - xs[0][1] = static_cast(i > 1); + state.reset(); - auto output = xorNet.feed(xs); + for (std::size_t i = 0; i < 4; ++i) { + cenet::math::matrix, 1, 2> xs; + xs.coeff(0) = static_cast(i & 1); + xs.coeff(1) = static_cast(i > 1); + + auto output = std::move(xorNet.feed(xs)); auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output); - network_type::learning_state state; xorNet.backward(loss, state); - xorNet.apply(state, EPSILON); + xorNet.apply(state, learning_late); } double acc = 0.0; for (std::size_t i = 0; i < 4; ++i) { - cenet::mat<1, 2, float> xs; - xs[0][0] = static_cast(i & 1); - xs[0][1] = static_cast(i > 1); + cenet::math::matrix, 1, 2> xs; + xs.coeff(0) = static_cast(i & 1); + xs.coeff(1) = static_cast(i > 1); - float yHat = xorNet.feed(xs)[0][0]; + float yHat = xorNet.feed(xs).coeff(0); float error = yHat - s_trainData[i]; if ((gen % 1000) == 0) { - std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n"; + std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n"; } acc += error * error; diff --git a/include/cenet/layers/dense.hpp b/include/cenet/layers/dense.hpp new file mode 100644 index 0000000..a05e9d3 --- /dev/null +++ b/include/cenet/layers/dense.hpp @@ -0,0 +1,166 @@ +/** + * The "dense" layer class. + */ + +#ifndef CENET_LAYERS_DENSE_HPP +#define CENET_LAYERS_DENSE_HPP + +#include "../layer.hpp" +#include "../math/tensor_fwd.hpp" +#include "../network.hpp" + +namespace cenet { +namespace layers { + +// TODO: redesign the layer interface after porting the old layers +template +class dense final : public layer_info { + template + friend class ::cenet::network; +private: + template + struct inner final { + using input_type = typename input_type_s::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>; + + 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 retained; + + void dump(std::ostream& os) const { + os.write(reinterpret_cast(weights.data()), sizeof(value_type) * weights.size()); + os.write(reinterpret_cast(biases.data()), sizeof(value_type) * biases.size()); + } + + void load(std::istream& is) { + is.read(reinterpret_cast(weights.data()), sizeof(value_type) * weights.size()); + is.read(reinterpret_cast(biases.data()), sizeof(value_type) * biases.size()); + } + + template + void fill_random(const Dist& dist) { + value_type scale = std::sqrt(2.0 / static_cast(input_cols)); + weights.view().fill_random(dist); + weights = weights.apply([scale](auto val) { return val * scale; }); + biases.view().fill(); + } + + template + auto feed(Fwd&& fwd) { + retained = std::forward(fwd); + return retained.matmul(weights) + biases; + } + + template + auto backward(gradient& grad, Error&& prevErr) { + grad.weights += retained.transpose().matmul(prevErr); + grad.biases += prevErr; + + return std::forward(prevErr).matmul(weights.transpose()); + } + + 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_cols; ++row) { + for (std::size_t col = 0; col < Features; ++col) { + auto 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); + + 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)); + + 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; + + 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); + + 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)); + + biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); + } + } + }; +}; + +class sigmoid final : public layer_info { + template + friend class ::cenet::network; +private: + template + struct inner final { + using input_type = typename input_type_s::type; + using output_type = input_type; + + typename output_type::template with_storage retained; + + struct gradient { + void reset() {} + }; + + void dump(std::ostream& os) const {} + + void load(std::istream& is) {} + + template + void fill_random(const Dist& dist) {} + + template + auto feed(Fwd&& fwd) { + return retained = std::forward(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); }); + } + + template + auto backward(gradient& grad, Error&& prevErr) const { + return std::forward(prevErr) * retained * + (static_cast(1) - retained); + } + + void apply_grad(gradient&, double, double) {} + }; +}; + +} // namespace layers +} // namespace cenet + +#endif // CENET_LAYERS_DENSE_HPP