diff --git a/example/mnist.cpp b/example/mnist.cpp index 0ec54d6..5e949e6 100644 --- a/example/mnist.cpp +++ b/example/mnist.cpp @@ -1,3 +1,5 @@ +#include "cenet/layers/convolutional.hpp" +#include "cenet/layers/dense.hpp" #include "cenet/loss/mse.hpp" #include @@ -13,28 +15,28 @@ #include #include -using network_type = cenet::network, - cenet::conv2d_layer<8, 3, 1, 1>, - cenet::relu_layer, - cenet::maxpool_layer<>, - cenet::conv2d_layer<16, 3, 1, 1>, - cenet::relu_layer, - cenet::maxpool_layer<>, - cenet::flatten_layer, - cenet::dense_layer<10>, - cenet::sigmoid_layer>; +using network_type = cenet::network, + cenet::layers::conv2d<8, 3, 1, 1>, + cenet::layers::relu, + cenet::layers::maxpool<>, + cenet::layers::conv2d<16, 3, 1, 1>, + cenet::layers::relu, + cenet::layers::maxpool<>, + cenet::layers::flatten, + cenet::layers::dense<10>, + cenet::layers::sigmoid>; static std::uniform_real_distribution<> dist(-1, 1); struct data { - cenet::tensor xs; - cenet::mat<1, 10, float> ys; + cenet::math::tensor xs{}; + cenet::math::matrix ys{}; }; using dataset = std::vector; template -static std::size_t col_largest_idx(const cenet::mat_col& col) { +static std::size_t col_largest_idx(const cenet::math::tensor_view& col) { std::size_t maxIdx = 0; std::remove_cv_t max = col[0]; for (std::size_t i = 1; i < N; ++i) { @@ -89,6 +91,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) { std::uint8_t label = 0; labels.read(reinterpret_cast(&label), sizeof(label)); + set[i].ys.view().fill(); set[i].ys[0][label] = 1.0; } @@ -108,10 +111,10 @@ int main(void) { static constexpr const char* NETWORK_PATH = "./mnist-conv.nn"; std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary); - if (file.is_open()) - mnistNet->load_network(file); - else - mnistNet->fill_random(dist); + // if (file.is_open()) + // mnistNet->load_network(file); + // else + mnistNet->fill_random(dist); dataset trainSet = load_dataset("./mnist/train-labels-idx1-ubyte", "./mnist/train-images-idx3-ubyte"); if (trainSet.empty()) return 1; @@ -123,7 +126,7 @@ int main(void) { std::size_t patienceCounter = 0; static constexpr std::size_t MAX_PATIENCE = 10; - static constexpr std::size_t MAX_EPOCHS = 1000; + static constexpr std::size_t MAX_EPOCHS = 2; static constexpr std::size_t BATCH_SIZE = 64; static constexpr std::size_t EPL = 1; // Epochs Per Log @@ -140,10 +143,10 @@ int main(void) { auto epochStart = std::chrono::high_resolution_clock::now(); for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) { - if (i > 0) state->reset(); + state->reset(); for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) { - auto output = mnistNet->feed(trainSet[i + j].xs); + auto output = std::move(mnistNet->feed(trainSet[i + j].xs)); auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output); mnistNet->backward(loss, *state); } diff --git a/include/cenet/layers/convolutional.hpp b/include/cenet/layers/convolutional.hpp new file mode 100644 index 0000000..e32ee6d --- /dev/null +++ b/include/cenet/layers/convolutional.hpp @@ -0,0 +1,346 @@ +#ifndef CENET_LAYERS_CONVOLUTIONAL_HPP +#define CENET_LAYERS_CONVOLUTIONAL_HPP + +#include "../layer.hpp" +#include "../math/tensor_fwd.hpp" +#include "../math/tensor_shape.hpp" +#include "../math/tensor_traits.hpp" +#include "../network.hpp" + +namespace cenet { +namespace layers { + +template +class conv2d final : public layer_info { + template + friend class ::cenet::network; +private: + template + struct inner final { + using input_type = typename input_type_s::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 output_type = math::tensor, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>; + + using weights_type = + 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()); + } + + 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) { + constexpr value_type fanIn = static_cast(IN_CHANS * KernelSize * KernelSize); + + const value_type scale = std::sqrt(6.0 / fanIn); + + weights.view().fill_random(dist); + weights = weights.apply([scale](auto val) { return val * scale; }); + biases.view().fill(); + } + + template + auto feed(Fwd&& fwd) { + 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) { + for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { + auto value = biases[oc]; + + 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) { + std::ptrdiff_t iy = static_cast((oy * Stride) + ky) - + static_cast(Padding); + std::ptrdiff_t ix = static_cast((ox * Stride) + kx) - + 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]; + } + } + } + } + + output[oc][oy][ox] = value; + } + } + } + retained = std::forward(fwd); + return output; + } + + template + auto backward(gradient& grad, Error prevErr) { + typename input_type::template with_storage backpropErr; + backpropErr.view().fill(); + + for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) { + for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { + 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; + + 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) { + const std::ptrdiff_t iy = static_cast((oy * Stride) + ky) - + static_cast(Padding); + + const std::ptrdiff_t ix = static_cast((ox * Stride) + kx) - + static_cast(Padding); + + 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; + + backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err; + } + } + } + } + } + } + } + + return backpropErr; + } + + 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 oc = 0; oc < OUT_CHANS; ++oc) { + 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; + + 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; + + 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)); + + weights[oc][ic][ky][kx] -= + rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon); + } + } + } + + auto avgGrad = grad.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; + + auto momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time)); + auto varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time)); + + biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon); + } + } + }; +}; + +template +class maxpool : public layer_info { + template + friend class ::cenet::network; +private: + template + struct inner final { + using input_type = typename input_type_s::type; + static_assert(math::is_tensor_v); + static_assert(input_type::shape_type::rank == 3); + static_assert(!input_type::traits::dynamic, "dynamic input to maxpool is currently unsupported"); + + 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 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; + + 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) {} + + template + void fill_random(const Dist& dist) {} + + auto feed(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) { + for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { + auto maxValue = input[ch][oy * Stride][ox * Stride]; + + for (std::size_t ky = 0; ky < PoolSize; ++ky) { + for (std::size_t kx = 0; kx < PoolSize; ++kx) { + maxValue = std::max(maxValue, input[ch][(oy * Stride) + ky][(ox * Stride) + kx]); + } + } + + output[ch][oy][ox] = maxValue; + } + } + } + this->input = std::move(input); + + return output; + } + + template + auto backward(gradient& grad, Error prevErr) { + input_type backpropErr; + backpropErr.view().fill(); + + for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) { + for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { + for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { + std::size_t maxY = oy * Stride; + std::size_t maxX = ox * Stride; + + auto maxValue = input[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]; + maxY = yIdx; + maxX = xIdx; + } + } + } + + backpropErr[ch][maxY][maxX] += + prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(ch, oy, ox))); + } + } + } + + return backpropErr; + } + + void apply_grad(gradient& grad, double divisor, double rate) {} + }; +}; + +class flatten final : public layer_info { + template + friend class ::cenet::network; +private: + template + struct inner final { + using input_type = typename input_type_s::type; + static_assert(math::is_tensor_v); + static_assert(!input_type::traits::dynamic, "dynamic input to flatten is currently unsupported"); + + using value_type = typename input_type::value_type; + + static constexpr auto FEATURES = input_type::shape_type::size; + + using output_type = math::matrix; + + struct gradient final { + 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 std::forward(fwd).template reshape>(); + } + + template + auto backward(gradient& grad, Error&& prevErr) { + return std::forward(prevErr).template reshape(); + } + + void apply_grad(gradient& grad, double divisor, double rate) {} + }; +}; + +} // namespace layers +} // namespace cenet + +#endif // CENET_LAYERS_CONVOLUTIONAL_HPP diff --git a/mnist-conv.nn b/mnist-conv.nn index fb0b1f8..b76347f 100644 Binary files a/mnist-conv.nn and b/mnist-conv.nn differ