Compare commits

..
4 Commits
19 changed files with 772 additions and 1278 deletions
+2 -6
View File
@@ -5,12 +5,8 @@ project(cenet CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(cenet INTERFACE
include/cenet/mat.hpp
include/cenet/tensor.hpp
include/cenet/layer.hpp
include/cenet/network.hpp
include/cenet/cenet.hpp)
file(GLOB_RECURSE CENET_HEADERS "include/*.hpp")
add_library(cenet INTERFACE ${CENET_HEADERS})
target_include_directories(cenet INTERFACE include/)
add_executable(xor example/xor.cpp)
+2 -2
View File
@@ -146,9 +146,9 @@ int main(void) {
state->reset();
for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) {
auto output = std::move(mnistNet->feed(trainSet[i + j].xs));
auto output = mnistNet->feed(trainSet[i + j].xs, *state);
auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output);
mnistNet->backward(loss, *state);
state->backward(*mnistNet, loss);
}
mnistNet->apply(*state, learningRate);
}
+14 -12
View File
@@ -11,12 +11,13 @@
static std::uniform_real_distribution<> dist(-1, 1);
int main(void) {
static constexpr float s_trainData[4] = {
0, // 0 ^ 0
1, // 1 ^ 0
1, // 0 ^ 1
0, // 1 ^ 1
};
static cenet::math::matrix<cenet::math::inline_storage<float>, 1, 1> s_trainData[4] = {};
for (std::size_t i = 0; i < 4; ++i) {
const bool x0 = (i & 1U) != 0;
const bool x1 = (i & 2U) != 0;
s_trainData[i].view().fill(x0 != x1 ? 1.0F : 0.0F);
}
// network net;
using network_type = cenet::network<cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2>,
@@ -26,6 +27,8 @@ int main(void) {
cenet::layers::sigmoid>;
network_type xorNet;
network_type::learning_state learningState;
static constexpr const char* NETWORK_PATH = "./xor.nn";
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
@@ -38,22 +41,21 @@ int main(void) {
std::size_t gen = 0;
network_type::learning_state state;
while (gen <= 10'000'000) {
state.reset();
learningState.reset();
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 output = xorNet.feed(xs, learningState);
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
xorNet.backward(loss, state);
learningState.backward(xorNet, loss);
}
xorNet.apply(state, learning_late);
xorNet.apply(learningState, learning_late);
double acc = 0.0;
@@ -63,7 +65,7 @@ int main(void) {
xs.coeff(1) = static_cast<float>(i > 1);
float yHat = xorNet.feed(xs).coeff(0);
float error = yHat - s_trainData[i];
float error = yHat - s_trainData[i].coeff(0);
if ((gen % 1000) == 0) {
std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n";
+2 -530
View File
@@ -1,9 +1,7 @@
#ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP
#include "mat.hpp"
#include "math/tensor.hpp"
#include "tensor.hpp"
#include <array>
#include <cstddef>
@@ -18,24 +16,6 @@ namespace cenet {
namespace detail {
template <typename T>
struct is_dense : std::false_type {};
template <std::size_t N, typename T>
struct is_dense<mat<1, N, T>> : std::true_type {};
template <typename T>
static constexpr auto is_dense_v = is_dense<T>::value;
template <typename T>
struct is_tensor : std::false_type {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
template <typename T>
struct is_tokens : std::false_type {};
@@ -54,7 +34,7 @@ struct layer_info {
protected:
template <class NN, std::size_t I>
struct input_type_s {
using type = typename std::tuple_element_t<I - 1, typename NN::layer_types>::output_type;
using type = typename std::template tuple_element_t<I - 1, typename NN::layer_types>::output_type;
};
template <class NN>
@@ -66,516 +46,8 @@ protected:
using input_inner_t = typename T::inner;
};
template <std::size_t Features, typename T = float>
class dense_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = mat<1, Features, T>;
static constexpr std::size_t INPUT_FEATURES = input_type::COLS;
static constexpr std::size_t OUTPUT_FEATURES = Features;
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES, T>;
using biases_type = mat<1, OUTPUT_FEATURES, T>;
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;
input_type input;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
T scale = std::sqrt(2.0 / static_cast<T>(INPUT_FEATURES));
weights = decltype(weights)::random(dist) * scale;
biases = decltype(biases){};
}
auto feed(input_type&& input) {
this->input = std::move(input);
return (this->input * weights) + biases;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
grad.weights += input.transpose() * prevErr;
grad.biases += prevErr;
return prevErr * 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_FEATURES; ++row) {
for (std::size_t col = 0; col < OUTPUT_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 < OUTPUT_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_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = input_type;
output_type output;
struct gradient {
void reset() {}
};
static float sigmoid(float in) { return 1 / (1 + std::exp(-in)); }
static double sigmoid(double in) { return 1 / (1 + std::exp(-in)); }
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
auto feed(input_type&& input) {
output.apply(std::move(input), [](auto unusd, auto in) { return sigmoid(in); });
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
}
void apply_grad(gradient&, double, double) {}
};
};
class relu_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class 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;
input_type input;
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 feed(input_type&& input) {
output_type output;
output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
this->input = std::move(input);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) const {
return prevErr.apply(input, [](auto in, auto 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,
typename T = float>
class conv2d_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(input_type::RANK == 3);
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static_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 = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<T, 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;
input_type input;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr T fanIn = static_cast<T>(IN_CHANS * KernelSize * KernelSize);
const T scale = std::sqrt(2.0 / fanIn);
weights = decltype(weights)::random(dist);
weights *= scale;
biases = decltype(biases){};
}
auto feed(input_type&& input) {
output_type 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 += input[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output[oc][oy][ox] = value;
}
}
}
this->input = std::move(input);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
input_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 auto 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[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, typename T = float>
class maxpool_layer : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(std::is_same_v<typename input_type::inner_type, T>);
static_assert(input_type::RANK == 3);
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static constexpr std::size_t 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 = tensor<T, 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;
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[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 network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static constexpr std::size_t FEATURES = input_type::SIZE;
using output_type = mat<1, FEATURES, typename input_type::inner_type>;
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;
std::copy(input.begin(), input.end(), output.data());
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
template <std::size_t VocabSize, std::size_t EmbedDims>
class tok2vec_layer : public layer_info {
class tok2vec_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
+132 -90
View File
@@ -1,23 +1,28 @@
#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"
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "cenet/layers/retained.hpp"
#include <cmath>
#include <iostream>
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;
struct conv2d final : public layer_tag {
static constexpr auto retain = retain::Input;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
using input_type = typename traits::input_type;
static_assert(math::is_tensor_v<input_type>);
static_assert(input_type::shape_type::rank == 3);
@@ -44,30 +49,9 @@ private:
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());
@@ -89,8 +73,7 @@ private:
biases.view().fill();
}
template <typename Fwd>
auto feed(Fwd&& fwd) {
auto feed(const input_type& input) {
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) {
@@ -106,7 +89,7 @@ private:
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];
value += input[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
@@ -116,12 +99,56 @@ private:
}
}
}
retained = std::forward<Fwd>(fwd);
return output;
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
using input_type = typename traits::input_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 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>;
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();
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
typename input_type::template with_storage<math::heap_storage_tag> backpropErr;
backpropErr.view().fill();
@@ -130,7 +157,7 @@ private:
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;
biases[oc] += err;
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
@@ -144,9 +171,9 @@ private:
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;
weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err;
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err;
backpropErr[ic][iy][ix] += data.weights[oc][ic][ky][kx] * err;
}
}
}
@@ -158,8 +185,8 @@ private:
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {
++grad.time;
void apply(data<N, I>& data, double divisor, double rate) {
++time;
constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999;
@@ -169,46 +196,45 @@ private:
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;
double avgGrad = 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;
momentumWeights[oc][ic][ky][kx] =
(beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad);
varianceWeights[oc][ic][ky][kx] =
(beta2 * 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));
auto momentumCorrected = momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, time));
weights[oc][ic][ky][kx] -=
data.weights[oc][ic][ky][kx] -=
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
}
}
}
auto avgGrad = grad.biases[oc] / divisor;
auto avgGrad = 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;
momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad);
varianceBiases[oc] = (beta2 * 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));
auto momentumCorrected = momentumBiases[oc] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceBiases[oc] / (1.0 - std::pow(beta2, time));
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
data.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;
struct maxpool final : public layer_tag {
static constexpr auto retain = retain::Input;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
using input_type = typename traits::input_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");
@@ -225,12 +251,6 @@ private:
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) {}
@@ -238,7 +258,7 @@ private:
template <typename Dist>
void fill_random(const Dist& dist) {}
auto feed(input_type&& input) {
auto feed(const 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) {
@@ -255,13 +275,29 @@ private:
}
}
}
this->input = std::move(input);
return output;
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
using input_type = typename traits::input_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;
void reset() {}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
input_type backpropErr;
backpropErr.view().fill();
@@ -271,15 +307,15 @@ private:
std::size_t maxY = oy * Stride;
std::size_t maxX = ox * Stride;
auto maxValue = input[ch][maxY][maxX];
auto maxValue = retained[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];
if (retained[ch][yIdx][xIdx] > maxValue) {
maxValue = retained[ch][yIdx][xIdx];
maxY = yIdx;
maxX = xIdx;
}
@@ -295,17 +331,18 @@ private:
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
void apply(data<N, I>&, double, double) {}
};
};
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;
struct flatten final : public layer_tag {
static constexpr auto retain = retain::None;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
using input_type = typename traits::input_type;
static_assert(math::is_tensor_v<input_type>);
static_assert(!input_type::traits::dynamic, "dynamic input to flatten is currently unsupported");
@@ -315,10 +352,6 @@ private:
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) {}
@@ -330,13 +363,22 @@ private:
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) {
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
using input_type = typename traits::input_type;
void reset() {}
template <typename Error, typename R>
auto backward(const data<N, I>& data, R, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
}
void apply_grad(gradient& grad, double divisor, double rate) {}
void apply(data<N, I>&, double, double) {}
};
};
+105 -85
View File
@@ -5,22 +5,27 @@
#ifndef CENET_LAYERS_DENSE_HPP
#define CENET_LAYERS_DENSE_HPP
#include "../layer.hpp"
#include "../math/tensor_fwd.hpp"
#include "../network.hpp"
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "./retained.hpp"
#include <cmath>
#include <iostream>
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;
struct dense final : public layer_tag {
static constexpr auto retain = retain::Input;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
using input_type = typename traits::input_type;
using value_type = typename input_type::value_type;
using output_type = math::matrix<value_type, 1, Features>;
@@ -29,31 +34,9 @@ private:
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());
@@ -74,20 +57,49 @@ private:
template <typename Fwd>
auto feed(Fwd&& fwd) {
retained = std::forward<Fwd>(fwd);
return retained.matmul(weights) + biases;
return std::forward<Fwd>(fwd).matmul(weights) + biases;
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<dense, N, I>>;
using input_type = typename traits::input_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>;
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();
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) {
grad.weights += retained.transpose().matmul(prevErr);
grad.biases += prevErr;
auto backward(const data<N, I>& data, const input_type& retained, Error&& prevErr) {
weights += retained.transpose().matmul(prevErr);
biases += prevErr;
return std::forward<Error>(prevErr).matmul(weights.transpose());
return std::forward<Error>(prevErr).matmul(data.weights.transpose());
}
void apply_grad(gradient& grad, double divisor, double rate) {
++grad.time;
void apply(data<N, I>& data, double divisor, double rate) {
++time;
constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999;
@@ -95,49 +107,44 @@ private:
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;
auto avgGrad = 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);
momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad);
varianceWeights[row][col] =
(beta2 * 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));
auto momentumCorrected = momentumWeights[row][col] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceWeights[row][col] / (1.0 - std::pow(beta2, time));
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
data.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;
double avgGrad = 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);
momentumBiases[0][col] = (beta1 * momentumBiases[0][col]) + ((1.0 - beta1) * avgGrad);
varianceBiases[0][col] = (beta2 * 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));
auto momentumCorrected = momentumBiases[0][col] / (1.0 - std::pow(beta1, time));
auto varianceCorrected = varianceBiases[0][col] / (1.0 - std::pow(beta2, time));
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
data.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;
struct sigmoid final : public layer_tag {
static constexpr auto retain = retain::Output;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<sigmoid, N, I>>;
using input_type = typename traits::input_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) {}
@@ -147,34 +154,39 @@ private:
template <typename Fwd>
auto feed(Fwd&& fwd) {
return retained = std::forward<Fwd>(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
return std::forward<Fwd>(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<sigmoid, N, I>>;
using input_type = typename traits::input_type;
using output_type = input_type;
void reset() {}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) const {
auto backward(const data<N, I>&, const output_type& retained, Error&& prevErr) const {
return std::forward<Error>(prevErr) * retained *
(static_cast<typename output_type::value_type>(1) - retained);
}
void apply_grad(gradient&, double, double) {}
void apply(data<N, I>&, 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;
struct relu final : public layer_tag {
static constexpr auto retain = retain::Input;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<relu, N, I>>;
using input_type = typename traits::input_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) {}
@@ -184,17 +196,25 @@ private:
template <typename Fwd>
auto feed(Fwd&& fwd) {
retained = std::forward<Fwd>(fwd);
return retained.apply([](auto in) { return in > 0.0 ? in : 0.0; });
return std::forward<Fwd>(fwd).apply([](auto in) { return in > 0.0 ? in : 0.0; });
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<relu, N, I>>;
using input_type = typename traits::input_type;
void reset() {}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) const {
auto backward(const data<N, I>&, const input_type& retained, 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) {}
void apply(data<N, I>&, double, double) {}
};
};
+22
View File
@@ -0,0 +1,22 @@
#ifndef CENET_LAYERS_LAYER_FWD_HPP
#define CENET_LAYERS_LAYER_FWD_HPP
#include <cstddef>
namespace cenet {
namespace layers {
struct layer_tag {};
template <typename L, typename N, std::size_t I>
struct network_layer {
using layer_type = L;
using network_type = N;
static constexpr auto position = I;
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_LAYER_FWD_HPP
+50
View File
@@ -0,0 +1,50 @@
#ifndef CENET_LAYERS_LAYER_TRAITS_HPP
#define CENET_LAYERS_LAYER_TRAITS_HPP
#include "../network_fwd.hpp"
#include "./layer_fwd.hpp"
#include "cenet/network_traits.hpp"
#include <cstddef>
#include <type_traits>
namespace cenet {
namespace layers {
namespace detail {
template <typename T>
struct is_layer : std::is_base_of<layer_tag, T> {};
template <typename L, typename... Args>
struct is_layer<network_layer<L, Args...>> : is_layer<L> {};
template <typename T>
static constexpr auto is_layer_v = is_layer<T>::value;
template <typename N, std::size_t I>
struct layer_input {};
template <typename In, typename... LR, std::size_t I>
struct layer_input<network<In, LR...>, I> {
using type = typename ::cenet::detail::
layer_for_t<::cenet::detail::layer_at_t<I - 1, network<In, LR...>>, network<In, LR...>, I - 1>::output_type;
};
template <typename In, typename... LR>
struct layer_input<network<In, LR...>, 0> {
using type = In;
};
template <typename T>
struct layer_traits {};
template <typename L, typename N, std::size_t I>
struct layer_traits<network_layer<L, N, I>> : network_layer<L, N, I> {
using input_type = typename layer_input<N, I>::type;
};
} // namespace detail
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_LAYER_TRAITS_HPP
+16
View File
@@ -0,0 +1,16 @@
#ifndef CENET_LAYERS_RETAINED_HPP
#define CENET_LAYERS_RETAINED_HPP
namespace cenet {
namespace layers {
enum class retain {
None,
Input,
Output,
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_RETAINED_HPP
-300
View File
@@ -1,300 +0,0 @@
#ifndef CENET_MAT_HPP
#define CENET_MAT_HPP
#include <cstddef>
#include <cstring>
#include <random>
#include <type_traits>
namespace cenet {
template <std::size_t N, typename T = double, typename = std::enable_if_t<(N >= 1)>>
class mat_col {
template <std::size_t M, std::size_t N2, typename T2, typename>
friend class mat;
private:
mat_col(T* data)
: m_data(data) {}
public:
T& operator[](std::size_t idx) { return m_data[idx]; }
const T& operator[](std::size_t idx) const { return m_data[idx]; }
private:
T* m_data;
};
template <std::size_t M, std::size_t N, typename T = double, typename = std::enable_if_t<(M >= 1 && N >= 1)>>
class mat {
public:
static constexpr std::size_t ROWS = M;
static constexpr std::size_t COLS = N;
using col_type = mat_col<N, T>;
using inner_type = T;
public:
mat() { std::memset(m_items, 0, sizeof(m_items)); }
mat(T init) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] = init;
}
}
}
mat(col_type col) {
static_assert((M == 1), "Invalid");
std::memcpy(m_items, col.m_data, sizeof(m_items));
}
~mat() = default;
mat(mat&& other) noexcept { std::memcpy(m_items, other.m_items, sizeof(m_items)); }
mat& operator=(mat&& other) noexcept {
if (this == &other) return *this;
std::memcpy(m_items, other.m_items, sizeof(m_items));
return *this;
}
mat(const mat& other) { std::memcpy(m_items, other.m_items, sizeof(m_items)); }
mat& operator=(const mat& other) {
if (this == &other) return *this;
std::memcpy(m_items, other.m_items, sizeof(m_items));
return *this;
}
public:
template <typename Dist>
static mat<M, N, T> random(Dist dist) {
static std::random_device s_rd;
static std::mt19937 s_mt(s_rd());
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = dist(s_mt);
}
}
return res;
}
public:
mat_col<N, T> operator[](std::size_t col) { return { m_items + (col * N) }; }
mat_col<N, const T> operator[](std::size_t col) const { return { m_items + (col * N) }; }
public:
mat operator+(const mat& rhs) const {
mat res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = (*this)[i][j] + rhs[i][j];
}
}
return res;
}
mat& operator+=(const mat& rhs) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] += rhs[i][j];
}
}
return *this;
}
mat operator-(const mat& rhs) const {
mat res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = (*this)[i][j] - rhs[i][j];
}
}
return res;
}
mat& operator-=(const mat& rhs) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] -= rhs[i][j];
}
}
return *this;
}
public:
mat hadamard(const mat& rhs) const {
mat res = *this;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] *= rhs[i][j];
}
}
return res;
}
public:
mat<N, M, T> transpose() const {
mat<N, M, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[j][i] = (*this)[i][j];
}
}
return res;
}
public:
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; }
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; }
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; }
private:
T m_items[M * N];
};
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator+(T scalar, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = scalar + rhs[i][j];
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator-(T scalar, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = scalar - rhs[i][j];
}
}
return res;
}
template <std::size_t N, typename T>
mat<1, N, T> operator+(T scalar, const mat_col<N, T>& rhs) {
mat<1, N, T> res;
for (std::size_t j = 0; j < N; ++j) {
res[0][j] = scalar + rhs[j];
}
return res;
}
template <std::size_t N, typename T>
mat<1, N, T> operator-(T scalar, const mat_col<N, T>& rhs) {
mat<1, N, T> res;
for (std::size_t j = 0; j < N; ++j) {
res[0][j] = scalar - rhs[j];
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator*(const mat<M, N, T>& lhs, T rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs[i][j] * rhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator*(T lhs, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = rhs[i][j] * lhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, std::size_t P, typename T>
mat<M, P, T> operator*(const mat<M, N, T>& lhs, const mat<N, P, T>& rhs) {
mat<M, P, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < P; ++j) {
for (std::size_t k = 0; k < N; ++k) {
res[i][j] += lhs[i][k] * rhs[k][j];
}
}
}
return res;
}
template <std::size_t M, std::size_t P, typename T>
mat<M, P, T> operator*(const mat<M, 1, T>& lhs, const mat_col<P, T>& rhs) {
mat<M, P, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < P; ++j) {
res[i][j] += lhs[i][0] * rhs[j];
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator/(const mat<M, N, T>& lhs, T rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs[i][j] / rhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator/(T lhs, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs / rhs[i][j];
}
}
return res;
}
} // namespace cenet
#endif // CENET_MAT_HPP
+44
View File
@@ -1,6 +1,7 @@
#ifndef CENET_MATH_EXPR_HPP
#define CENET_MATH_EXPR_HPP
#include "cenet/math/tensor_traits.hpp"
#include "ops.hpp"
#include "type_traits.hpp"
@@ -28,31 +29,63 @@ struct ops_provider {
return { self(), std::forward<R>(rhs) };
}
template <typename R>
binary_expression<CRTP, R, ops::matmul> matmul(R&& rhs) const {
if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(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) };
}
template <typename Func>
unary_expression<CRTP, ops::apply<Func>> apply(Func&& func) const {
if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<Func>(func) };
}
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) };
}
template <typename R, typename Func>
binary_expression<CRTP, R, ops::apply<Func>> apply(R&& rhs, Func&& func) const {
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() };
}
unary_expression<CRTP, ops::transpose> transpose() const {
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() };
}
template <typename S>
unary_expression<CRTP, ops::reshape<S>> reshape() const {
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() };
}
private:
decltype(auto) self() & { return reinterpret_cast<CRTP&>(*this); }
decltype(auto) self() && { return reinterpret_cast<CRTP&&>(*this); }
decltype(auto) self() const& { return reinterpret_cast<const CRTP&>(*this); }
decltype(auto) self() const&& { return reinterpret_cast<const CRTP&&>(*this); }
};
namespace detail {
@@ -152,6 +185,17 @@ binary_expression<L, R, Op> operator/(L&& lhs, R&& rhs) {
return { std::forward<L>(lhs), std::forward<R>(rhs) };
}
template <typename T>
constexpr decltype(auto) eval(T&& fwd) {
if constexpr (detail::is_expression_v<T>) {
auto tensor = tensor_from_shape<decltype(fwd.coeff(std::declval<std::size_t>()))>(fwd.shape());
tensor = std::forward<T>(fwd);
return tensor;
} else {
return std::forward<T>(fwd);
}
}
} // namespace math
} // namespace cenet
+1 -3
View File
@@ -111,11 +111,9 @@ public:
tensor& operator=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
if constexpr (!traits::inline_storage) {
if constexpr (traits::dynamic) {
if (m_shape != exprFwd.shape()) {
set_dimensions(exprFwd.shape());
} else {
m_items = new value_type[traits::size];
}
}
+24
View File
@@ -1,6 +1,8 @@
#ifndef CENET_MATH_TENSOR_TRAITS_HPP
#define CENET_MATH_TENSOR_TRAITS_HPP
#include "cenet/math/tensor_shape.hpp"
#include "cenet/math/type_traits.hpp"
#include "tensor_fwd.hpp"
#include <type_traits>
@@ -90,6 +92,19 @@ struct tensor_with_storage<inline_storage_tag> {
using type = tensor<inline_storage<detach_storage_t<T>>, Dims...>;
};
template <typename T, typename Shape>
struct tensor_from_shape {};
template <typename T, std::size_t... Dims>
struct tensor_from_shape<T, static_shape<Dims...>> {
using type = tensor<T, Dims...>;
};
template <typename T, std::size_t... Dims>
struct tensor_from_shape<T, dynamic_shape<Dims...>> {
using type = tensor<T, Dims...>;
};
} // namespace detail
template <typename T>
@@ -115,6 +130,15 @@ struct tensor_traits<tensor<T, Dims...>> {
using with_storage_t = typename detail::tensor_with_storage<ST>::template type<T, Dims...>;
};
template <typename T, typename Shape>
constexpr decltype(auto) tensor_from_shape(const Shape& shape) {
typename detail::tensor_from_shape<T, remove_cvref_t<Shape>>::type tensor;
if constexpr (!detail::is_static_shape_v<Shape>) {
tensor.set_dimensions(shape);
}
return tensor;
}
} // namespace math
} // namespace cenet
+117 -60
View File
@@ -1,6 +1,10 @@
#ifndef CENET_NETWORK_HPP
#define CENET_NETWORK_HPP
#include "./network_traits.hpp"
#include "cenet/layers/retained.hpp"
#include "cenet/math/expr.hpp"
#include <cstddef>
#include <istream>
#include <ostream>
@@ -12,33 +16,11 @@ namespace cenet {
template <typename Input, typename... Layers>
class network {
friend class layer_info;
private:
template <typename Seq>
struct layer_types_gen {};
template <std::size_t... I>
struct layer_types_gen<std::index_sequence<I...>> {
using type = std::tuple<typename Layers::template inner<network, I>...>;
};
using layer_types = typename layer_types_gen<std::make_index_sequence<sizeof...(Layers)>>::type;
using output_layer_type = std::tuple_element_t<sizeof...(Layers) - 1, layer_types>;
template <std::size_t I>
using layer_input_t = typename std::tuple_element_t<I, layer_types>::input_type;
private:
template <std::size_t I>
auto& get_layer() {
return std::get<I>(m_layers);
}
template <std::size_t I>
const auto& get_layer() const {
return std::get<I>(m_layers);
}
public:
using input_type = Input;
using output_type = typename output_layer_type::output_type;
using traits = network_traits<network>;
using input_type = typename traits::input_type;
using output_type = typename traits::output_type;
public:
const output_type& get_output() const { return m_output; }
public:
@@ -50,14 +32,14 @@ public:
private:
template <std::size_t... I>
void dump_network(std::ostream& os, std::index_sequence<I...>) const {
(get_layer<I>().dump(os), ...);
(at<I>().dump(os), ...);
}
public:
void load_network(std::istream& is) { load_network(is, std::make_index_sequence<sizeof...(Layers)>{}); }
private:
template <std::size_t... I>
void load_network(std::istream& is, std::index_sequence<I...>) {
(get_layer<I>().load(is), ...);
(at<I>().load(is), ...);
}
public:
template <typename Dist>
@@ -67,7 +49,7 @@ public:
private:
template <typename Dist, std::size_t... I>
void fill_random(const Dist& dist, std::index_sequence<I...>) {
(get_layer<I>().fill_random(dist), ...);
(at<I>().fill_random(dist), ...);
}
public:
output_type feed(input_type input) { return feed_impl<0>(std::move(input)); }
@@ -77,75 +59,150 @@ private:
if constexpr (I == sizeof...(Layers)) {
return std::forward<Current>(current);
} else {
return feed_impl<I + 1>(get_layer<I>().feed(std::forward<Current>(current)));
return feed_impl<I + 1>(at<I>().feed(std::forward<Current>(current)));
}
}
private:
// TODO: pass in the optimizer
struct layers_grad_gen {
template <std::size_t I, typename LF, typename... LR>
struct impl {
using type = decltype(std::tuple_cat(std::tuple<typename LF::template grad<network, I>>{},
std::declval<typename impl<I + 1, LR...>::type>()));
};
template <std::size_t I, typename LF>
struct impl<I, LF> {
using type = std::tuple<typename LF::template grad<network, I>>;
};
using type = typename impl<0, Layers...>::type;
};
public:
struct learning_state final {
friend class network;
void reset() {
m_count = 0;
reset(std::make_index_sequence<sizeof...(Layers)>{});
}
template <std::size_t I, typename = std::enable_if_t<(I < sizeof...(Layers))>>
decltype(auto) get() {
template <std::size_t I>
decltype(auto) at() {
return std::get<I>(m_layers);
}
void increment() { ++m_count; }
auto count() const { return m_count; }
template <typename Loss>
void backward(const network& network, const Loss& loss) {
at<0>().backward(network.template at<0>(),
retained_for<0>(),
backward_chain<sizeof...(Layers) - 1>(network, loss.gradient));
++m_count;
}
private:
template <std::size_t... I>
void reset(std::index_sequence<I...>) {
(std::get<I>(m_layers).reset(), ...);
}
private:
template <typename Seq>
struct gen {};
template <std::size_t I, typename Error>
auto backward_chain(const network& network, Error&& error) {
if constexpr (I != 0) {
return backward_chain<I - 1>(network,
at<I>().backward(network.template at<I>(), retained_for<I>(), std::forward<Error>(error)));
} else {
return std::forward<Error>(error);
}
}
template <std::size_t... I>
struct gen<std::index_sequence<I...>> {
using type = std::tuple<typename Layers::template inner<network, I>::gradient...>;
};
struct empty {};
template <std::size_t I>
decltype(auto) retained_for() const {
if constexpr (detail::layer_retains_v<network, I, layers::retain::Input>) {
return std::get<I>(m_retained);
} else if constexpr (detail::layer_retains_v<network, I, layers::retain::Output>) {
return std::get<I + 1>(m_retained);
} else {
return empty{};
}
}
private:
std::size_t m_count = 0;
typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct
typename layers_grad_gen::type m_layers;
};
public:
template <typename Loss, typename LState>
void backward(const Loss& loss, LState& state) {
get_layer<0>().backward(state.template get<0>(), backward_chain<sizeof...(Layers) - 1>(state, loss.gradient));
state.increment();
}
output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); }
private:
template <std::size_t I, typename LState, typename ErrorType>
auto backward_chain(LState& state, ErrorType error) {
if constexpr (I != 0) {
auto next = get_layer<I>().backward(state.template get<I>(), error);
return backward_chain<I - 1>(state, next);
template <std::size_t I, typename Current>
auto feed_impl(Current&& current, learning_state& state) {
if constexpr (I == sizeof...(Layers)) {
return std::forward<Current>(current);
} else {
return error;
if constexpr (detail::layer_retains_v<network, I, layers::retain::Input>) {
std::get<I>(state.m_retained) = current;
}
auto next = at<I>().feed(std::forward<Current>(current));
if constexpr (detail::layer_retains_v<network, I, layers::retain::Output>) {
std::get<I + 1>(state.m_retained) = next;
}
return feed_impl<I + 1>(std::move(next), state);
}
}
public:
void apply(learning_state& state, double rate) {
apply(state, rate, std::make_index_sequence<sizeof...(Layers)>{});
void apply(learning_state& state, double learningRate) {
apply(state, learningRate, std::make_index_sequence<sizeof...(Layers)>{});
}
private:
template <std::size_t... I>
void apply(learning_state& state, double rate, std::index_sequence<I...>) {
(std::get<I>(m_layers).apply_grad(state.template get<I>(), state.count(), rate), ...);
(std::get<I>(state.m_layers).apply(at<I>(), state.count(), rate), ...);
}
public:
void train(const input_type& input, const output_type& expected, double learningRate) {
learning_state state;
backward(input, expected, state);
apply(state, learningRate);
template <std::size_t I>
decltype(auto) at() {
return std::get<I>(m_layers);
}
template <std::size_t I>
decltype(auto) at() const {
return std::get<I>(m_layers);
}
private:
layer_types m_layers;
struct layers_data_gen {
template <std::size_t I, typename LF, typename... LR>
struct impl {
using type = decltype(std::tuple_cat(std::tuple<typename LF::template data<network, I>>{},
std::declval<typename impl<I + 1, LR...>::type>()));
};
template <std::size_t I, typename LF>
struct impl<I, LF> {
using type = std::tuple<typename LF::template data<network, I>>;
};
template <std::size_t I, std::size_t J, typename LF, typename... LR>
struct at : at<I - 1, J, LR...> {};
template <std::size_t J, typename LF, typename... LR>
struct at<0, J, LF, LR...> {
using type = typename LF::template data<network, J>;
};
using type = typename impl<0, Layers...>::type;
};
public:
template <std::size_t I>
using layer = typename layers_data_gen::template at<I, I, Layers...>::type;
private:
typename layers_data_gen::type m_layers;
output_type m_output;
};
+11
View File
@@ -0,0 +1,11 @@
#ifndef CENET_NETWORK_FWD_HPP
#define CENET_NETWORK_FWD_HPP
namespace cenet {
template <typename I, typename... Layers>
class network;
}
#endif // CENET_NETWORK_FWD_HPP
+102
View File
@@ -0,0 +1,102 @@
#ifndef CENET_NETWORK_TRAITS_HPP
#define CENET_NETWORK_TRAITS_HPP
#include "./layers/retained.hpp"
#include "./network_fwd.hpp"
#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>
namespace cenet {
namespace detail {
template <std::size_t At, typename T>
struct layer_at {};
template <std::size_t At, typename I, typename LF, typename... LR>
struct layer_at<At, network<I, LF, LR...>> {
static_assert(At <= sizeof...(LR));
using type = typename layer_at<At - 1, network<I, LR...>>::type;
};
template <typename I, typename LF, typename... LR>
struct layer_at<0, network<I, LF, LR...>> {
using type = LF;
};
template <std::size_t At, typename T>
using layer_at_t = typename layer_at<At, T>::type;
template <typename L, typename N, std::size_t I>
using layer_for_t = typename L::template data<N, I>;
template <typename N, std::size_t At, layers::retain Retain>
struct layer_retains : std::conditional_t<layer_at_t<At, N>::retain == Retain, std::true_type, std::false_type> {};
template <typename N, std::size_t At, layers::retain Retain>
inline constexpr auto layer_retains_v = layer_retains<N, At, Retain>::value;
template <typename N>
struct network_retained {};
template <typename In, typename... Ls>
struct network_retained<network<In, Ls...>> {
private:
using network_type = network<In, Ls...>;
struct empty {};
template <std::size_t... Is>
static constexpr auto generate(std::index_sequence<Is...>) {
if constexpr (layer_retains_v<network_type, 0, layers::retain::Input>) {
return std::tuple_cat(std::tuple<In>{}, generate_layer<Is>()...);
} else {
return std::tuple_cat(std::tuple<empty>{}, generate_layer<Is>()...);
}
}
template <std::size_t I>
static constexpr auto generate_layer() {
if constexpr (I + 1 >= sizeof...(Ls)) { // Last layer
if constexpr (layer_retains_v<network_type, I, layers::retain::Output>) {
return std::tuple<typename layer_for_t<layer_at_t<I, network_type>, network_type, I>::output_type>{};
} else {
return std::tuple<empty>{};
}
} else {
if constexpr (layer_retains_v<network_type, I, layers::retain::Output> ||
layer_retains_v<network_type, I + 1, layers::retain::Input>) {
return std::tuple<typename layer_for_t<layer_at_t<I, network_type>, network_type, I>::output_type>{};
} else {
return std::tuple<empty>{};
}
}
}
public:
using type = decltype(generate(std::make_index_sequence<sizeof...(Ls)>{}));
};
template <typename T>
using network_retained_t = typename network_retained<T>::type;
} // namespace detail
template <typename T>
struct network_traits {};
template <typename I, typename... Layers>
struct network_traits<network<I, Layers...>> {
using network_type = network<I, Layers...>;
using input_type = I;
using output_layer = detail::layer_at_t<sizeof...(Layers) - 1, network_type>;
using output_type =
typename detail::layer_for_t<output_layer, network<I, Layers...>, sizeof...(Layers) - 1>::output_type;
};
} // namespace cenet
#endif // CENET_NETWORK_TRAITS_HPP
-188
View File
@@ -1,188 +0,0 @@
#ifndef CENET_TENSOR_HPP
#define CENET_TENSOR_HPP
#include <cstddef>
#include <cstring>
#include <random>
#include <tuple>
#include <type_traits>
#include <utility>
namespace cenet {
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);
using inner_type = T;
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];
};
} // namespace cenet
#endif // CENET_TENSOR_HPP
BIN
View File
Binary file not shown.
+126
View File
@@ -0,0 +1,126 @@
// TODO: write actual tests
#include <algorithm>
#include <cenet/math/expr.hpp>
#include <cenet/math/tensor.hpp>
#include <cenet/math/tensor_fwd.hpp>
#include <cstring>
#include <gtest/gtest.h>
using cenet::math::dynamic_extent;
// Whatever
TEST(Tensor, View) {
cenet::math::tensor<float, 3, 2, 2> tensor;
auto view = tensor.view()[1][1];
}
TEST(Tensor, Ops) {
constexpr float lhsArray[2 * 3] = { 1, 2, 3, 4, 5, 6 };
cenet::math::tensor<float, dynamic_extent, 3> lhs;
lhs.set_dimensions(2, 3);
lhs.view().fill(lhsArray);
constexpr float rhsArray[2 * 3] = { 6, 5, 4, 3, 2, 1 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 3> rhs;
rhs.view().fill(rhsArray);
constexpr float resultArray[2 * 3] = { 6 * 1, 6 * 2, 6 * 3, 6 * 4, 6 * 5, 6 * 6 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 3> result = lhs + rhs - 1;
result *= lhs;
for (std::size_t i = 0; i < result.size(); ++i) {
EXPECT_EQ(result.coeff(i), resultArray[i]);
}
}
TEST(Tensor, MatMul) {
constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 };
constexpr float rhsArray[2 * 2] = { 5, 6, 7, 8 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> lhs;
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> rhs;
lhs.view().fill(lhsArray);
rhs.view().fill(rhsArray);
constexpr float expArray[2 * 2] = { (1 * 5) + (2 * 7), (1 * 6) + (2 * 8), (3 * 5) + (4 * 7), (3 * 6) + (4 * 8) };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> result = lhs.matmul(rhs);
for (std::size_t i = 0; i < result.size(); ++i) {
EXPECT_EQ(result.coeff(i), expArray[i]);
}
}
// MatMul was so good they made a sequel
TEST(Tensor, MatMul2) {
constexpr float lhsArray[3 * 2] = { 1, 2, 5, 6, 7, 8 };
constexpr float rhsArray[2 * 1] = { 3, 4 };
cenet::math::tensor<cenet::math::inline_storage<float>, 3, 2> lhs;
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 1> rhs;
lhs.view().fill(lhsArray);
rhs.view().fill(rhsArray);
constexpr float expArray[3 * 1] = { 11, 39, 53 };
cenet::math::tensor<cenet::math::inline_storage<float>, 3, 1> result = lhs.matmul(rhs);
for (std::size_t i = 0; i < result.size(); ++i) {
EXPECT_EQ(result.coeff(i), expArray[i]);
}
}
TEST(Tensor, Apply) {
constexpr float values[2 * 2] = { 1, 2, 3, 4 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> tensor;
tensor.view().fill(values);
constexpr float expected[2 * 2] = { 1, 4, 9, 16 };
tensor = tensor.apply([](auto val) { return val * val; });
for (std::size_t i = 0; i < tensor.size(); ++i) {
EXPECT_EQ(tensor.coeff(i), expected[i]);
}
}
TEST(Tensor, Apply2) {
constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 };
constexpr float rhsArray[2 * 2] = { 4, 3, 2, 1 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> lhs;
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> rhs;
lhs.view().fill(lhsArray);
rhs.view().fill(rhsArray);
constexpr float expArray[2 * 2] = { 4, 3, 3, 4 };
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> result =
lhs.apply(rhs, [](auto x1, auto x2) { return std::max(x1, x2); });
for (std::size_t i = 0; i < result.size(); ++i) {
EXPECT_EQ(result.coeff(i), expArray[i]);
}
}
TEST(Tensor, Offsets) {
cenet::math::tensor<float, 2, 3, 4> tensor;
for (std::size_t i = 0; i < tensor.size(); ++i)
tensor.coeff(i) = static_cast<float>(i);
EXPECT_EQ(tensor[1][0][0], 12);
EXPECT_EQ(tensor[1][2][0], 20);
EXPECT_EQ(tensor[1][2][3], 23);
}
TEST(Tensor, Offsets2) {
using shape_type = cenet::math::static_shape<2, 3, 4>;
shape_type shape;
EXPECT_EQ(shape.calculate_offset(std::make_tuple(1)), 12);
EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2)), 20);
EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2, 3)), 23);
}