feat: add layers for CNNs

This commit is contained in:
2026-09-20 21:08:33 +02:00
parent 5bb278c9de
commit 27b1a677d9
7 changed files with 607 additions and 22 deletions
+21 -1
View File
@@ -139,10 +139,30 @@ public:
return res; return res;
} }
public: public:
T* data() { return m_items; } template <typename Func>
mat& apply(Func&& func) {
for (auto& el : *this)
el = func(el);
return *this;
}
template <typename Func>
mat& apply(const mat& rhs, Func&& func) {
for (auto it = begin(), itR = rhs.begin(); it != end(); ++it, ++itR)
*it = func(*it, *itR);
return *this;
}
public:
T* data() { return m_items; }
const T* data() const { return m_items; } const T* data() const { return m_items; }
T* begin() { return m_items; }
T* end() { return m_items + size(); }
const T* begin() const { return m_items; }
const T* end() const { return m_items + size(); }
const T* cbegin() const { return begin(); }
const T* cend() const { return end(); }
constexpr std::size_t size() const { return M * N; } constexpr std::size_t size() const { return M * N; }
public: public:
bool operator==(const mat& rhs) const { return std::memcmp(m_items, rhs.m_items, sizeof(m_items)) == 0; } bool operator==(const mat& rhs) const { return std::memcmp(m_items, rhs.m_items, sizeof(m_items)) == 0; }
+384 -3
View File
@@ -2,7 +2,9 @@
#define NN_HPP #define NN_HPP
#include "mat.hpp" #include "mat.hpp"
#include "tensor.hpp"
#include <algorithm>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
#include <istream> #include <istream>
@@ -12,7 +14,8 @@
#include <utility> #include <utility>
struct layer_input { struct layer_input {
static constexpr std::uint32_t DENSE_TAG = 0x444E5345; static constexpr std::uint32_t DENSE_TAG = 0x444E5345;
static constexpr std::uint32_t TENSOR_TAG = 0x544E5352;
}; };
template <std::size_t Features> template <std::size_t Features>
@@ -43,6 +46,32 @@ private:
}; };
}; };
template <std::size_t... Dims>
class tensor_input : public layer_input {
template <typename Input, typename... Layers>
friend class nn;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = TENSOR_TAG;
using type = tensor<double, 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;
};
};
struct layer_info { struct layer_info {
protected: protected:
template <class NN, std::size_t I> template <class NN, std::size_t I>
@@ -190,8 +219,7 @@ 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) {
for (std::size_t i = 0; i < input_type::FEATURES; ++i) output.get().apply(input, [](double unusd, double in) { return sigmoid(in); });
output.get()[0][i] = sigmoid(input.get()[0][i]);
return output; return output;
} }
@@ -204,6 +232,359 @@ private:
}; };
}; };
class relu_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class nn;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using output_type = input_type;
input_type savedInput;
output_type output;
struct gradient {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
savedInput = input;
output.get().apply(input, [](double unusd, double in) { return in > 0.0 ? in : 0.0; });
return output;
}
template <typename Error>
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; });
}
void apply_grad(gradient&, double, double) {}
};
};
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
class conv2d_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class nn;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
using input_tensor = input_type::type;
static_assert(input_tensor::RANK == 3);
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 = 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<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
using weights_type = tensor<double, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<double, 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 = weights_type{};
biases = biases_type{};
}
};
weights_type weights;
biases_type biases;
output_type output;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr double fanIn = static_cast<double>(IN_CHANS * KernelSize * KernelSize);
const double scale = std::sqrt(2.0 / fanIn);
weights = decltype(weights)::random(dist);
weights *= scale;
biases = decltype(biases){};
}
auto& forward(const input_type& input) {
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];
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<std::ptrdiff_t>((oy * Stride) + ky) -
static_cast<std::ptrdiff_t>(Padding);
std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
value += input.get()[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output.get()[oc][oy][ox] = value;
}
}
}
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
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];
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<std::ptrdiff_t>((oy * Stride) + ky) -
static_cast<std::ptrdiff_t>(Padding);
const std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
grad.weights[oc][ic][ky][kx] += input.get()[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;
double momentumCorrected =
grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time));
double 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);
}
}
}
double 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));
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
}
}
};
};
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
class maxpool_layer : public layer_info {
template <typename Input, typename... Layers>
friend class nn;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
using input_tensor = input_type::type;
static_assert(input_tensor::RANK == 3);
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_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
using output_type = input_inner_t<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
output_type output;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
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];
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
maxValue = std::max(maxValue, input.get()[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
}
}
output.get()[ch][oy][ox] = maxValue;
}
}
}
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
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;
double maxValue = input.get()[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.get()[ch][yIdx][xIdx] > maxValue) {
maxValue = input.get()[ch][yIdx][xIdx];
maxY = yIdx;
maxX = xIdx;
}
}
}
backpropErr[ch][maxY][maxX] += prevErr[ch][oy][ox];
}
}
}
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
class flatten_layer : public layer_info {
template <typename Input, typename... Layers>
friend class nn;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
using input_tensor = input_type::type;
static constexpr std::size_t FEATURES = input_tensor::SIZE;
using output_type = input_inner_t<dense_input<FEATURES>>;
output_type output;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
std::copy(input.get().begin(), input.get().end(), output.xs.data());
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
template <typename Input, typename... Layers> template <typename Input, typename... Layers>
class nn { class nn {
friend class layer_info; friend class layer_info;
+183
View File
@@ -0,0 +1,183 @@
#ifndef TENSOR_HPP
#define TENSOR_HPP
#include <cstddef>
#include <cstring>
#include <random>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
template <typename T, std::size_t First, std::size_t... Rest>
class tensor {
public:
static constexpr auto DIMENSIONS = std::make_tuple(First, Rest...);
template <std::size_t I>
static constexpr std::size_t dimension() {
return std::get<I>(DIMENSIONS);
}
static constexpr std::size_t RANK = 1 + sizeof...(Rest);
public:
template <typename InT, std::size_t InFirst, std::size_t... InRest>
class view {
friend class tensor;
private:
view(InT* data)
: m_data(data) {}
public:
static constexpr auto DIMENSIONS = std::make_tuple(InFirst, InRest...);
public:
decltype(auto) operator[](std::size_t idx) {
if constexpr (sizeof...(InRest) == 0) {
InT& ref = m_data[idx];
return (ref); // NOLINT
} else {
return view<InT, InRest...>{ m_data + (idx * (InRest * ...)) };
}
}
decltype(auto) operator[](std::size_t idx) const {
if constexpr (sizeof...(InRest) == 0) {
const InT& ref = m_data[idx];
return (ref); // NOLINT
} else {
return view<InT, InRest...>{ m_data + (idx * (InRest * ...)) };
}
}
public:
constexpr std::size_t size() const { return InFirst * (InRest * ...); }
InT* data() { return m_data; }
const InT* data() const { return m_data; }
private:
InT* m_data;
};
public:
using view_type = view<T, First, Rest...>;
using const_view_type = view<const T, First, Rest...>;
public:
tensor() { std::memset(m_items, 0, sizeof(m_items)); }
~tensor() = default;
tensor(tensor&& rhs) noexcept { std::memcpy(m_items, rhs.m_items, sizeof(m_items)); }
tensor& operator=(tensor&& rhs) noexcept {
if (this == &rhs) return *this;
std::memcpy(m_items, rhs.m_items, sizeof(m_items));
return *this;
}
tensor(const tensor& rhs) noexcept { std::memcpy(m_items, rhs.m_items, sizeof(m_items)); }
tensor& operator=(const tensor& rhs) noexcept {
if (this == &rhs) return *this;
std::memcpy(m_items, rhs.m_items, sizeof(m_items));
return *this;
}
public:
tensor(const view_type& view) { std::memcpy(m_items, view.data(), sizeof(m_items)); }
operator view_type() { return m_items; }
template <typename Dist>
static tensor random(Dist dist) {
static std::random_device s_rd;
static std::mt19937 s_mt(s_rd());
tensor result;
for (auto& var : result)
var = dist(s_mt);
return result;
}
public:
template <std::size_t... InDims, typename... Offs>
view<T, InDims...> slice(Offs... offs) {
static_assert(sizeof...(InDims) <= sizeof...(Rest) + 1);
static_assert((sizeof...(Offs) == sizeof...(Rest) + 1) && (std::is_same_v<Offs, std::size_t> && ...));
return { slice(std::make_index_sequence<sizeof...(Rest) + 1>{}, offs...) };
}
private:
template <std::size_t I>
constexpr std::size_t stride() {
if constexpr (I == sizeof...(Rest))
return 1;
else
return stride<I + 1>() * std::get<I + 1>(DIMENSIONS);
}
template <std::size_t... I, typename... Offs>
T* slice(std::index_sequence<I...>, Offs... offs) {
return m_items + ((offs * stride<I>()) + ...);
}
public:
decltype(auto) operator[](std::size_t idx) {
if constexpr (sizeof...(Rest) == 0) {
T& ref = m_items[idx];
return (ref); // NOLINT
} else {
return view<T, Rest...>{ m_items + (idx * (Rest * ...)) };
}
}
decltype(auto) operator[](std::size_t idx) const {
if constexpr (sizeof...(Rest) == 0) {
const T& ref = m_items[idx];
return (ref); // NOLINT
} else {
return view<const T, Rest...>{ m_items + (idx * (Rest * ...)) };
}
}
public:
template <typename Func>
auto& apply(Func&& func) {
for (auto& var : *this) {
var = func(var);
}
return *this;
}
template <typename Func>
auto& apply(const tensor& rhs, Func&& func) {
for (auto it1 = begin(), it2 = rhs.begin(), endIt = end(); it1 != endIt; ++it1, ++it2) {
*it1 = func(*it1, *it2);
}
return *this;
}
public:
auto& operator+=(const tensor& rhs) {
return apply(rhs, [](T lhs, T rhs) { return lhs + rhs; });
}
auto& operator-=(const tensor& rhs) {
return apply(rhs, [](T lhs, T rhs) { return lhs - rhs; });
}
auto& operator*=(T scalar) {
return apply([scalar](T lhs) { return lhs * scalar; });
}
auto& operator/=(T scalar) {
return apply([scalar](T lhs) { return lhs / scalar; });
}
public:
static constexpr std::size_t SIZE = First * (Rest * ... * 1);
std::size_t size() const { return SIZE; }
T* data() { return m_items; }
const T* data() const { return m_items; }
T* begin() { return m_items; }
T* end() { return m_items + SIZE; }
const T* begin() const { return m_items; }
const T* end() const { return m_items + SIZE; }
const T* cbegin() const { return m_items; }
const T* cend() const { return m_items + SIZE; }
private:
T m_items[SIZE];
};
#endif // TENSOR_HPP
BIN
View File
Binary file not shown.
View File
Binary file not shown.
+19 -18
View File
@@ -1,5 +1,6 @@
#include "mat.hpp" #include "mat.hpp"
#include "nn.hpp" #include "nn.hpp"
#include "tensor.hpp"
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
@@ -13,11 +14,22 @@
#include <random> #include <random>
#include <vector> #include <vector>
using network_type = nn<tensor_input<1, 28, 28>,
conv2d_layer<8, 3, 1, 1>,
relu_layer,
maxpool_layer<>,
conv2d_layer<16, 3, 1, 1>,
relu_layer,
maxpool_layer<>,
flatten_layer,
dense_layer<10>,
sigmoid_layer>;
static std::uniform_real_distribution<> dist(-1, 1); static std::uniform_real_distribution<> dist(-1, 1);
struct data { struct data {
mat<1, 784> xs; tensor<double, 1, 28, 28> xs;
mat<1, 10> ys; mat<1, 10> ys;
}; };
using dataset = std::vector<data>; using dataset = std::vector<data>;
@@ -72,7 +84,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::uint8_t pixel = 0; std::uint8_t pixel = 0;
images.read(reinterpret_cast<char*>(&pixel), sizeof(pixel)); images.read(reinterpret_cast<char*>(&pixel), sizeof(pixel));
set[i].xs[0][(row * dims[0]) + col] = static_cast<double>(pixel) / 255.0; set[i].xs[0][row][col] = static_cast<double>(pixel) / 255.0;
} }
} }
@@ -87,22 +99,14 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
} }
static void shuffle_dataset(dataset& set) { static void shuffle_dataset(dataset& set) {
auto rng = std::default_random_engine{}; static std::mt19937 s_rng(std::random_device{}());
std::shuffle(std::begin(set), std::end(set), rng); std::shuffle(std::begin(set), std::end(set), s_rng);
} }
int main(void) { int main(void) {
using network_type = nn<dense_input<784>,
dense_layer<300>,
sigmoid_layer,
dense_layer<100>,
sigmoid_layer,
dense_layer<10>,
sigmoid_layer>;
network_type* mnistNet = new network_type(); network_type* mnistNet = new network_type();
static constexpr const char* NETWORK_PATH = "./mnist.nn"; static constexpr const char* NETWORK_PATH = "./mnist-conv.nn";
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary); std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
if (file.is_open()) if (file.is_open())
@@ -123,7 +127,7 @@ int main(void) {
static constexpr std::size_t MAX_EPOCHS = 1000; static constexpr std::size_t MAX_EPOCHS = 1000;
static constexpr std::size_t BATCH_SIZE = 64; static constexpr std::size_t BATCH_SIZE = 64;
static constexpr std::size_t EPL = 5; // Epochs Per Log static constexpr std::size_t EPL = 1; // Epochs Per Log
double learningRate = 0.001; double learningRate = 0.001;
@@ -202,8 +206,5 @@ int main(void) {
} }
} }
saveFile.seekp(0);
mnistNet->dump_network(saveFile);
return 0; return 0;
} }