Compare commits

..
26 Commits
Author SHA1 Message Date
CHatingPython d97b65678a refactor(examples): port the mnist example 2026-11-02 03:01:48 +01:00
CHatingPython f59602e99a fix(examples): fix xor network example 2026-11-01 21:21:33 +01:00
CHatingPython 7cc35104d4 fix(math): fix calculate_offset 2026-11-01 21:21:16 +01:00
CHatingPython d23905c259 feat(math): add reshape operation 2026-11-01 20:44:25 +01:00
CHatingPython 961067c28d refactor(math): move calculate_offset to shapes 2026-11-01 20:44:00 +01:00
CHatingPython 1e37036bb3 fix(nn): fix relu layers 2026-11-01 20:43:37 +01:00
CHatingPython 367ec2da69 feat(nn): migrate the relu layer 2026-11-01 18:51:31 +01:00
CHatingPython 4b782a6619 refactor(nn): start migrating layers to cenet::math 2026-11-01 13:20:40 +01:00
CHatingPython c65743e957 fix(math): fix transpose operation 2026-11-01 13:20:19 +01:00
CHatingPython c96d31a378 feat(math): add transpose operation and fill_random 2026-11-01 13:06:34 +01:00
CHatingPython 795915d100 fix(math): fix critical tensor/expression mistakes 2026-11-01 12:48:41 +01:00
CHatingPython 377cd5941d fix(math): fix unary expression shape reporting 2026-11-01 11:25:54 +01:00
CHatingPython a264009629 fix(math): fix tensor and tensor_view 2026-11-01 11:17:44 +01:00
CHatingPython f3e2fb7c58 fix(math): fix with_storage trait 2026-11-01 10:51:49 +01:00
CHatingPython 75243e9d08 feat(math): add with_storage template to tensor 2026-11-01 09:59:06 +01:00
CHatingPython 3dfcb754f8 feat(math): introduce apply operation 2026-11-01 09:52:09 +01:00
CHatingPython 78864efba9 feat(math): introduce ops_provider CRTP class 2026-11-01 07:34:22 +01:00
CHatingPython 2267c8d7f8 feat(math): introduce matmul operator 2026-11-01 07:34:08 +01:00
CHatingPython 673e068344 feat(math): add static get (sget) to shapes 2026-11-01 07:33:14 +01:00
CHatingPython 0eeafe31c4 feat(math): introduce best shape trait 2026-11-01 06:48:02 +01:00
CHatingPython 8dee1cbe1f feat(math): introduce scalar operations 2026-11-01 06:10:59 +01:00
CHatingPython de783ad7b7 refactor(math): improve expressions
Improve expressions by passing index, lhs and rhs.
2026-11-01 06:03:04 +01:00
CHatingPython 3fca91e1ea refactor(math): generalize tensor operations 2026-11-01 05:59:58 +01:00
CHatingPython b482010c5d feat(math): add operator field to expressions 2026-11-01 05:35:58 +01:00
CHatingPython 09d23cd568 fix(math): fix tensor expression assignments 2026-11-01 05:32:32 +01:00
CHatingPython 8fe56476ed refactor(nn): separate loss function from network
Refs: #3
2026-10-30 23:45:54 +01:00
16 changed files with 1252 additions and 315 deletions
+28 -20
View File
@@ -1,3 +1,7 @@
#include "cenet/layers/convolutional.hpp"
#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cenet/cenet.hpp> #include <cenet/cenet.hpp>
@@ -11,28 +15,28 @@
#include <random> #include <random>
#include <vector> #include <vector>
using network_type = cenet::network<cenet::tensor<float, 1, 28, 28>, using network_type = cenet::network<cenet::math::tensor<float, 1, 28, 28>,
cenet::conv2d_layer<8, 3, 1, 1>, cenet::layers::conv2d<8, 3, 1, 1>,
cenet::relu_layer, cenet::layers::relu,
cenet::maxpool_layer<>, cenet::layers::maxpool<>,
cenet::conv2d_layer<16, 3, 1, 1>, cenet::layers::conv2d<16, 3, 1, 1>,
cenet::relu_layer, cenet::layers::relu,
cenet::maxpool_layer<>, cenet::layers::maxpool<>,
cenet::flatten_layer, cenet::layers::flatten,
cenet::dense_layer<10>, cenet::layers::dense<10>,
cenet::sigmoid_layer>; cenet::layers::sigmoid>;
static std::uniform_real_distribution<> dist(-1, 1); static std::uniform_real_distribution<> dist(-1, 1);
struct data { struct data {
cenet::tensor<float, 1, 28, 28> xs; cenet::math::tensor<float, 1, 28, 28> xs{};
cenet::mat<1, 10, float> ys; cenet::math::matrix<float, 1, 10> ys{};
}; };
using dataset = std::vector<data>; using dataset = std::vector<data>;
template <std::size_t N, typename T> template <std::size_t N, typename T>
static std::size_t col_largest_idx(const cenet::mat_col<N, T>& col) { static std::size_t col_largest_idx(const cenet::math::tensor_view<T, N>& col) {
std::size_t maxIdx = 0; std::size_t maxIdx = 0;
std::remove_cv_t<T> max = col[0]; std::remove_cv_t<T> max = col[0];
for (std::size_t i = 1; i < N; ++i) { for (std::size_t i = 1; i < N; ++i) {
@@ -87,6 +91,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::uint8_t label = 0; std::uint8_t label = 0;
labels.read(reinterpret_cast<char*>(&label), sizeof(label)); labels.read(reinterpret_cast<char*>(&label), sizeof(label));
set[i].ys.view().fill();
set[i].ys[0][label] = 1.0; set[i].ys[0][label] = 1.0;
} }
@@ -106,9 +111,9 @@ int main(void) {
static constexpr const char* NETWORK_PATH = "./mnist-conv.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())
mnistNet->load_network(file); // mnistNet->load_network(file);
else // else
mnistNet->fill_random(dist); mnistNet->fill_random(dist);
dataset trainSet = load_dataset("./mnist/train-labels-idx1-ubyte", "./mnist/train-images-idx3-ubyte"); dataset trainSet = load_dataset("./mnist/train-labels-idx1-ubyte", "./mnist/train-images-idx3-ubyte");
@@ -121,7 +126,7 @@ int main(void) {
std::size_t patienceCounter = 0; std::size_t patienceCounter = 0;
static constexpr std::size_t MAX_PATIENCE = 10; 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 BATCH_SIZE = 64;
static constexpr std::size_t EPL = 1; // Epochs Per Log static constexpr std::size_t EPL = 1; // Epochs Per Log
@@ -138,10 +143,13 @@ int main(void) {
auto epochStart = std::chrono::high_resolution_clock::now(); auto epochStart = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) { 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) for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) {
mnistNet->backprop(trainSet[i + j].xs, trainSet[i + j].ys, *state); 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);
}
mnistNet->apply(*state, learningRate); mnistNet->apply(*state, learningRate);
} }
+28 -16
View File
@@ -1,3 +1,7 @@
#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include "cenet/math/tensor_fwd.hpp"
#include <cenet/cenet.hpp> #include <cenet/cenet.hpp>
#include <cstddef> #include <cstddef>
#include <fstream> #include <fstream>
@@ -15,11 +19,11 @@ int main(void) {
}; };
// network net; // network net;
using network_type = cenet::network<cenet::mat<1, 2, float>, using network_type = cenet::network<cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2>,
cenet::dense_layer<2>, cenet::layers::dense<2>,
cenet::sigmoid_layer, cenet::layers::sigmoid,
cenet::dense_layer<1>, cenet::layers::dense<1>,
cenet::sigmoid_layer>; cenet::layers::sigmoid>;
network_type xorNet; network_type xorNet;
static constexpr const char* NETWORK_PATH = "./xor.nn"; static constexpr const char* NETWORK_PATH = "./xor.nn";
@@ -30,31 +34,39 @@ int main(void) {
else else
xorNet.fill_random(dist); xorNet.fill_random(dist);
static constexpr double EPSILON = 0.5; static constexpr double learning_late = 0.5;
std::size_t gen = 0; std::size_t gen = 0;
network_type::learning_state state;
while (gen <= 10'000'000) { while (gen <= 10'000'000) {
for (std::size_t i = 0; i < 4; ++i) { state.reset();
cenet::mat<1, 2, float> xs;
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
xorNet.train(xs, s_trainData[i], EPSILON); for (std::size_t i = 0; i < 4; ++i) {
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
xs.coeff(0) = static_cast<float>(i & 1);
xs.coeff(1) = static_cast<float>(i > 1);
auto output = std::move(xorNet.feed(xs));
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
xorNet.backward(loss, state);
} }
xorNet.apply(state, learning_late);
double acc = 0.0; double acc = 0.0;
for (std::size_t i = 0; i < 4; ++i) { for (std::size_t i = 0; i < 4; ++i) {
cenet::mat<1, 2, float> xs; cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
xs[0][0] = static_cast<float>(i & 1); xs.coeff(0) = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1); xs.coeff(1) = static_cast<float>(i > 1);
float yHat = xorNet.feed(xs)[0][0]; float yHat = xorNet.feed(xs).coeff(0);
float error = yHat - s_trainData[i]; float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) { if ((gen % 1000) == 0) {
std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n"; std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n";
} }
acc += error * error; acc += error * error;
+34 -26
View File
@@ -105,7 +105,7 @@ private:
weights_type weights; weights_type weights;
biases_type biases; biases_type biases;
output_type output; input_type input;
void dump(std::ostream& os) const { void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size()); os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
@@ -124,10 +124,13 @@ private:
biases = decltype(biases){}; biases = decltype(biases){};
} }
auto& forward(const input_type& input) { return output = (input * weights) + biases; } auto feed(input_type&& input) {
this->input = std::move(input);
return (this->input * weights) + biases;
}
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
grad.weights += input.transpose() * prevErr; grad.weights += input.transpose() * prevErr;
grad.biases += prevErr; grad.biases += prevErr;
@@ -197,13 +200,13 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type&& input) {
output.apply(input, [](auto unusd, auto in) { return sigmoid(in); }); output.apply(std::move(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(gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output)); return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
} }
@@ -220,8 +223,7 @@ private:
using input_type = typename input_type_s<NN, I>::type; using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type; using output_type = input_type;
input_type savedInput; input_type input;
output_type output;
struct gradient { struct gradient {
void reset() {} void reset() {}
@@ -234,15 +236,16 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type&& input) {
savedInput = input; output_type output;
output.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; });
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const { auto backward(gradient& grad, Error prevErr) const {
return prevErr.apply(savedInput, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); return prevErr.apply(input, [](auto in, auto check) { return check > 0.0 ? in : 0.0; });
} }
void apply_grad(gradient&, double, double) {} void apply_grad(gradient&, double, double) {}
@@ -303,7 +306,7 @@ private:
weights_type weights; weights_type weights;
biases_type biases; biases_type biases;
output_type output; input_type input;
void dump(std::ostream& os) const { void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size()); os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
@@ -326,7 +329,8 @@ private:
biases = decltype(biases){}; biases = decltype(biases){};
} }
auto& forward(const input_type& input) { auto feed(input_type&& input) {
output_type output;
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) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
@@ -351,11 +355,12 @@ private:
} }
} }
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
input_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) {
@@ -455,7 +460,8 @@ private:
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 = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>; using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output;
input_type input;
struct gradient final { struct gradient final {
void reset() {} void reset() {}
@@ -468,7 +474,8 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type&& input) {
output_type output;
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) {
@@ -484,12 +491,13 @@ private:
} }
} }
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
input_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) {
@@ -537,7 +545,6 @@ private:
static constexpr std::size_t FEATURES = input_type::SIZE; static constexpr std::size_t FEATURES = input_type::SIZE;
using output_type = mat<1, FEATURES, typename input_type::inner_type>; using output_type = mat<1, FEATURES, typename input_type::inner_type>;
output_type output;
struct gradient final { struct gradient final {
void reset() {} void reset() {}
@@ -550,17 +557,16 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type input) {
output_type output;
std::copy(input.begin(), input.end(), output.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(gradient& grad, Error prevErr) {
input_type backpropErr; input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin()); std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
return backpropErr; return backpropErr;
} }
@@ -584,7 +590,7 @@ private:
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>; using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>; using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
output_type output; input_type input;
embedding_type embedding; embedding_type embedding;
@@ -620,17 +626,19 @@ private:
} }
} }
auto& forward(const input_type& input) { auto feed(input_type&& input) {
output_type output;
output.set_dimensions(input.size(), EmbedDims); output.set_dimensions(input.size(), EmbedDims);
for (std::size_t i = 0; i < input.size(); ++i) { for (std::size_t i = 0; i < input.size(); ++i) {
if (input[i] >= VocabSize) throw std::out_of_range("invalid token!"); if (input[i] >= VocabSize) throw std::out_of_range("invalid token!");
output.view()[i].fill(embedding.view()[input[i]]); output.view()[i].fill(embedding.view()[input[i]]);
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
void backward(const input_type& input, gradient& grad, Error prevErr) { void backward(gradient& grad, Error prevErr) {
const auto errorShape = prevErr.shape(); const auto errorShape = prevErr.shape();
if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) { if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) {
throw std::invalid_argument("unexpected embedding gradient shape"); throw std::invalid_argument("unexpected embedding gradient shape");
+346
View File
@@ -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 <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
class conv2d final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
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<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type =
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = math::tensor<math::inline_storage<value_type>, 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<math::inline_storage_tag> retained;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(value_type) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(value_type) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(value_type) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr value_type fanIn = static_cast<value_type>(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 <typename Fwd>
auto feed(Fwd&& fwd) {
typename output_type::template with_storage<math::heap_storage_tag> 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<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 += fwd[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output[oc][oy][ox] = value;
}
}
}
retained = std::forward<Fwd>(fwd);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
typename input_type::template with_storage<math::heap_storage_tag> 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<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] += 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 <std::size_t PoolSize = 2, std::size_t Stride = 2>
class maxpool : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
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<math::inline_storage<value_type>, 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 <typename Dist>
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 <typename Error>
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 <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
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<value_type, 1, FEATURES>;
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) {}
template <typename Fwd>
auto feed(Fwd&& fwd) {
return std::forward<Fwd>(fwd).template reshape<math::shape_of<1, FEATURES>>();
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_CONVOLUTIONAL_HPP
+204
View File
@@ -0,0 +1,204 @@
/**
* The "dense" layer class.
*/
#ifndef CENET_LAYERS_DENSE_HPP
#define CENET_LAYERS_DENSE_HPP
#include "../layer.hpp"
#include "../math/tensor_fwd.hpp"
#include "../network.hpp"
namespace cenet {
namespace layers {
// TODO: redesign the layer interface after porting the old layers
template <std::size_t Features>
class dense final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
using value_type = typename input_type::value_type;
using output_type = math::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
struct gradient final {
using parent_type = inner;
weights_type weights;
biases_type biases;
// TODO: move Adam into optimizer state
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<math::inline_storage_tag> retained;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(value_type) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(value_type) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(value_type) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
value_type scale = std::sqrt(2.0 / static_cast<value_type>(input_cols));
weights.view().fill_random(dist);
weights = weights.apply([scale](auto val) { return val * scale; });
biases.view().fill();
}
template <typename Fwd>
auto feed(Fwd&& fwd) {
retained = std::forward<Fwd>(fwd);
return retained.matmul(weights) + biases;
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) {
grad.weights += retained.transpose().matmul(prevErr);
grad.biases += prevErr;
return std::forward<Error>(prevErr).matmul(weights.transpose());
}
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 row = 0; row < input_cols; ++row) {
for (std::size_t col = 0; col < Features; ++col) {
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);
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);
}
}
for (std::size_t col = 0; col < Features; ++col) {
double avgGrad = grad.biases[0][col] / divisor;
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);
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);
}
}
};
};
class sigmoid final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type;
typename output_type::template with_storage<math::inline_storage_tag> retained;
struct gradient {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
template <typename Fwd>
auto feed(Fwd&& fwd) {
return retained = std::forward<Fwd>(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) const {
return std::forward<Error>(prevErr) * retained *
(static_cast<typename output_type::value_type>(1) - retained);
}
void apply_grad(gradient&, double, double) {}
};
};
class relu final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type;
typename input_type::template with_storage<math::inline_storage_tag> retained;
struct gradient {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
template <typename Fwd>
auto feed(Fwd&& fwd) {
retained = std::forward<Fwd>(fwd);
return retained.apply([](auto in) { return in > 0.0 ? in : 0.0; });
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) const {
return std::forward<Error>(prevErr).apply(retained,
[](auto in, auto check) { return check > 0.0 ? in : 0.0; });
}
void apply_grad(gradient&, double, double) {}
};
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_DENSE_HPP
+24
View File
@@ -0,0 +1,24 @@
#ifndef CENET_LOSS_MSE_HPP
#define CENET_LOSS_MSE_HPP
#include <utility>
namespace cenet {
namespace loss {
struct mean_squared_error {
template <typename L, typename R>
struct result {
decltype(std::declval<R>() - std::declval<L>()) gradient;
};
template <typename L, typename R>
static result<L, R> calculate(L&& result, R&& expected) {
return { std::forward<R>(expected) - std::forward<L>(result) };
}
};
} // namespace loss
} // namespace cenet
#endif // CENET_LOSS_MSE_HPP
+99 -54
View File
@@ -2,8 +2,9 @@
#define CENET_MATH_EXPR_HPP #define CENET_MATH_EXPR_HPP
#include "ops.hpp" #include "ops.hpp"
#include "tensor_traits.hpp" #include "type_traits.hpp"
#include <stdexcept>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@@ -11,43 +12,102 @@ namespace cenet {
namespace math { namespace math {
struct expression_tag {}; struct expression_tag {};
struct expression_node_tag : expression_tag {};
template <typename E, typename Op> template <typename E, typename Op>
struct unary_expression : expression_tag { struct unary_expression;
E expr;
constexpr auto shape() const { return expr.shape(); }
auto coeff(std::size_t index) const { return Op{}(expr.coeff(index)); }
};
template <typename L, typename R, typename Op> template <typename L, typename R, typename Op>
struct binary_expression : expression_tag { struct binary_expression;
L lhs;
R rhs;
template <typename LFwd = L, typename RFwd = R> template <typename CRTP>
binary_expression(LFwd&& lhs, RFwd&& rhs) struct ops_provider {
: lhs(std::forward<LFwd>(lhs)), rhs(std::forward<RFwd>(rhs)) {} template <typename R>
binary_expression<CRTP, R, ops::matmul> matmul(R&& rhs) {
if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs) };
}
constexpr auto shape() const { return Op::shape(lhs, rhs); } template <typename Func>
unary_expression<CRTP, ops::apply<Func>> apply(Func&& func) {
if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<Func>(func) };
}
auto coeff(std::size_t index) const { return Op{}(index, lhs.coeff(index), as_operand(rhs)); } template <typename R, typename Func>
binary_expression<CRTP, R, ops::apply<Func>> apply(R&& rhs, Func&& func) {
if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs), std::forward<Func>(func) };
}
unary_expression<CRTP, ops::transpose> transpose() {
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() };
}
template <typename S>
unary_expression<CRTP, ops::reshape<S>> reshape() {
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() };
}
private: private:
template <typename T> decltype(auto) self() & { return reinterpret_cast<CRTP&>(*this); }
static decltype(auto) as_operand(T&& value) { decltype(auto) self() && { return reinterpret_cast<CRTP&&>(*this); }
if constexpr (is_tensor_v<T>) {
return std::as_const(value).view();
} else {
return std::forward<T>(value);
}
}
}; };
namespace detail { namespace detail {
template <typename T> template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>; struct operand_storage {
using raw_type = remove_cvref_t<T>;
using type = std::conditional_t<std::is_base_of_v<expression_node_tag, raw_type>,
raw_type,
std::conditional_t<std::is_lvalue_reference_v<T>, T, raw_type>>;
};
template <typename T>
using operand_storage_t = typename operand_storage<T>::type;
} // namespace detail
template <typename E, typename Op>
struct unary_expression : expression_node_tag, ops_provider<unary_expression<E, Op>> {
using expr_type = detail::operand_storage_t<E>;
expr_type expr;
Op op;
template <typename EFwd = E,
typename OpFwd = Op,
typename = std::enable_if_t<std::is_constructible_v<expr_type, EFwd&&> &&
!std::is_same_v<std::decay_t<EFwd>, unary_expression>>>
unary_expression(EFwd&& expr, OpFwd&& op = Op{}) // NOLINT
: expr(std::forward<EFwd>(expr)), op(std::forward<OpFwd>(op)) {}
constexpr auto shape() const { return Op::shape(expr); }
auto coeff(std::size_t index) const { return op(index, std::as_const(expr)); }
};
template <typename L, typename R, typename Op>
struct binary_expression : expression_node_tag, ops_provider<binary_expression<L, R, Op>> {
using lhs_type = detail::operand_storage_t<L>;
using rhs_type = detail::operand_storage_t<R>;
lhs_type lhs;
rhs_type rhs;
Op op;
template <typename LFwd = L, typename RFwd = R, typename OpFwd = Op>
binary_expression(LFwd&& lhs, RFwd&& rhs, OpFwd&& op = Op{})
: lhs(std::forward<LFwd>(lhs)), rhs(std::forward<RFwd>(rhs)), op(std::forward<OpFwd>(op)) {}
constexpr auto shape() const { return Op::shape(lhs, rhs); }
auto coeff(std::size_t index) const { return op(index, std::as_const(lhs), std::as_const(rhs)); }
};
namespace detail {
template <typename T, typename = void> template <typename T, typename = void>
struct operand { struct operand {
@@ -63,47 +123,32 @@ template <typename T>
using operand_t = typename operand<T>::type; using operand_t = typename operand<T>::type;
template <typename T> template <typename T>
static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, std::remove_cv_t<T>>; static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, remove_cvref_t<T>>;
template <typename E>
struct expression_result {
using type = remove_cvref_t<E>;
};
template <typename E, typename Op>
struct expression_result<unary_expression<E, Op>> {
using type = typename Op::template result_type<operand_t<typename expression_result<remove_cvref_t<E>>::type>>;
};
template <typename L, typename R, typename Op>
struct expression_result<binary_expression<L, R, Op>> {
using type = typename Op::template result_type<operand_t<typename expression_result<remove_cvref_t<L>>::type>,
operand_t<typename expression_result<remove_cvref_t<R>>::type>>;
};
} // namespace detail } // namespace detail
template <typename L, template <typename L, typename R, typename Op = ops::plus>
typename R,
typename Op = ops::plus,
typename = std::void_t<typename detail::expression_result<binary_expression<L, R, Op>>::type>>
binary_expression<L, R, Op> operator+(L&& lhs, R&& rhs) { binary_expression<L, R, Op> operator+(L&& lhs, R&& rhs) {
// TODO: introduce a better exception class
if (!Op::compatible(lhs, rhs)) throw std::runtime_error("tensor shape mismatch");
return { std::forward<L>(lhs), std::forward<R>(rhs) }; return { std::forward<L>(lhs), std::forward<R>(rhs) };
} }
template <typename L, template <typename L, typename R, typename Op = ops::minus>
typename R,
typename Op = ops::minus,
typename = std::void_t<typename detail::expression_result<binary_expression<L, R, Op>>::type>>
binary_expression<L, R, Op> operator-(L&& lhs, R&& rhs) { binary_expression<L, R, Op> operator-(L&& lhs, R&& rhs) {
if (!Op::compatible(lhs, rhs)) throw std::runtime_error("tensor shape mismatch");
return { std::forward<L>(lhs), std::forward<R>(rhs) }; return { std::forward<L>(lhs), std::forward<R>(rhs) };
} }
template <typename L, template <typename L, typename R, typename Op = ops::multiply>
typename R,
typename Op = ops::multiply,
typename = std::void_t<typename detail::expression_result<binary_expression<L, R, Op>>::type>>
binary_expression<L, R, Op> operator*(L&& lhs, R&& rhs) { binary_expression<L, R, Op> operator*(L&& lhs, R&& rhs) {
if (!Op::compatible(lhs, rhs)) throw std::runtime_error("tensor shape mismatch");
return { std::forward<L>(lhs), std::forward<R>(rhs) };
}
template <typename L, typename R, typename Op = ops::divide>
binary_expression<L, R, Op> operator/(L&& lhs, R&& rhs) {
if (!Op::compatible(lhs, rhs)) throw std::runtime_error("tensor shape mismatch");
return { std::forward<L>(lhs), std::forward<R>(rhs) }; return { std::forward<L>(lhs), std::forward<R>(rhs) };
} }
+162 -76
View File
@@ -1,10 +1,12 @@
#ifndef CENET_MATH_OPS_HPP #ifndef CENET_MATH_OPS_HPP
#define CENET_MATH_OPS_HPP #define CENET_MATH_OPS_HPP
#include "tensor_fwd.hpp"
#include "tensor_shape.hpp" #include "tensor_shape.hpp"
#include "tensor_traits.hpp" #include "type_traits.hpp"
#include <cstddef> #include <cstddef>
#include <functional>
#include <stdexcept> #include <stdexcept>
#include <type_traits> #include <type_traits>
@@ -12,120 +14,204 @@ namespace cenet {
namespace math { namespace math {
namespace ops { namespace ops {
class plus { namespace detail {
private:
template <typename T, typename = void>
struct has_shape : std::false_type {};
template <typename T>
struct has_shape<T, std::void_t<decltype(std::declval<T>().shape())>> : std::true_type {};
} // namespace detail
template <typename Op>
struct generic_binary_op {
template <typename L, typename R> template <typename L, typename R>
struct result_type_impl {}; static constexpr bool compatible(const L& lhs, const R& rhs) {
if constexpr (std::is_arithmetic_v<L> || std::is_arithmetic_v<R>) {
template <typename LT, std::size_t... LDims, typename RT, std::size_t... RDims> return true;
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> { } else {
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() + std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape(); return lhs.shape() == rhs.shape();
} }
}
template <typename L, typename R> template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) { static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape"); if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) { using best_shape = cenet::math::detail::best_shape<decltype(shape_wrapper(lhs)), decltype(shape_wrapper(rhs))>;
static_assert(best_shape::valid, "uncompatible operands");
if constexpr (best_shape::left) {
return lhs.shape(); return lhs.shape();
} else { } else {
return rhs.shape(); return rhs.shape();
} }
} }
template <typename LT, typename R> template <typename L, typename R>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const { constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const {
return lhs + rhs.coeff(index); if constexpr (std::is_arithmetic_v<L>) {
return Op{}(lhs, rhs.coeff(index));
} else if constexpr (std::is_arithmetic_v<R>) {
return Op{}(lhs.coeff(index), rhs);
} else {
return Op{}(lhs.coeff(index), rhs.coeff(index));
}
}
private:
template <typename T>
static constexpr auto shape_wrapper(T&& fwd) {
if constexpr (detail::has_shape<T>::value) {
return std::forward<T>(fwd).shape();
} else {
return std::forward<T>(fwd);
}
} }
}; };
class minus { struct plus : generic_binary_op<std::plus<>> {};
private: struct minus : generic_binary_op<std::minus<>> {};
struct multiply : generic_binary_op<std::multiplies<>> {};
struct divide : generic_binary_op<std::divides<>> {};
struct matmul {
template <typename L, typename R> template <typename L, typename R>
struct result_type_impl {}; static constexpr bool compatible(const L& lhs, const R& rhs) {
using lhs_shape = remove_cvref_t<decltype(lhs.shape())>;
using rhs_shape = remove_cvref_t<decltype(rhs.shape())>;
template <typename LT, std::size_t... LDims, typename RT, std::size_t... RDims> return lhs_shape::rank == 2 && rhs_shape::rank == 2 &&
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> { lhs.shape().template get<1>() == rhs.shape().template get<0>();
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() - std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape();
} }
template <typename L, typename R> template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) { static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape"); if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) {
return lhs.shape(); using lhs_shape = remove_cvref_t<decltype(lhs.shape())>;
using rhs_shape = remove_cvref_t<decltype(rhs.shape())>;
constexpr std::size_t lhs_rows = lhs_shape::template sget<0>();
constexpr std::size_t rhs_cols = rhs_shape::template sget<1>();
if constexpr (lhs_rows == dynamic_extent || rhs_cols == dynamic_extent) {
return dynamic_shape<lhs_rows, rhs_cols>{ lhs_shape::template get<0>(), rhs_shape::template get<1>() };
} else { } else {
return rhs.shape(); return static_shape<lhs_rows, rhs_cols>{};
} }
} }
template <typename LT, typename R> template <typename L, typename R>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const { constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const {
return lhs - rhs.coeff(index); const std::size_t outCols = shape(lhs, rhs).template get<1>();
const std::size_t row = index / outCols;
const std::size_t col = index % outCols;
auto lhsRows = lhs.shape().template get<0>();
auto lhsCols = lhs.shape().template get<1>();
auto rhsCols = rhs.shape().template get<1>();
decltype(lhs.coeff(0) * rhs.coeff(0)) acc{};
for (std::size_t i = 0; i < lhsCols; ++i) {
acc += lhs.coeff((row * lhsCols) + i) * rhs.coeff((i * rhsCols) + col);
}
return acc;
} }
}; };
class multiply { template <typename Func>
private: struct apply {
Func func;
template <typename Fwd = Func, typename = std::enable_if_t<std::is_constructible_v<Func, Fwd>>>
apply(Fwd&& fwd) // NOLINT
: func(std::forward<Fwd>(fwd)) {}
template <typename E>
static constexpr bool compatible(const E& expr) {
return true;
}
template <typename L, typename R> template <typename L, typename R>
struct result_type_impl {}; static constexpr bool compatible(const L& lhs, const R& rhs) {
template <typename LT, std::size_t... LDims, typename RT, std::size_t... RDims>
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> {
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() * std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape(); return lhs.shape() == rhs.shape();
} }
template <typename E>
static constexpr auto shape(const E& expr) {
if (!compatible(expr)) throw std::runtime_error("uncompatible operands");
return expr.shape();
}
template <typename L, typename R> template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) { static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape"); if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) {
return lhs.shape(); return lhs.shape();
}
template <typename E>
constexpr auto operator()(std::size_t index, const E& expr) const {
return func(expr.coeff(index));
}
template <typename L, typename R>
constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const {
return func(lhs.coeff(index), rhs.coeff(index));
}
};
struct transpose {
template <typename E>
static constexpr bool compatible(const E& expr) {
return true;
}
template <typename E>
static constexpr auto shape(const E& expr) {
if (!compatible(expr)) throw std::runtime_error("uncompatible operands");
using shape_type = remove_cvref_t<decltype(expr.shape())>;
constexpr std::size_t rows = shape_type::template sget<0>();
constexpr std::size_t cols = shape_type::template sget<1>();
if constexpr (rows == dynamic_extent || cols == dynamic_extent) {
return dynamic_shape<cols, rows>{ shape_type::template get<1>(), shape_type::template get<0>() };
} else { } else {
return rhs.shape(); return static_shape<cols, rows>{};
} }
} }
template <typename LT, typename R> template <typename E>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const { constexpr auto operator()(std::size_t index, const E& expr) const {
return lhs * rhs.coeff(index); const std::size_t rows = expr.shape().template get<0>();
const std::size_t cols = expr.shape().template get<1>();
return expr.coeff(((index % rows) * cols) + (index / rows));
}
};
// TODO: introduce dynamic reshape
template <typename S, typename = std::enable_if_t<::cenet::math::detail::is_static_shape_v<S>>>
struct reshape {
template <typename E>
static constexpr bool compatible(const E& expr) {
using shape_type = remove_cvref_t<decltype(expr.shape())>;
if constexpr (!::cenet::math::detail::is_static_shape<shape_type>::value) {
return false;
} else {
return shape_type::size == S::size;
}
}
template <typename E>
static constexpr auto shape(const E& expr) {
if (!compatible(expr)) throw std::runtime_error("uncompatible operands");
return S{};
}
template <typename E>
constexpr auto operator()(std::size_t index, const E& expr) const {
return expr.coeff(index);
} }
}; };
+83 -47
View File
@@ -17,7 +17,7 @@ namespace cenet {
namespace math { namespace math {
template <typename T, std::size_t... Dims> template <typename T, std::size_t... Dims>
class tensor { class tensor : public expression_tag, public ops_provider<tensor<T, Dims...>> {
public: public:
using traits = tensor_traits<tensor>; using traits = tensor_traits<tensor>;
using value_type = typename traits::value_type; using value_type = typename traits::value_type;
@@ -25,15 +25,19 @@ public:
using view_type = tensor_view<value_type, Dims...>; using view_type = tensor_view<value_type, Dims...>;
using constant_view_type = tensor_view<constant_value_type, Dims...>; using constant_view_type = tensor_view<constant_value_type, Dims...>;
using shape_type = std::conditional_t<traits::dynamic, dynamic_shape<Dims...>, static_shape<Dims...>>; using shape_type = std::conditional_t<traits::dynamic, dynamic_shape<Dims...>, static_shape<Dims...>>;
public:
template <typename ST>
using with_storage = typename traits::template with_storage_t<ST>;
public: public:
tensor() { tensor() {
if constexpr (traits::dynamic) { if constexpr (traits::dynamic) {
m_items = nullptr; m_items = nullptr;
m_shape = {}; m_shape = {};
} else if constexpr (traits::inline_storage) { } else if constexpr (traits::inline_storage) {
std::memset(m_items, 0, sizeof(m_items)); view().fill();
} else { } else {
m_items = new value_type[traits::size]; m_items = new value_type[traits::size];
view().fill();
} }
} }
@@ -72,7 +76,7 @@ public:
tensor(const tensor& other) tensor(const tensor& other)
: m_shape(other.m_shape) { : m_shape(other.m_shape) {
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{}); dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{}); dyn_copy(other.m_items, std::make_index_sequence<sizeof...(Dims)>{});
} }
tensor& operator=(const tensor& other) { tensor& operator=(const tensor& other) {
@@ -85,70 +89,90 @@ public:
} }
public: public:
template <typename E, template <typename E,
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && typename = std::enable_if_t<detail::is_expression_v<E> && !std::is_same_v<std::decay_t<E>, tensor>>>
shape_type::template compatible<typename detail::expression_result<E>::type>()>> tensor(E&& exprFwd) { // NOLINT
tensor(E&& expr) { // NOLINT if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
if constexpr (!traits::inline_storage) { if constexpr (!traits::inline_storage) {
if constexpr (traits::dynamic) { if constexpr (traits::dynamic) {
set_dimensions(expr.shape()); set_dimensions(exprFwd.shape());
} else { } else {
m_items = new value_type[traits::size]; m_items = new value_type[traits::size];
} }
} }
for (std::size_t i = 0; i < view().size(); ++i) { E expr = std::forward<E>(exprFwd);
m_items[i] = std::forward<E>(expr).coeff(i); for (std::size_t i = 0; i < size(); ++i) {
m_items[i] = expr.coeff(i);
} }
} }
template <typename E, template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && tensor& operator=(E&& exprFwd) {
std::is_same_v<tensor, typename detail::expression_result<E>::type>>> if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
tensor& operator=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape"); if constexpr (!traits::inline_storage) {
for (std::size_t i = 0; i < view().size(); ++i) { if constexpr (traits::dynamic) {
m_items[i] = std::forward<E>(expr); set_dimensions(exprFwd.shape());
} else {
m_items = new value_type[traits::size];
} }
} }
template <typename E, E expr = std::forward<E>(exprFwd);
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator+=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] += std::forward<E>(expr); m_items[i] = expr.coeff(i);
}
} }
template <typename E, return *this;
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator-=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] -= std::forward<E>(expr);
}
} }
template <typename E, template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && tensor& operator+=(E&& exprFwd) {
std::is_same_v<tensor, typename detail::expression_result<E>::type>>> if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
tensor& operator*=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape"); E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] *= std::forward<E>(expr); m_items[i] += expr.coeff(i);
}
} }
template <typename E, return *this;
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator/=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] /= std::forward<E>(expr);
} }
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator-=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] -= expr.coeff(i);
}
return *this;
}
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator*=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] *= expr.coeff(i);
}
return *this;
}
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator/=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] /= expr;
}
return *this;
} }
public: public:
view_type view() { return { m_items, m_shape }; } view_type view() { return { m_items, m_shape }; }
@@ -156,6 +180,16 @@ public:
explicit operator view_type() { return view(); } explicit operator view_type() { return view(); }
explicit operator constant_view_type() const { return view(); } explicit operator constant_view_type() const { return view(); }
public:
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
decltype(auto) operator[](Off off) {
return view()[off];
}
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
decltype(auto) operator[](Off off) const {
return view()[off];
}
public: public:
template <typename... RtDims, template <typename... RtDims,
typename = std::enable_if_t<( typename = std::enable_if_t<(
@@ -228,12 +262,14 @@ private:
private: private:
template <std::size_t... Is> template <std::size_t... Is>
void dyn_alloc(std::index_sequence<Is...>) { void dyn_alloc(std::index_sequence<Is...>) {
m_items = new value_type[(m_shape.dimensions[Is] * ...)]; if constexpr (!traits::inline_storage) {
m_items = new value_type[size()];
}
} }
template <std::size_t... Is> template <std::size_t... Is>
void dyn_copy(const value_type* src, std::index_sequence<Is...>) { void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
std::memcpy(m_items, src, sizeof(*m_items) * (m_shape.dimensions[Is] * ... * 1)); std::memcpy(m_items, src, sizeof(*m_items) * size());
} }
void release() { void release() {
+3
View File
@@ -14,6 +14,9 @@ struct inline_storage {
using value_type = T; using value_type = T;
}; };
struct heap_storage_tag {};
struct inline_storage_tag {};
template <typename T, std::size_t... Dims> template <typename T, std::size_t... Dims>
class tensor_view; class tensor_view;
+149 -29
View File
@@ -36,20 +36,18 @@ struct static_shape : shape<Dims...> {
return compatible_impl<T>::value; return compatible_impl<T>::value;
} }
template <std::size_t... RDims>
bool operator==(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) && ((Dims == RDims) && ...);
}
template <std::size_t... RDims>
bool operator!=(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) != sizeof...(RDims) || ((Dims != RDims) || ...);
}
template <std::size_t I> template <std::size_t I>
constexpr auto get() const { constexpr auto get() const {
return get_impl<I, Dims...>::value; return get_impl<I, Dims...>::value;
} }
template <std::size_t I>
static constexpr auto sget() {
return get_impl<I, Dims...>::value;
}
static constexpr auto rank = sizeof...(Dims);
static constexpr auto score = sizeof...(Dims);
private: private:
template <typename T> template <typename T>
struct compatible_impl : std::false_type {}; struct compatible_impl : std::false_type {};
@@ -65,12 +63,56 @@ private:
struct get_impl<0, First, Rest...> { struct get_impl<0, First, Rest...> {
static constexpr auto value = First; static constexpr auto value = First;
}; };
private:
template <std::size_t S, std::size_t...>
struct size_impl {
static constexpr auto value = S;
};
template <std::size_t S, std::size_t First, std::size_t... Rest>
struct size_impl<S, First, Rest...> : size_impl<First * S, Rest...> {};
public:
static constexpr auto size = size_impl<1, Dims...>::value;
template <std::size_t Start = 0, typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
constexpr std::size_t off_count = sizeof...(Offs);
static_assert(off_count > 0);
static_assert(Start + off_count <= sizeof...(Dims));
return calculate_offset_impl<off_count - 1, Start>(offs) * trailing_product<Start + off_count>();
}
private:
template <std::size_t I, std::size_t Start, typename... Offs>
std::size_t calculate_offset_impl(const std::tuple<Offs...>& offs) const {
if constexpr (I == 0) {
return std::get<0>(offs);
} else {
return (calculate_offset_impl<I - 1, Start>(offs) * get<Start + I>()) + std::get<I>(offs);
}
}
template <std::size_t I>
std::size_t trailing_product() const {
if constexpr (I == sizeof...(Dims)) {
return 1;
} else {
return get<I>() * trailing_product<I + 1>();
}
}
}; };
template <std::size_t... Dims> template <std::size_t... Dims>
struct dynamic_shape : shape<Dims...> { struct dynamic_shape : shape<Dims...> {
dynamic_shape() = default; dynamic_shape() = default;
template <typename... RDims,
typename = std::enable_if_t<(sizeof...(RDims) == sizeof...(Dims)) && (std::is_integral_v<RDims> && ...)>>
explicit dynamic_shape(RDims... rtDimensions) {
store_impl<0>(rtDimensions...);
}
template <std::size_t ExtRank, typename = std::enable_if_t<(ExtRank >= sizeof...(Dims))>> template <std::size_t ExtRank, typename = std::enable_if_t<(ExtRank >= sizeof...(Dims))>>
explicit dynamic_shape(const dynamic_shape<ExtRank>& oth) { explicit dynamic_shape(const dynamic_shape<ExtRank>& oth) {
constexpr std::size_t ext_offset = ExtRank - sizeof...(Dims); constexpr std::size_t ext_offset = ExtRank - sizeof...(Dims);
@@ -89,23 +131,16 @@ struct dynamic_shape : shape<Dims...> {
return compatible_impl<T>::value; return compatible_impl<T>::value;
} }
template <std::size_t... RDims>
bool operator==(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) &&
compare_impl<decltype(rhs), RDims...>(std::make_index_sequence<sizeof...(Dims)>{}, rhs);
}
template <std::size_t... RDims>
bool operator==(const dynamic_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) &&
compare_impl<decltype(rhs), RDims...>(std::make_index_sequence<sizeof...(Dims)>{}, rhs);
}
template <std::size_t I> template <std::size_t I>
constexpr auto get() const { constexpr auto get() const {
return get_impl<I, Dims...>::value == dynamic_extent ? dimensions[I] : get_impl<I, Dims...>::value; return get_impl<I, Dims...>::value == dynamic_extent ? dimensions[I] : get_impl<I, Dims...>::value;
} }
template <std::size_t I>
static constexpr auto sget() {
return get_impl<I, Dims...>::value;
}
std::size_t dimensions[sizeof...(Dims)]{}; std::size_t dimensions[sizeof...(Dims)]{};
private: private:
template <typename T> template <typename T>
@@ -115,13 +150,9 @@ private:
struct compatible_impl<tensor<T, OthDims...>> struct compatible_impl<tensor<T, OthDims...>>
: std::conditional_t<((Dims == dynamic_extent || Dims == OthDims) && ...), std::true_type, std::false_type> {}; : std::conditional_t<((Dims == dynamic_extent || Dims == OthDims) && ...), std::true_type, std::false_type> {};
template <template <std::size_t...> class L, template <template <std::size_t...> class R, std::size_t... RDims, std::size_t... Is>
std::size_t... LDims, constexpr bool compare_impl(std::index_sequence<Is...>, const R<RDims...>& rhs) const {
template <std::size_t...> class R, return ((get<Is>() == rhs.template get<Is>()) && ...);
std::size_t... RDims,
std::size_t... Is>
static constexpr bool compare_impl(std::index_sequence<Is...>, const L<LDims...>& lhs, const R<RDims...>& rhs) {
return ((lhs.template get<Is>() == rhs.template get<Is>()) && ...);
} }
template <std::size_t I, std::size_t First, std::size_t... Rest> template <std::size_t I, std::size_t First, std::size_t... Rest>
@@ -131,6 +162,51 @@ private:
struct get_impl<0, First, Rest...> { struct get_impl<0, First, Rest...> {
static constexpr auto value = First; static constexpr auto value = First;
}; };
template <std::size_t Score, std::size_t...>
struct score_impl {
static constexpr auto value = Score;
};
template <std::size_t Score, std::size_t First, std::size_t... Rest>
struct score_impl<Score, First, Rest...> : score_impl<Score + ((First != dynamic_extent) ? 1 : 0), Rest...> {};
template <std::size_t I, typename RDim, typename... RDims, typename = std::enable_if_t<(I < sizeof...(Dims))>>
void store_impl(RDim first, RDims... rest) {
dimensions[I] = first;
store_impl<I + 1>(rest...);
}
public:
static constexpr auto rank = sizeof...(Dims);
static constexpr auto score = score_impl<0, Dims...>::value;
template <std::size_t Start = 0, typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
constexpr std::size_t off_count = sizeof...(Offs);
static_assert(off_count > 0);
static_assert(Start + off_count <= sizeof...(Dims));
return calculate_offset_impl<off_count - 1, Start>(offs) * trailing_product<Start + off_count>();
}
private:
template <std::size_t I, std::size_t Start, typename... Offs>
std::size_t calculate_offset_impl(const std::tuple<Offs...>& offs) const {
if constexpr (I == 0) {
return std::get<0>(offs);
} else {
return (calculate_offset_impl<I - 1, Start>(offs) * get<Start + I>()) + std::get<I>(offs);
}
}
template <std::size_t I>
std::size_t trailing_product() const {
if constexpr (I == sizeof...(Dims)) {
return 1;
} else {
return get<I>() * trailing_product<I + 1>();
}
}
}; };
namespace detail { namespace detail {
@@ -141,6 +217,13 @@ struct is_static_shape : std::false_type {};
template <std::size_t... Dims> template <std::size_t... Dims>
struct is_static_shape<static_shape<Dims...>> : std::true_type {}; struct is_static_shape<static_shape<Dims...>> : std::true_type {};
template <std::size_t... Dims>
struct is_static_shape_var : std::true_type {};
template <std::size_t First, std::size_t... Rest>
struct is_static_shape_var<First, Rest...>
: std::conditional_t<(First == dynamic_extent), std::false_type, is_static_shape_var<Rest...>> {};
template <typename T> template <typename T>
inline constexpr auto is_static_shape_v = is_static_shape<T>::value; inline constexpr auto is_static_shape_v = is_static_shape<T>::value;
@@ -170,8 +253,45 @@ struct is_shape_equivalent<L<LFirst, LRest...>, R<RFirst, RRest...>>
template <template <std::size_t...> class L, template <std::size_t...> class R> template <template <std::size_t...> class L, template <std::size_t...> class R>
struct is_shape_equivalent<L<>, R<>> : std::true_type {}; struct is_shape_equivalent<L<>, R<>> : std::true_type {};
template <typename L, typename R, typename = void>
struct best_shape {};
template <template <std::size_t...> class T, std::size_t... Dims, typename O>
struct best_shape<T<Dims...>, O> {
using type = T<Dims...>;
static constexpr bool valid = true;
static constexpr bool left = true;
};
template <template <std::size_t...> class T, std::size_t... Dims, typename O>
struct best_shape<O, T<Dims...>> {
using type = T<Dims...>;
static constexpr bool valid = true;
static constexpr bool left = false;
};
template <template <std::size_t...> class L,
std::size_t... LDims,
template <std::size_t...> class R,
std::size_t... RDims>
struct best_shape<L<LDims...>, R<RDims...>> {
static constexpr bool valid = sizeof...(LDims) == sizeof...(RDims);
static constexpr bool left = L<RDims...>::score >= R<LDims...>::score;
using type = std::enable_if_t<valid, std::conditional_t<left, L<LDims...>, R<RDims...>>>;
};
template <std::size_t... Dims>
struct shape_of_impl {
using type = std::conditional_t<is_static_shape_var<Dims...>::value, static_shape<Dims...>, dynamic_shape<Dims...>>;
};
} // namespace detail } // namespace detail
template <std::size_t... Dims>
using shape_of = typename detail::shape_of_impl<Dims...>::type;
template <template <std::size_t...> class L, template <template <std::size_t...> class L,
std::size_t... LDims, std::size_t... LDims,
template <std::size_t...> class R, template <std::size_t...> class R,
+22
View File
@@ -73,6 +73,25 @@ struct is_tensor_dynamic<tensor<T, dynamic_extent, Rest...>> : std::true_type {}
template <typename T> template <typename T>
static constexpr auto is_tensor_dynamic_v = is_tensor_dynamic<T>::value; static constexpr auto is_tensor_dynamic_v = is_tensor_dynamic<T>::value;
namespace detail {
template <typename>
struct tensor_with_storage {};
template <>
struct tensor_with_storage<heap_storage_tag> {
template <typename T, std::size_t... Dims>
using type = tensor<detach_storage_t<T>, Dims...>;
};
template <>
struct tensor_with_storage<inline_storage_tag> {
template <typename T, std::size_t... Dims>
using type = tensor<inline_storage<detach_storage_t<T>>, Dims...>;
};
} // namespace detail
template <typename T> template <typename T>
struct tensor_traits {}; struct tensor_traits {};
@@ -91,6 +110,9 @@ struct tensor_traits<tensor<T, Dims...>> {
static constexpr std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> dimensions = { Dims... }; static constexpr std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> dimensions = { Dims... };
static constexpr std::size_t size = dynamic ? dynamic_extent : (Dims * ... * 1); static constexpr std::size_t size = dynamic ? dynamic_extent : (Dims * ... * 1);
template <typename ST>
using with_storage_t = typename detail::tensor_with_storage<ST>::template type<T, Dims...>;
}; };
} // namespace math } // namespace math
+22 -20
View File
@@ -8,6 +8,7 @@
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <random>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@@ -15,7 +16,7 @@ namespace cenet {
namespace math { namespace math {
template <typename T, std::size_t... Dims> template <typename T, std::size_t... Dims>
class tensor_view { class tensor_view : public expression_tag, public ops_provider<tensor_view<T, Dims...>> {
static_assert(std::is_arithmetic_v<T>); static_assert(std::is_arithmetic_v<T>);
template <typename, std::size_t...> template <typename, std::size_t...>
@@ -32,8 +33,10 @@ public:
typename = std::enable_if_t<( typename = std::enable_if_t<(
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>> sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
decltype(auto) slice(Offs... offs) { decltype(auto) slice(Offs... offs) {
auto* ptr = m_view + calculate_offset(std::make_tuple(offs...)); auto* ptr = m_view + m_shape.calculate_offset(std::make_tuple(offs...));
if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr; if constexpr (sizeof...(Offs) == sizeof...(Dims))
return *ptr;
else
return inner_view<T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{}); return inner_view<T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
} }
@@ -41,8 +44,10 @@ public:
typename = std::enable_if_t<( typename = std::enable_if_t<(
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>> sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
decltype(auto) slice(Offs... offs) const { decltype(auto) slice(Offs... offs) const {
const auto* ptr = m_view + calculate_offset(std::make_tuple(offs...)); const auto* ptr = m_view + m_shape.calculate_offset(std::make_tuple(offs...));
if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr; if constexpr (sizeof...(Offs) == sizeof...(Dims))
return *ptr;
else
return inner_view<const T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{}); return inner_view<const T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
} }
public: public:
@@ -55,19 +60,6 @@ public:
decltype(auto) operator[](Off off) const { decltype(auto) operator[](Off off) const {
return slice(off); return slice(off);
} }
private:
template <typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
return calculate_offset_impl<sizeof...(Offs) - 1, sizeof...(Dims) - sizeof...(Offs)>(offs);
}
template <std::size_t I, std::size_t Start, typename... Offs>
std::size_t calculate_offset_impl(const std::tuple<Offs...>& offs) const {
if constexpr (I == 0)
return std::get<I>(offs) * dimension<Start + I>();
else
return (calculate_offset_impl<I - 1, Start>(offs) + std::get<I>(offs)) * dimension<Start + I>();
}
public: public:
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); } constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
@@ -91,10 +83,20 @@ public:
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) { void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
offset = std::min(offset, size()); offset = std::min(offset, size());
std::memcpy(m_view + offset, source, std::min(length, size() - offset)); std::memcpy(m_view + offset, source, std::min(length, size() - offset) * sizeof(*m_view));
} }
void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size()); } void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size() * sizeof(*m_view)); }
template <typename Dist>
void fill_random(Dist dist) {
static std::random_device s_rd;
static std::mt19937 s_mt(s_rd());
for (std::size_t i = 0; i < size(); ++i) {
m_view[i] = dist(s_mt);
}
}
public: public:
value_type& coeff(std::size_t index) { return m_view[index]; } value_type& coeff(std::size_t index) { return m_view[index]; }
const value_type& coeff(std::size_t index) const { return m_view[index]; } const value_type& coeff(std::size_t index) const { return m_view[index]; }
+15
View File
@@ -0,0 +1,15 @@
#ifndef CENET_MATH_TYPE_TRAITS_HPP
#define CENET_MATH_TYPE_TRAITS_HPP
#include <type_traits>
namespace cenet {
namespace math {
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
}
} // namespace cenet
#endif // CENET_MATH_TYPE_TRAITS_HPP
+31 -25
View File
@@ -40,7 +40,11 @@ public:
using input_type = Input; using input_type = Input;
using output_type = typename output_layer_type::output_type; using output_type = typename 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 m_output; }
public:
struct loss {
double value;
};
public: public:
void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence<sizeof...(Layers)>{}); } void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence<sizeof...(Layers)>{}); }
private: private:
@@ -66,27 +70,31 @@ private:
(get_layer<I>().fill_random(dist), ...); (get_layer<I>().fill_random(dist), ...);
} }
public: public:
const output_type& feed(const input_type& input) { output_type feed(input_type input) { return feed_impl<0>(std::move(input)); }
feed<sizeof...(Layers) - 1>(input);
return get_layer<sizeof...(Layers) - 1>().output;
}
private: private:
template <std::size_t I> template <std::size_t I, typename Current>
auto feed(const input_type& input) { auto feed_impl(Current&& current) {
if constexpr (I == 0) { if constexpr (I == sizeof...(Layers)) {
return get_layer<I>().forward(input); return std::forward<Current>(current);
} else { } else {
return get_layer<I>().forward(feed<I - 1>(input)); return feed_impl<I + 1>(get_layer<I>().feed(std::forward<Current>(current)));
} }
} }
public: public:
struct learning_state final { struct learning_state final {
friend class network;
void reset() { void reset() {
m_count = 0; m_count = 0;
reset(std::make_index_sequence<sizeof...(Layers)>{}); reset(std::make_index_sequence<sizeof...(Layers)>{});
} }
template <std::size_t I, typename = std::enable_if_t<(I < sizeof...(Layers))>>
decltype(auto) get() {
return std::get<I>(m_layers);
}
void increment() { ++m_count; }
auto count() const { return m_count; }
private: private:
template <std::size_t... I> template <std::size_t... I>
void reset(std::index_sequence<I...>) { void reset(std::index_sequence<I...>) {
@@ -106,20 +114,17 @@ public:
typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers; typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
}; };
public: public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) { template <typename Loss, typename LState>
feed(input); void backward(const Loss& loss, LState& state) {
auto outputErr = get_output() - expected; get_layer<0>().backward(state.template get<0>(), backward_chain<sizeof...(Layers) - 1>(state, loss.gradient));
get_layer<0>().backward(input, state.increment();
std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
state.m_count += 1;
} }
private: private:
template <std::size_t I, typename ErrorType> template <std::size_t I, typename LState, typename ErrorType>
auto backprop_chain(learning_state& state, ErrorType error) { auto backward_chain(LState& state, ErrorType error) {
if constexpr (I != 0) { if constexpr (I != 0) {
auto next = get_layer<I>().backward(get_layer<I - 1>().output, std::get<I>(state.m_layers), error); auto next = get_layer<I>().backward(state.template get<I>(), error);
return backprop_chain<I - 1>(state, next); return backward_chain<I - 1>(state, next);
} else { } else {
return error; return error;
} }
@@ -131,16 +136,17 @@ public:
private: private:
template <std::size_t... I> template <std::size_t... I>
void apply(learning_state& state, double rate, std::index_sequence<I...>) { void apply(learning_state& state, double rate, std::index_sequence<I...>) {
(std::get<I>(m_layers).apply_grad(std::get<I>(state.m_layers), state.m_count, rate), ...); (std::get<I>(m_layers).apply_grad(state.template get<I>(), state.count(), rate), ...);
} }
public: public:
void train(const input_type& input, const output_type& expected, double learningRate) { void train(const input_type& input, const output_type& expected, double learningRate) {
learning_state state; learning_state state;
backprop(input, expected, state); backward(input, expected, state);
apply(state, learningRate); apply(state, learningRate);
} }
private: private:
layer_types m_layers; layer_types m_layers;
output_type m_output;
}; };
} // namespace cenet } // namespace cenet
BIN
View File
Binary file not shown.