From 490661ebc06dbd2af1b78efb9414f8eb837c5969 Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Sun, 25 Oct 2026 15:55:07 +0100 Subject: [PATCH] refactor: add type parameter to layer inputs --- example/mnist.cpp | 12 +++--- example/xor.cpp | 18 ++++----- include/cenet/input.hpp | 10 +++-- include/cenet/layer.hpp | 83 +++++++++++++++++++++++----------------- include/cenet/mat.hpp | 3 +- include/cenet/tensor.hpp | 2 + 6 files changed, 72 insertions(+), 56 deletions(-) diff --git a/example/mnist.cpp b/example/mnist.cpp index 36a84ff..5fc6076 100644 --- a/example/mnist.cpp +++ b/example/mnist.cpp @@ -11,7 +11,7 @@ #include #include -using network_type = cenet::network, +using network_type = cenet::network, cenet::conv2d_layer<8, 3, 1, 1>, cenet::relu_layer, cenet::maxpool_layer<>, @@ -25,8 +25,8 @@ using network_type = cenet::network, static std::uniform_real_distribution<> dist(-1, 1); struct data { - cenet::tensor xs; - cenet::mat<1, 10> ys; + cenet::tensor xs; + cenet::mat<1, 10, float> ys; }; using dataset = std::vector; @@ -81,7 +81,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) { std::uint8_t pixel = 0; images.read(reinterpret_cast(&pixel), sizeof(pixel)); - set[i].xs[0][row][col] = static_cast(pixel) / 255.0; + set[i].xs[0][row][col] = static_cast(pixel) / 255.0F; } } @@ -157,8 +157,8 @@ int main(void) { const auto& output = mnistNet->feed(validationSet[i].xs); for (std::size_t j = 0; j < 10; ++j) { - double diff = output.get()[0][j] - validationSet[i].ys[0][j]; - totalLoss += diff * diff; + float diff = output.get()[0][j] - validationSet[i].ys[0][j]; + totalLoss += diff * diff; } if (col_largest_idx(output.get()[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits; diff --git a/example/xor.cpp b/example/xor.cpp index 6205cc8..ef31bd3 100644 --- a/example/xor.cpp +++ b/example/xor.cpp @@ -7,7 +7,7 @@ static std::uniform_real_distribution<> dist(-1, 1); int main(void) { - static constexpr double s_trainData[4] = { + static constexpr float s_trainData[4] = { 0, // 0 ^ 0 1, // 1 ^ 0 1, // 0 ^ 1 @@ -36,9 +36,9 @@ int main(void) { while (gen <= 10'000'000) { for (std::size_t i = 0; i < 4; ++i) { - cenet::mat<1, 2> xs; - xs[0][0] = static_cast(i & 1); - xs[0][1] = static_cast(i > 1); + cenet::mat<1, 2, float> xs; + xs[0][0] = static_cast(i & 1); + xs[0][1] = static_cast(i > 1); xorNet.train(xs, s_trainData[i], EPSILON); } @@ -46,12 +46,12 @@ int main(void) { double acc = 0.0; for (std::size_t i = 0; i < 4; ++i) { - cenet::mat<1, 2> xs; - xs[0][0] = static_cast(i & 1); - xs[0][1] = static_cast(i > 1); + cenet::mat<1, 2, float> xs; + xs[0][0] = static_cast(i & 1); + xs[0][1] = static_cast(i > 1); - double yHat = xorNet.feed(xs).get()[0][0]; - double error = yHat - s_trainData[i]; + float yHat = xorNet.feed(xs).get()[0][0]; + float error = yHat - s_trainData[i]; if ((gen % 1000) == 0) { std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n"; diff --git a/include/cenet/input.hpp b/include/cenet/input.hpp index 81005cc..692ba1a 100644 --- a/include/cenet/input.hpp +++ b/include/cenet/input.hpp @@ -14,7 +14,7 @@ struct layer_input { static constexpr std::uint32_t TENSOR_TAG = 0x544E5352; }; -template +template class dense_input : public layer_input { template friend class network; @@ -26,7 +26,8 @@ private: static constexpr std::size_t FEATURES = Features; - using type = mat<1, FEATURES>; + using inner_type = T; + using type = mat<1, FEATURES, T>; template >> inner(Args&&... args) @@ -42,7 +43,7 @@ private: }; }; -template +template class tensor_input : public layer_input { template friend class network; @@ -52,7 +53,8 @@ private: struct inner final { static constexpr std::uint32_t TAG = TENSOR_TAG; - using type = tensor; + using inner_type = T; + using type = tensor; template >> inner(Args&&... args) diff --git a/include/cenet/layer.hpp b/include/cenet/layer.hpp index 3b0048b..bd20b64 100644 --- a/include/cenet/layer.hpp +++ b/include/cenet/layer.hpp @@ -26,7 +26,7 @@ protected: using input_inner_t = typename T::inner; }; -template +template class dense_layer final : public layer_info { template friend class network; @@ -36,13 +36,13 @@ private: using input_type = input_type_s::type; static_assert(input_type::TAG == layer_input::DENSE_TAG); - using output_type = input_inner_t>; + using output_type = input_inner_t>; static constexpr std::size_t INPUT_FEATURES = input_type::FEATURES; static constexpr std::size_t OUTPUT_FEATURES = Features; - using weights_type = mat; - using biases_type = mat<1, OUTPUT_FEATURES>; + using weights_type = mat; + using biases_type = mat<1, OUTPUT_FEATURES, T>; struct gradient final { using parent_type = inner; @@ -68,20 +68,20 @@ private: output_type output; void dump(std::ostream& os) const { - os.write(reinterpret_cast(weights.data()), sizeof(double) * weights.size()); - os.write(reinterpret_cast(biases.data()), sizeof(double) * biases.size()); + os.write(reinterpret_cast(weights.data()), sizeof(T) * weights.size()); + os.write(reinterpret_cast(biases.data()), sizeof(T) * biases.size()); } void load(std::istream& is) { - is.read(reinterpret_cast(weights.data()), sizeof(double) * weights.size()); - is.read(reinterpret_cast(biases.data()), sizeof(double) * biases.size()); + is.read(reinterpret_cast(weights.data()), sizeof(T) * weights.size()); + is.read(reinterpret_cast(biases.data()), sizeof(T) * biases.size()); } template void fill_random(const Dist& dist) { - double scale = std::sqrt(2.0 / static_cast(INPUT_FEATURES)); - weights = decltype(weights)::random(dist) * scale; - biases = decltype(biases)::random(dist) * scale; + T scale = std::sqrt(2.0 / static_cast(INPUT_FEATURES)); + weights = decltype(weights)::random(dist) * scale; + biases = decltype(biases)::random(dist) * scale; } auto& forward(const input_type& input) { return output = (input.get() * weights) + biases; } @@ -103,14 +103,14 @@ private: for (std::size_t row = 0; row < INPUT_FEATURES; ++row) { for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) { - double avgGrad = grad.weights[row][col] / divisor; + 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); - double momentumCorrected = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time)); - double varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time)); + 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); } @@ -122,8 +122,8 @@ private: 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); - double momentumCorrected = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time)); - double varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time)); + 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); } @@ -147,6 +147,7 @@ private: void reset() {} }; + static float sigmoid(float in) { return 1 / (1 + std::exp(-in)); } static double sigmoid(double in) { return 1 / (1 + std::exp(-in)); } void dump(std::ostream& os) const {} @@ -157,13 +158,13 @@ private: void fill_random(const Dist& dist) {} auto& forward(const input_type& input) { - output.get().apply(input, [](double unusd, double in) { return sigmoid(in); }); + output.get().apply(input, [](auto unusd, auto in) { return sigmoid(in); }); return output; } template auto backward(const input_type& input, gradient& grad, Error prevErr) const { - return prevErr.hadamard(output.get().hadamard(1.0 - output.get())); + return prevErr.hadamard(output.get().hadamard(static_cast(1) - output.get())); } void apply_grad(gradient&, double, double) {} @@ -195,20 +196,24 @@ private: auto& forward(const input_type& input) { savedInput = input; - output.get().apply(input, [](double unusd, double in) { return in > 0.0 ? in : 0.0; }); + output.get().apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; }); return output; } template auto backward(const input_type& input, gradient& grad, Error prevErr) const { - return prevErr.apply(savedInput, [](double in, double check) { return check > 0.0 ? in : 0.0; }); + return prevErr.apply(savedInput, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); } void apply_grad(gradient&, double, double) {} }; }; -template +template class conv2d_layer final : public layer_info { template friend class network; @@ -225,14 +230,19 @@ private: static constexpr std::size_t IN_HEIGHT = input_tensor::template dimension<1>(); static constexpr std::size_t IN_WIDTH = input_tensor::template dimension<2>(); + 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 = input_inner_t>; + using output_type = input_inner_t>; - using weights_type = tensor; - using biases_type = tensor; + using weights_type = tensor; + using biases_type = tensor; struct gradient final { using parent_type = inner; @@ -282,7 +292,7 @@ private: 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) { - double value = biases[oc]; + auto value = biases[oc]; for (std::size_t ic = 0; ic < IN_CHANS; ++ic) { for (std::size_t ky = 0; ky < KernelSize; ++ky) { @@ -313,7 +323,7 @@ private: 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 double err = prevErr[oc][oy][ox]; + const auto err = prevErr[oc][oy][ox]; grad.biases[oc] += err; @@ -361,9 +371,9 @@ private: grad.varianceWeights[oc][ic][ky][kx] = beta2 * grad.varianceWeights[oc][ic][ky][kx] + (1.0 - beta2) * avgGrad * avgGrad; - double momentumCorrected = + auto momentumCorrected = grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time)); - double varianceCorrected = + auto varianceCorrected = grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time)); weights[oc][ic][ky][kx] -= @@ -372,13 +382,13 @@ private: } } - double avgGrad = grad.biases[oc] / divisor; + 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; - double momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time)); - double varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time)); + 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); } @@ -386,7 +396,7 @@ private: }; }; -template +template class maxpool_layer : public layer_info { template friend class network; @@ -397,6 +407,7 @@ private: static_assert(input_type::TAG == layer_input::TENSOR_TAG); using input_tensor = input_type::type; + static_assert(std::is_same_v); static_assert(input_tensor::RANK == 3); static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>(); @@ -407,7 +418,7 @@ private: 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 = input_inner_t>; + using output_type = input_inner_t>; output_type output; struct gradient final { @@ -425,7 +436,7 @@ private: 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) { - double maxValue = input.get()[ch][oy * Stride][ox * Stride]; + auto maxValue = input.get()[ch][oy * Stride][ox * Stride]; for (std::size_t ky = 0; ky < PoolSize; ++ky) { for (std::size_t kx = 0; kx < PoolSize; ++kx) { @@ -451,7 +462,7 @@ private: std::size_t maxY = oy * Stride; std::size_t maxX = ox * Stride; - double maxValue = input.get()[ch][maxY][maxX]; + auto maxValue = input.get()[ch][maxY][maxX]; for (std::size_t ky = 0; ky < PoolSize; ++ky) { for (std::size_t kx = 0; kx < PoolSize; ++kx) { @@ -491,7 +502,7 @@ private: static constexpr std::size_t FEATURES = input_tensor::SIZE; - using output_type = input_inner_t>; + using output_type = input_inner_t>; output_type output; struct gradient final { diff --git a/include/cenet/mat.hpp b/include/cenet/mat.hpp index 833c155..4f10b60 100644 --- a/include/cenet/mat.hpp +++ b/include/cenet/mat.hpp @@ -25,7 +25,8 @@ private: template = 1 && N >= 1)>> class mat { public: - using col_type = mat_col; + using col_type = mat_col; + using inner_type = T; public: mat() { std::memset(m_items, 0, sizeof(m_items)); } diff --git a/include/cenet/tensor.hpp b/include/cenet/tensor.hpp index cd82e6f..eeb9c15 100644 --- a/include/cenet/tensor.hpp +++ b/include/cenet/tensor.hpp @@ -21,6 +21,8 @@ public: } static constexpr std::size_t RANK = 1 + sizeof...(Rest); + + using inner_type = T; public: template class view {