diff --git a/example/mnist.cpp b/example/mnist.cpp index 5e949e6..614b2b0 100644 --- a/example/mnist.cpp +++ b/example/mnist.cpp @@ -146,9 +146,9 @@ int main(void) { state->reset(); 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); - mnistNet->backward(loss, *state); + state->backward(*mnistNet, loss); } mnistNet->apply(*state, learningRate); } diff --git a/include/cenet/layers/convolutional.hpp b/include/cenet/layers/convolutional.hpp index bcd3508..0652c57 100644 --- a/include/cenet/layers/convolutional.hpp +++ b/include/cenet/layers/convolutional.hpp @@ -4,22 +4,22 @@ #include "../math/tensor_fwd.hpp" #include "../math/tensor_shape.hpp" #include "../math/tensor_traits.hpp" -#include "../network.hpp" #include "./layer_fwd.hpp" #include "./layer_traits.hpp" +#include "cenet/layers/retained.hpp" #include +#include namespace cenet { namespace layers { template -class conv2d final : public layer_tag { - template - friend class ::cenet::network; -private: +struct conv2d final : public layer_tag { + static constexpr auto retain = retain::Input; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; @@ -49,30 +49,9 @@ private: math::tensor, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>; using biases_type = math::tensor, OUT_CHANS>; - struct gradient final { - using parent_type = inner; - - 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(); - } - }; - 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()); @@ -94,8 +73,7 @@ private: biases.view().fill(); } - template - auto feed(Fwd&& fwd) { + auto feed(const input_type& input) { typename output_type::template with_storage output; for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { @@ -111,7 +89,7 @@ private: static_cast(Padding); if (iy >= 0 && iy < static_cast(IN_HEIGHT) && ix >= 0 && ix < static_cast(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); return output; } + }; + + template + struct grad final { + 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>; + + 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 - auto backward(gradient& grad, Error prevErr) { + auto backward(const data& data, const input_type& retained, Error prevErr) { typename input_type::template with_storage backpropErr; backpropErr.view().fill(); @@ -135,7 +157,7 @@ private: 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))); - grad.biases[oc] += err; + biases[oc] += err; for (std::size_t ic = 0; ic < IN_CHANS; ++ic) { for (std::size_t ky = 0; ky < KernelSize; ++ky) { @@ -149,9 +171,9 @@ private: if (iy >= 0 && iy < static_cast(IN_HEIGHT) && ix >= 0 && ix < static_cast(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; } - void apply_grad(gradient& grad, double divisor, double rate) { - ++grad.time; + void apply(data& data, double divisor, double rate) { + ++time; constexpr double beta1 = 0.9; constexpr double beta2 = 0.999; @@ -174,45 +196,42 @@ private: 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 = grad.weights[oc][ic][ky][kx] / divisor; + double avgGrad = weights[oc][ic][ky][kx] / divisor; - grad.momentumWeights[oc][ic][ky][kx] = - (beta1 * grad.momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad); - grad.varianceWeights[oc][ic][ky][kx] = - (beta2 * grad.varianceWeights[oc][ic][ky][kx]) + ((1.0 - beta2) * avgGrad * avgGrad); + momentumWeights[oc][ic][ky][kx] = + (beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad); + varianceWeights[oc][ic][ky][kx] = + (beta2 * varianceWeights[oc][ic][ky][kx]) + ((1.0 - beta2) * avgGrad * avgGrad); - auto momentumCorrected = - grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time)); - auto varianceCorrected = - grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time)); + auto momentumCorrected = momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, time)); + auto varianceCorrected = varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, time)); - weights[oc][ic][ky][kx] -= + data.weights[oc][ic][ky][kx] -= 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); - grad.varianceBiases[oc] = (beta2 * grad.varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad); + momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad); + varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad); - auto momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time)); - auto varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time)); + auto momentumCorrected = momentumBiases[oc] / (1.0 - std::pow(beta1, 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 -class maxpool final : public layer_tag { - template - friend class ::cenet::network; -private: +struct maxpool final : public layer_tag { + static constexpr auto retain = retain::Input; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; @@ -232,12 +251,6 @@ private: using output_type = math::tensor, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>; - input_type input; - - struct gradient final { - void reset() {} - }; - void dump(std::ostream& os) const {} void load(std::istream& is) {} @@ -245,7 +258,7 @@ private: template void fill_random(const Dist& dist) {} - auto feed(input_type&& input) { + auto feed(const input_type& input) { output_type output; for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { @@ -262,13 +275,29 @@ private: } } } - this->input = std::move(input); return output; } + }; + + template + struct grad final { + using traits = typename detail::layer_traits>; + + 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 - auto backward(gradient& grad, Error prevErr) { + auto backward(const data& data, const input_type& retained, Error prevErr) { input_type backpropErr; backpropErr.view().fill(); @@ -278,15 +307,15 @@ private: std::size_t maxY = oy * 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 kx = 0; kx < PoolSize; ++kx) { const std::size_t yIdx = (oy * Stride) + ky; const std::size_t xIdx = (ox * Stride) + kx; - if (input[ch][yIdx][xIdx] > maxValue) { - maxValue = input[ch][yIdx][xIdx]; + if (retained[ch][yIdx][xIdx] > maxValue) { + maxValue = retained[ch][yIdx][xIdx]; maxY = yIdx; maxX = xIdx; } @@ -302,16 +331,15 @@ private: return backpropErr; } - void apply_grad(gradient& grad, double divisor, double rate) {} + void apply(data&, double, double) {} }; }; -class flatten final : public layer_tag { - template - friend class ::cenet::network; -private: +struct flatten final : public layer_tag { + static constexpr auto retain = retain::None; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; @@ -324,10 +352,6 @@ private: using output_type = math::matrix; - struct gradient final { - void reset() {} - }; - void dump(std::ostream& os) const {} void load(std::istream& is) {} @@ -339,13 +363,22 @@ private: auto feed(Fwd&& fwd) { return std::forward(fwd).template reshape>(); } + }; - template - auto backward(gradient& grad, Error&& prevErr) { + template + struct grad final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + + void reset() {} + + template + auto backward(const data& data, R, Error&& prevErr) { return std::forward(prevErr).template reshape(); } - void apply_grad(gradient& grad, double divisor, double rate) {} + void apply(data&, double, double) {} }; }; diff --git a/mnist-conv.nn b/mnist-conv.nn index dc1bbf0..a360af2 100644 Binary files a/mnist-conv.nn and b/mnist-conv.nn differ