refactor: remove input.hpp

This commit is contained in:
2026-10-25 19:21:17 +01:00
parent 471c9c8997
commit fa0418914a
8 changed files with 81 additions and 146 deletions
+3 -3
View File
@@ -11,7 +11,7 @@
#include <random> #include <random>
#include <vector> #include <vector>
using network_type = cenet::network<cenet::tensor_input<float, 1, 28, 28>, using network_type = cenet::network<cenet::tensor<float, 1, 28, 28>,
cenet::conv2d_layer<8, 3, 1, 1>, cenet::conv2d_layer<8, 3, 1, 1>,
cenet::relu_layer, cenet::relu_layer,
cenet::maxpool_layer<>, cenet::maxpool_layer<>,
@@ -157,11 +157,11 @@ int main(void) {
const auto& output = mnistNet->feed(validationSet[i].xs); const auto& output = mnistNet->feed(validationSet[i].xs);
for (std::size_t j = 0; j < 10; ++j) { for (std::size_t j = 0; j < 10; ++j) {
float diff = output.get()[0][j] - validationSet[i].ys[0][j]; float diff = output[0][j] - validationSet[i].ys[0][j];
totalLoss += diff * diff; totalLoss += diff * diff;
} }
if (col_largest_idx(output.get()[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits; if (col_largest_idx(output[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits;
} }
currentLoss = totalLoss / static_cast<double>(validationSet.size()); currentLoss = totalLoss / static_cast<double>(validationSet.size());
+2 -2
View File
@@ -15,7 +15,7 @@ int main(void) {
}; };
// network net; // network net;
using network_type = cenet::network<cenet::dense_input<2>, using network_type = cenet::network<cenet::mat<1, 2, float>,
cenet::dense_layer<2>, cenet::dense_layer<2>,
cenet::sigmoid_layer, cenet::sigmoid_layer,
cenet::dense_layer<1>, cenet::dense_layer<1>,
@@ -50,7 +50,7 @@ int main(void) {
xs[0][0] = static_cast<float>(i & 1); xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1); xs[0][1] = static_cast<float>(i > 1);
float yHat = xorNet.feed(xs).get()[0][0]; float yHat = xorNet.feed(xs)[0][0];
float error = yHat - s_trainData[i]; float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) { if ((gen % 1000) == 0) {
+2 -3
View File
@@ -1,8 +1,7 @@
#ifndef CENET_HPP #ifndef CENET_HPP
#define CENET_HPP #define CENET_HPP
#include "input.hpp" #include "layer.hpp" // IWYU pragma: export
#include "layer.hpp" #include "network.hpp" // IWYU pragma: export
#include "network.hpp"
#endif // CENET_HPP #endif // CENET_HPP
-85
View File
@@ -1,85 +0,0 @@
#ifndef CENET_INPUT_HPP
#define CENET_INPUT_HPP
#include "mat.hpp"
#include "tensor.hpp"
#include <cstdint>
#include <type_traits>
namespace cenet {
struct layer_input {
static constexpr std::uint32_t DENSE_TAG = 0x444E5345;
static constexpr std::uint32_t TENSOR_TAG = 0x544E5352;
};
template <std::size_t Features, typename T = float>
class dense_input : public layer_input {
template <typename Input, typename... Layers>
friend class network;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = DENSE_TAG;
static constexpr std::size_t FEATURES = Features;
using inner_type = T;
using type = mat<1, FEATURES, T>;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<type, Args...>>>
inner(Args&&... args)
: xs(std::forward<Args>(args)...) {}
operator type&() { return xs; }
operator const type&() const { return xs; }
type& get() { return xs; }
const type& get() const { return xs; }
type xs;
};
};
template <typename T, std::size_t... Dims>
class tensor_input : public layer_input {
template <typename Input, typename... Layers>
friend class network;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = TENSOR_TAG;
using inner_type = T;
using type = tensor<T, Dims...>;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<type, Args...>>>
inner(Args&&... args)
: xs(std::forward<Args>(args)...) {}
operator type&() { return xs; }
operator const type&() const { return xs; }
type& get() { return xs; }
const type& get() const { return xs; }
type xs;
};
};
namespace detail {
template <typename T, typename = void>
struct is_layer_input : std::false_type {};
template <typename T>
struct is_layer_input<T, std::enable_if_t<std::is_base_of_v<layer_input, T>>> : std::true_type {};
} // namespace detail
} // namespace cenet
#endif // CENET_INPUT_HPP
+69 -51
View File
@@ -1,15 +1,39 @@
#ifndef CENET_LAYER_HPP #ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP #define CENET_LAYER_HPP
#include "input.hpp" #include "mat.hpp"
#include "tensor.hpp"
#include <cstddef> #include <cstddef>
#include <istream> #include <istream>
#include <ostream> #include <ostream>
#include <tuple> #include <tuple>
#include <type_traits>
namespace cenet { namespace cenet {
namespace detail {
template <typename T>
struct is_dense : std::false_type {};
template <std::size_t N, typename T>
struct is_dense<mat<1, N, T>> : std::true_type {};
template <typename T>
static constexpr auto is_dense_v = is_dense<T>::value;
template <typename T>
struct is_tensor : std::false_type {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
} // namespace detail
struct layer_info { struct layer_info {
protected: protected:
template <class NN, std::size_t I> template <class NN, std::size_t I>
@@ -34,11 +58,11 @@ private:
template <class NN, std::size_t I> template <class NN, std::size_t I>
struct inner final { struct inner final {
using input_type = input_type_s<NN, I>::type; using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::DENSE_TAG); static_assert(detail::is_dense_v<input_type>);
using output_type = input_inner_t<dense_input<Features, T>>; using output_type = mat<1, Features, T>;
static constexpr std::size_t INPUT_FEATURES = input_type::FEATURES; static constexpr std::size_t INPUT_FEATURES = input_type::COLS;
static constexpr std::size_t OUTPUT_FEATURES = Features; static constexpr std::size_t OUTPUT_FEATURES = Features;
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES, T>; using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES, T>;
@@ -84,11 +108,11 @@ private:
biases = decltype(biases){}; biases = decltype(biases){};
} }
auto& forward(const input_type& input) { return output = (input.get() * weights) + biases; } auto& forward(const input_type& input) { return output = (input * weights) + biases; }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(const input_type& input, gradient& grad, Error prevErr) {
grad.weights += input.get().transpose() * prevErr; grad.weights += input.transpose() * prevErr;
grad.biases += prevErr; grad.biases += prevErr;
return prevErr * weights.transpose(); return prevErr * weights.transpose();
@@ -138,7 +162,7 @@ private:
template <class NN, std::size_t I> template <class NN, std::size_t I>
struct inner final { struct inner final {
using input_type = input_type_s<NN, I>::type; using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::DENSE_TAG); static_assert(detail::is_dense_v<input_type>);
using output_type = input_type; using output_type = input_type;
output_type output; output_type output;
@@ -158,13 +182,13 @@ private:
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto& forward(const input_type& input) {
output.get().apply(input, [](auto unusd, auto in) { return sigmoid(in); }); output.apply(input, [](auto unusd, auto in) { return sigmoid(in); });
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const { auto backward(const input_type& input, gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.get().hadamard(static_cast<output_type::inner_type>(1) - output.get())); return prevErr.hadamard(output.hadamard(static_cast<output_type::inner_type>(1) - output));
} }
void apply_grad(gradient&, double, double) {} void apply_grad(gradient&, double, double) {}
@@ -196,7 +220,7 @@ private:
auto& forward(const input_type& input) { auto& forward(const input_type& input) {
savedInput = input; savedInput = input;
output.get().apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; }); output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
return output; return output;
} }
@@ -221,14 +245,12 @@ private:
template <class NN, std::size_t I> template <class NN, std::size_t I>
struct inner final { struct inner final {
using input_type = input_type_s<NN, I>::type; using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG); static_assert(detail::is_tensor_v<input_type>);
static_assert(input_type::RANK == 3);
using input_tensor = input_type::type; static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static_assert(input_tensor::RANK == 3); static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
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(Stride > 0, "Invalid stride passed to conv2d_layer");
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer"); static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
@@ -239,7 +261,7 @@ private:
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1; 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; static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
using output_type = input_inner_t<tensor_input<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>; using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>; using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<T, OUT_CHANS>; using biases_type = tensor<T, OUT_CHANS>;
@@ -268,20 +290,20 @@ private:
output_type output; output_type output;
void dump(std::ostream& os) const { void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size()); os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size()); os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
} }
void load(std::istream& is) { void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size()); is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size()); is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
} }
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) { void fill_random(const Dist& dist) {
constexpr double fanIn = static_cast<double>(IN_CHANS * KernelSize * KernelSize); constexpr T fanIn = static_cast<T>(IN_CHANS * KernelSize * KernelSize);
const double scale = std::sqrt(2.0 / fanIn); const T scale = std::sqrt(2.0 / fanIn);
weights = decltype(weights)::random(dist); weights = decltype(weights)::random(dist);
weights *= scale; weights *= scale;
@@ -303,13 +325,13 @@ 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 += input.get()[ic][iy][ix] * weights[oc][ic][ky][kx]; value += input[ic][iy][ix] * weights[oc][ic][ky][kx];
} }
} }
} }
} }
output.get()[oc][oy][ox] = value; output[oc][oy][ox] = value;
} }
} }
} }
@@ -318,7 +340,7 @@ private:
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr; input_type backpropErr;
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) {
@@ -339,7 +361,7 @@ 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] += input.get()[ic][iy][ix] * err; grad.weights[oc][ic][ky][kx] += input[ic][iy][ix] * err;
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err; backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err;
} }
@@ -404,21 +426,19 @@ private:
template <class NN, std::size_t I> template <class NN, std::size_t I>
struct inner final { struct inner final {
using input_type = input_type_s<NN, I>::type; using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG); static_assert(detail::is_tensor_v<input_type>);
static_assert(std::is_same_v<typename input_type::inner_type, T>);
static_assert(input_type::RANK == 3);
using input_tensor = input_type::type; static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static_assert(std::is_same_v<typename input_tensor::inner_type, T>); static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static_assert(input_tensor::RANK == 3); static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
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 constexpr std::size_t OUT_CHANS = IN_CHANS; 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_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1; static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
using output_type = input_inner_t<tensor_input<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>; using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output; output_type output;
struct gradient final { struct gradient final {
@@ -436,15 +456,15 @@ private:
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) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
auto maxValue = input.get()[ch][oy * Stride][ox * Stride]; auto maxValue = input[ch][oy * Stride][ox * Stride];
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) {
maxValue = std::max(maxValue, input.get()[ch][(oy * Stride) + ky][(ox * Stride) + kx]); maxValue = std::max(maxValue, input[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
} }
} }
output.get()[ch][oy][ox] = maxValue; output[ch][oy][ox] = maxValue;
} }
} }
} }
@@ -454,7 +474,7 @@ private:
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr; input_type backpropErr;
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) {
@@ -462,15 +482,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.get()[ch][maxY][maxX]; auto maxValue = input[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.get()[ch][yIdx][xIdx] > maxValue) { if (input[ch][yIdx][xIdx] > maxValue) {
maxValue = input.get()[ch][yIdx][xIdx]; maxValue = input[ch][yIdx][xIdx];
maxY = yIdx; maxY = yIdx;
maxX = xIdx; maxX = xIdx;
} }
@@ -496,13 +516,11 @@ private:
template <class NN, std::size_t I> template <class NN, std::size_t I>
struct inner final { struct inner final {
using input_type = input_type_s<NN, I>::type; using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG); static_assert(detail::is_tensor_v<input_type>);
using input_tensor = input_type::type; static constexpr std::size_t FEATURES = input_type::SIZE;
static constexpr std::size_t FEATURES = input_tensor::SIZE; using output_type = mat<1, FEATURES, typename input_type::inner_type>;
using output_type = input_inner_t<dense_input<FEATURES, typename input_tensor::inner_type>>;
output_type output; output_type output;
struct gradient final { struct gradient final {
@@ -517,13 +535,13 @@ private:
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto& forward(const input_type& input) {
std::copy(input.get().begin(), input.get().end(), output.xs.data()); std::copy(input.begin(), input.end(), output.data());
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr; input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin()); std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
+3
View File
@@ -25,6 +25,9 @@ private:
template <std::size_t M, std::size_t N, typename T = double, typename = std::enable_if_t<(M >= 1 && N >= 1)>> template <std::size_t M, std::size_t N, typename T = double, typename = std::enable_if_t<(M >= 1 && N >= 1)>>
class mat { class mat {
public: public:
static constexpr std::size_t ROWS = M;
static constexpr std::size_t COLS = N;
using col_type = mat_col<N, T>; using col_type = mat_col<N, T>;
using inner_type = T; using inner_type = T;
public: public:
+2 -2
View File
@@ -37,7 +37,7 @@ private:
return std::get<I>(m_layers); return std::get<I>(m_layers);
} }
public: public:
using input_type = Input::inner; using input_type = Input;
using output_type = output_layer_type::output_type; using output_type = output_layer_type::output_type;
public: public:
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; } const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; }
@@ -108,7 +108,7 @@ public:
public: public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) { void backprop(const input_type& input, const output_type& expected, learning_state& state) {
feed(input); feed(input);
auto outputErr = get_output().get() - expected; auto outputErr = get_output() - expected;
get_layer<0>().backward(input, get_layer<0>().backward(input,
std::get<0>(state.m_layers), std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr)); backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
BIN
View File
Binary file not shown.