refactor: refactor convolutional too

This commit is contained in:
2026-11-19 16:13:33 +01:00
parent 6455bebb1f
commit e19b6b499d
3 changed files with 118 additions and 85 deletions
+2 -2
View File
@@ -146,9 +146,9 @@ int main(void) {
state->reset(); state->reset();
for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) { for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) {
auto output = std::move(mnistNet->feed(trainSet[i + j].xs)); auto output = mnistNet->feed(trainSet[i + j].xs, *state);
auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output); auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output);
mnistNet->backward(loss, *state); state->backward(*mnistNet, loss);
} }
mnistNet->apply(*state, learningRate); mnistNet->apply(*state, learningRate);
} }
+116 -83
View File
@@ -4,22 +4,22 @@
#include "../math/tensor_fwd.hpp" #include "../math/tensor_fwd.hpp"
#include "../math/tensor_shape.hpp" #include "../math/tensor_shape.hpp"
#include "../math/tensor_traits.hpp" #include "../math/tensor_traits.hpp"
#include "../network.hpp"
#include "./layer_fwd.hpp" #include "./layer_fwd.hpp"
#include "./layer_traits.hpp" #include "./layer_traits.hpp"
#include "cenet/layers/retained.hpp"
#include <cmath> #include <cmath>
#include <iostream>
namespace cenet { namespace cenet {
namespace layers { namespace layers {
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0> template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
class conv2d final : public layer_tag { struct conv2d final : public layer_tag {
template <typename Input, typename... Layers> static constexpr auto retain = retain::Input;
friend class ::cenet::network;
private:
template <class N, std::size_t I> template <class N, std::size_t I>
struct inner final { struct data final {
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>; using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
using input_type = typename traits::input_type; using input_type = typename traits::input_type;
@@ -49,30 +49,9 @@ private:
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>; 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>; using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
struct gradient final {
using parent_type = inner;
weights_type weights{}; weights_type weights{};
biases_type biases{}; biases_type biases{};
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 { 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*>(weights.data()), sizeof(value_type) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size()); os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
@@ -94,8 +73,7 @@ private:
biases.view().fill(); biases.view().fill();
} }
template <typename Fwd> auto feed(const input_type& input) {
auto feed(Fwd&& fwd) {
typename output_type::template with_storage<math::heap_storage_tag> output; typename output_type::template with_storage<math::heap_storage_tag> output;
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) { for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
@@ -111,7 +89,7 @@ private:
static_cast<std::ptrdiff_t>(Padding); static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 && if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) { ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
value += fwd[ic][iy][ix] * weights[oc][ic][ky][kx]; value += input[ic][iy][ix] * weights[oc][ic][ky][kx];
} }
} }
} }
@@ -121,12 +99,56 @@ private:
} }
} }
} }
retained = std::forward<Fwd>(fwd);
return output; return output;
} }
};
template <class N, std::size_t I>
struct grad final {
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>;
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.view().fill();
biases.view().fill();
}
template <typename Error> template <typename Error>
auto backward(gradient& grad, Error prevErr) { auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
typename input_type::template with_storage<math::heap_storage_tag> backpropErr; typename input_type::template with_storage<math::heap_storage_tag> backpropErr;
backpropErr.view().fill(); backpropErr.view().fill();
@@ -135,7 +157,7 @@ private:
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
const auto err = prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(oc, oy, ox))); const auto err = prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(oc, oy, ox)));
grad.biases[oc] += err; biases[oc] += err;
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) { for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) { for (std::size_t ky = 0; ky < KernelSize; ++ky) {
@@ -149,9 +171,9 @@ private:
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 && if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) { ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
grad.weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err; weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err;
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err; backpropErr[ic][iy][ix] += data.weights[oc][ic][ky][kx] * err;
} }
} }
} }
@@ -163,8 +185,8 @@ private:
return backpropErr; return backpropErr;
} }
void apply_grad(gradient& grad, double divisor, double rate) { void apply(data<N, I>& data, double divisor, double rate) {
++grad.time; ++time;
constexpr double beta1 = 0.9; constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999; constexpr double beta2 = 0.999;
@@ -174,45 +196,42 @@ private:
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) { for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) { for (std::size_t ky = 0; ky < KernelSize; ++ky) {
for (std::size_t kx = 0; kx < KernelSize; ++kx) { for (std::size_t kx = 0; kx < KernelSize; ++kx) {
double avgGrad = grad.weights[oc][ic][ky][kx] / divisor; double avgGrad = weights[oc][ic][ky][kx] / divisor;
grad.momentumWeights[oc][ic][ky][kx] = momentumWeights[oc][ic][ky][kx] =
(beta1 * grad.momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad); (beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad);
grad.varianceWeights[oc][ic][ky][kx] = varianceWeights[oc][ic][ky][kx] =
(beta2 * grad.varianceWeights[oc][ic][ky][kx]) + ((1.0 - beta2) * avgGrad * avgGrad); (beta2 * varianceWeights[oc][ic][ky][kx]) + ((1.0 - beta2) * avgGrad * avgGrad);
auto momentumCorrected = auto momentumCorrected = momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, time));
grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time)); auto varianceCorrected = varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, time));
auto varianceCorrected =
grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time));
weights[oc][ic][ky][kx] -= data.weights[oc][ic][ky][kx] -=
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon); rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
} }
} }
} }
auto avgGrad = grad.biases[oc] / divisor; auto avgGrad = biases[oc] / divisor;
grad.momentumBiases[oc] = (beta1 * grad.momentumBiases[oc]) + ((1.0 - beta1) * avgGrad); momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad);
grad.varianceBiases[oc] = (beta2 * grad.varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad); varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad);
auto momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time)); auto momentumCorrected = momentumBiases[oc] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time)); auto varianceCorrected = varianceBiases[oc] / (1.0 - std::pow(beta2, time));
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon); data.biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
} }
} }
}; };
}; };
template <std::size_t PoolSize = 2, std::size_t Stride = 2> template <std::size_t PoolSize = 2, std::size_t Stride = 2>
class maxpool final : public layer_tag { struct maxpool final : public layer_tag {
template <typename Input, typename... Layers> static constexpr auto retain = retain::Input;
friend class ::cenet::network;
private:
template <class N, std::size_t I> template <class N, std::size_t I>
struct inner final { struct data final {
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>; using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
using input_type = typename traits::input_type; using input_type = typename traits::input_type;
@@ -232,12 +251,6 @@ private:
using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>; using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
input_type input;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {} void dump(std::ostream& os) const {}
void load(std::istream& is) {} void load(std::istream& is) {}
@@ -245,7 +258,7 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto feed(input_type&& input) { auto feed(const input_type& input) {
output_type output; output_type output;
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) { for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
@@ -262,13 +275,29 @@ private:
} }
} }
} }
this->input = std::move(input);
return output; return output;
} }
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
using input_type = typename traits::input_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 constexpr std::size_t OUT_CHANS = IN_CHANS;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
void reset() {}
template <typename Error> template <typename Error>
auto backward(gradient& grad, Error prevErr) { auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
input_type backpropErr; input_type backpropErr;
backpropErr.view().fill(); backpropErr.view().fill();
@@ -278,15 +307,15 @@ private:
std::size_t maxY = oy * Stride; std::size_t maxY = oy * Stride;
std::size_t maxX = ox * Stride; std::size_t maxX = ox * Stride;
auto maxValue = input[ch][maxY][maxX]; auto maxValue = retained[ch][maxY][maxX];
for (std::size_t ky = 0; ky < PoolSize; ++ky) { for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) { for (std::size_t kx = 0; kx < PoolSize; ++kx) {
const std::size_t yIdx = (oy * Stride) + ky; const std::size_t yIdx = (oy * Stride) + ky;
const std::size_t xIdx = (ox * Stride) + kx; const std::size_t xIdx = (ox * Stride) + kx;
if (input[ch][yIdx][xIdx] > maxValue) { if (retained[ch][yIdx][xIdx] > maxValue) {
maxValue = input[ch][yIdx][xIdx]; maxValue = retained[ch][yIdx][xIdx];
maxY = yIdx; maxY = yIdx;
maxX = xIdx; maxX = xIdx;
} }
@@ -302,16 +331,15 @@ private:
return backpropErr; return backpropErr;
} }
void apply_grad(gradient& grad, double divisor, double rate) {} void apply(data<N, I>&, double, double) {}
}; };
}; };
class flatten final : public layer_tag { struct flatten final : public layer_tag {
template <typename Input, typename... Layers> static constexpr auto retain = retain::None;
friend class ::cenet::network;
private:
template <class N, std::size_t I> template <class N, std::size_t I>
struct inner final { struct data final {
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>; using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
using input_type = typename traits::input_type; using input_type = typename traits::input_type;
@@ -324,10 +352,6 @@ private:
using output_type = math::matrix<value_type, 1, FEATURES>; using output_type = math::matrix<value_type, 1, FEATURES>;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {} void dump(std::ostream& os) const {}
void load(std::istream& is) {} void load(std::istream& is) {}
@@ -339,13 +363,22 @@ private:
auto feed(Fwd&& fwd) { auto feed(Fwd&& fwd) {
return std::forward<Fwd>(fwd).template reshape<math::shape_of<1, FEATURES>>(); return std::forward<Fwd>(fwd).template reshape<math::shape_of<1, FEATURES>>();
} }
};
template <typename Error> template <class N, std::size_t I>
auto backward(gradient& grad, Error&& prevErr) { struct grad final {
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
using input_type = typename traits::input_type;
void reset() {}
template <typename Error, typename R>
auto backward(const data<N, I>& data, R, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>(); return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
} }
void apply_grad(gradient& grad, double divisor, double rate) {} void apply(data<N, I>&, double, double) {}
}; };
}; };
BIN
View File
Binary file not shown.