Compare commits
51
Commits
5598ff06cd
...
math
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8b00b32d2
|
||
|
|
f98615fea4
|
||
|
|
3a27df500e
|
||
|
|
dea973ddd6
|
||
|
|
14292b1d97
|
||
|
|
2f24260cbf
|
||
|
|
a9ba1874f1
|
||
|
|
e19b6b499d
|
||
|
|
6455bebb1f
|
||
|
|
f5429c7e23
|
||
|
|
1e76b92c2a
|
||
|
|
d97b65678a
|
||
|
|
f59602e99a
|
||
|
|
7cc35104d4
|
||
|
|
d23905c259
|
||
|
|
961067c28d
|
||
|
|
1e37036bb3
|
||
|
|
367ec2da69
|
||
|
|
4b782a6619
|
||
|
|
c65743e957
|
||
|
|
c96d31a378
|
||
|
|
795915d100
|
||
|
|
377cd5941d
|
||
|
|
a264009629
|
||
|
|
f3e2fb7c58
|
||
|
|
75243e9d08
|
||
|
|
3dfcb754f8
|
||
|
|
78864efba9
|
||
|
|
2267c8d7f8
|
||
|
|
673e068344
|
||
|
|
0eeafe31c4
|
||
|
|
8dee1cbe1f
|
||
|
|
de783ad7b7
|
||
|
|
3fca91e1ea
|
||
|
|
b482010c5d
|
||
|
|
09d23cd568
|
||
|
|
8fe56476ed
|
||
|
|
513413515e
|
||
|
|
2702167244
|
||
|
|
1b8db65330
|
||
|
|
a0ca8e572d
|
||
|
|
bdb0198640
|
||
|
|
e8edbe7b7e
|
||
|
|
5360b4f9b0
|
||
|
|
a4640c4835
|
||
|
|
22bf8db5e8
|
||
|
|
814050baca
|
||
|
|
0734de1386
|
||
|
|
1f95dd51db
|
||
|
|
94276e68d3
|
||
|
|
a47302d532
|
+49
-14
@@ -2,21 +2,56 @@ cmake_minimum_required(VERSION 3.14)
|
|||||||
|
|
||||||
project(cenet CXX)
|
project(cenet CXX)
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 20)
|
option(CENET_BUILD_TESTS "Compile cenet tests" OFF)
|
||||||
|
option(CENET_BUILD_EXAMPLES "Compile cenet examples" ON)
|
||||||
|
|
||||||
add_library(cenet INTERFACE
|
option(TULIP_DISABLE_SIMD "Disable SIMD backend for tulip" OFF)
|
||||||
include/cenet/mat.hpp
|
|
||||||
include/cenet/tensor.hpp
|
|
||||||
include/cenet/layer.hpp
|
|
||||||
include/cenet/network.hpp
|
|
||||||
include/cenet/cenet.hpp)
|
|
||||||
target_include_directories(cenet INTERFACE include/)
|
|
||||||
|
|
||||||
add_executable(xor example/xor.cpp)
|
file(GLOB_RECURSE TULIP_HEADERS CONFIGURE_DEPENDS "include/tulip/*.hpp")
|
||||||
target_link_libraries(xor PRIVATE cenet)
|
add_library(tulip INTERFACE ${TULIP_HEADERS})
|
||||||
|
target_include_directories(tulip INTERFACE include)
|
||||||
|
target_compile_features(tulip INTERFACE cxx_std_17)
|
||||||
|
add_library(cenet::tulip ALIAS tulip)
|
||||||
|
|
||||||
add_executable(mnist example/mnist.cpp)
|
if(TULIP_DISABLE_SIMD)
|
||||||
target_link_libraries(mnist PRIVATE cenet)
|
target_compile_definitions(tulip INTERFACE TULIP_DISABLE_SIMD)
|
||||||
|
endif()
|
||||||
|
|
||||||
add_executable(tokenizer example/tokenizer.cpp)
|
file(GLOB_RECURSE CENET_HEADERS CONFIGURE_DEPENDS "include/cenet/*.hpp")
|
||||||
target_link_libraries(tokenizer PRIVATE cenet)
|
add_library(cenet INTERFACE ${CENET_HEADERS})
|
||||||
|
target_link_libraries(cenet INTERFACE tulip)
|
||||||
|
target_include_directories(cenet INTERFACE include)
|
||||||
|
target_compile_features(cenet INTERFACE cxx_std_17)
|
||||||
|
add_library(cenet::cenet ALIAS cenet)
|
||||||
|
|
||||||
|
if(CENET_BUILD_EXAMPLES)
|
||||||
|
add_executable(xor example/xor.cpp)
|
||||||
|
target_link_libraries(xor PRIVATE cenet)
|
||||||
|
|
||||||
|
add_executable(mnist example/mnist.cpp)
|
||||||
|
target_link_libraries(mnist PRIVATE cenet)
|
||||||
|
|
||||||
|
add_executable(tokenizer example/tokenizer.cpp)
|
||||||
|
target_link_libraries(tokenizer PRIVATE cenet)
|
||||||
|
|
||||||
|
add_executable(gpt example/gpt.cpp)
|
||||||
|
target_link_libraries(gpt PRIVATE cenet)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(CENET_BUILD_TESTS)
|
||||||
|
include(FetchContent)
|
||||||
|
FetchContent_Declare(
|
||||||
|
googletest
|
||||||
|
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
|
||||||
|
)
|
||||||
|
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||||
|
FetchContent_MakeAvailable(googletest)
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
|
||||||
|
add_executable(math_test test/tensor.cpp)
|
||||||
|
target_link_libraries(math_test GTest::gtest_main cenet)
|
||||||
|
|
||||||
|
include(GoogleTest)
|
||||||
|
gtest_discover_tests(math_test)
|
||||||
|
endif()
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#include "cenet/layers/token.hpp"
|
||||||
|
#include "cenet/network.hpp"
|
||||||
|
#include "tokenizer.hpp"
|
||||||
|
|
||||||
|
#include <cenet/cenet.hpp>
|
||||||
|
#include <iostream>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
static constexpr std::size_t VOCAB_SIZE = 2256;
|
||||||
|
|
||||||
|
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::layers::tok2vec<2256, 512>>;
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
tokenizer<VOCAB_SIZE> bpe;
|
||||||
|
if (!bpe.load("./gpt/shakespeare.bpe")) return 1;
|
||||||
|
std::cout << "Vocabulary loaded!\n";
|
||||||
|
|
||||||
|
auto* gpt = new network_type();
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
+29
-21
@@ -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<tulip::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;
|
tulip::tensor<float, 1, 28, 28> xs{};
|
||||||
cenet::mat<1, 10, float> ys;
|
tulip::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 tulip::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
|
||||||
@@ -130,7 +135,7 @@ int main(void) {
|
|||||||
|
|
||||||
std::ofstream saveFile(NETWORK_PATH, std::ios::out | std::ios::binary);
|
std::ofstream saveFile(NETWORK_PATH, std::ios::out | std::ios::binary);
|
||||||
|
|
||||||
network_type::learning_state* state = new network_type::learning_state();
|
auto* state = new network_type::learning_state<cenet::optim::adam>();
|
||||||
|
|
||||||
for (std::size_t epoch = 0; epoch <= MAX_EPOCHS; ++epoch) {
|
for (std::size_t epoch = 0; epoch <= MAX_EPOCHS; ++epoch) {
|
||||||
shuffle_dataset(trainSet);
|
shuffle_dataset(trainSet);
|
||||||
@@ -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 = mnistNet->feed(trainSet[i + j].xs, *state);
|
||||||
|
auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output);
|
||||||
|
state->backward(*mnistNet, loss);
|
||||||
|
}
|
||||||
mnistNet->apply(*state, learningRate);
|
mnistNet->apply(*state, learningRate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -283,8 +283,8 @@ private:
|
|||||||
file.write(value.data(), static_cast<std::streamsize>(value.size()));
|
file.write(value.data(), static_cast<std::streamsize>(value.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
template <std::size_t... Is>
|
template <typename T, std::size_t... Is>
|
||||||
void dump(std::ofstream& file, auto value, std::index_sequence<Is...>) const {
|
void dump(std::ofstream& file, T value, std::index_sequence<Is...>) const {
|
||||||
char buf[] = { static_cast<char>((value >> (Is << 3ULL)) & 0xFF)... };
|
char buf[] = { static_cast<char>((value >> (Is << 3ULL)) & 0xFF)... };
|
||||||
file.write(buf, sizeof(buf));
|
file.write(buf, sizeof(buf));
|
||||||
}
|
}
|
||||||
@@ -308,7 +308,7 @@ public:
|
|||||||
auto lhs = load_u32(file);
|
auto lhs = load_u32(file);
|
||||||
auto rhs = load_u32(file);
|
auto rhs = load_u32(file);
|
||||||
auto merge = load_u32(file);
|
auto merge = load_u32(file);
|
||||||
m_merges.insert(lhs | (rhs << 32ULL), merge);
|
m_merges.emplace(lhs | (static_cast<std::uint64_t>(rhs) << 32ULL), merge);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -326,7 +326,7 @@ private:
|
|||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
T load(std::ifstream& file) const {
|
T load(std::ifstream& file) const {
|
||||||
return load(file, std::make_index_sequence<sizeof(T)>{});
|
return load<T>(file, std::make_index_sequence<sizeof(T)>{});
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T, std::size_t... Is>
|
template <typename T, std::size_t... Is>
|
||||||
|
|||||||
+37
-23
@@ -1,3 +1,7 @@
|
|||||||
|
#include "cenet/layers/dense.hpp"
|
||||||
|
#include "cenet/loss/mse.hpp"
|
||||||
|
#include "tulip/tensor_fwd.hpp"
|
||||||
|
|
||||||
#include <cenet/cenet.hpp>
|
#include <cenet/cenet.hpp>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
@@ -7,21 +11,24 @@
|
|||||||
static std::uniform_real_distribution<> dist(-1, 1);
|
static std::uniform_real_distribution<> dist(-1, 1);
|
||||||
|
|
||||||
int main(void) {
|
int main(void) {
|
||||||
static constexpr float s_trainData[4] = {
|
static tulip::matrix<tulip::inline_storage<float>, 1, 1> s_trainData[4] = {};
|
||||||
0, // 0 ^ 0
|
for (std::size_t i = 0; i < 4; ++i) {
|
||||||
1, // 1 ^ 0
|
const bool x0 = (i & 1U) != 0;
|
||||||
1, // 0 ^ 1
|
const bool x1 = (i & 2U) != 0;
|
||||||
0, // 1 ^ 1
|
|
||||||
};
|
s_trainData[i].view().fill(x0 != x1 ? 1.0F : 0.0F);
|
||||||
|
}
|
||||||
|
|
||||||
// network net;
|
// network net;
|
||||||
using network_type = cenet::network<cenet::mat<1, 2, float>,
|
using network_type = cenet::network<tulip::matrix<tulip::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;
|
||||||
|
|
||||||
|
network_type::learning_state learningState;
|
||||||
|
|
||||||
static constexpr const char* NETWORK_PATH = "./xor.nn";
|
static constexpr const char* NETWORK_PATH = "./xor.nn";
|
||||||
|
|
||||||
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
|
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
|
||||||
@@ -30,31 +37,38 @@ 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;
|
||||||
|
|
||||||
while (gen <= 10'000'000) {
|
while (gen <= 10'000'000) {
|
||||||
for (std::size_t i = 0; i < 4; ++i) {
|
learningState.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) {
|
||||||
|
tulip::matrix<tulip::inline_storage<float>, 1, 2> xs;
|
||||||
|
xs.coeff(0) = static_cast<float>(i & 1);
|
||||||
|
xs.coeff(1) = static_cast<float>(i > 1);
|
||||||
|
|
||||||
|
auto output = xorNet.feed(xs, learningState);
|
||||||
|
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
|
||||||
|
|
||||||
|
learningState.backward(xorNet, loss);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
xorNet.apply(learningState, 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;
|
tulip::matrix<tulip::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].coeff(0);
|
||||||
|
|
||||||
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;
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
|
// The most useless header
|
||||||
|
// I am keeping it for the memes
|
||||||
|
|
||||||
#ifndef CENET_HPP
|
#ifndef CENET_HPP
|
||||||
#define CENET_HPP
|
#define CENET_HPP
|
||||||
|
|
||||||
#include "layer.hpp" // IWYU pragma: export
|
|
||||||
#include "network.hpp" // IWYU pragma: export
|
#include "network.hpp" // IWYU pragma: export
|
||||||
|
|
||||||
#endif // CENET_HPP
|
#endif // CENET_HPP
|
||||||
|
|||||||
@@ -1,557 +0,0 @@
|
|||||||
#ifndef CENET_LAYER_HPP
|
|
||||||
#define CENET_LAYER_HPP
|
|
||||||
|
|
||||||
#include "mat.hpp"
|
|
||||||
#include "tensor.hpp"
|
|
||||||
|
|
||||||
#include <cstddef>
|
|
||||||
#include <istream>
|
|
||||||
#include <ostream>
|
|
||||||
#include <tuple>
|
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
namespace cenet {
|
|
||||||
|
|
||||||
namespace detail {
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
struct is_dense : std::false_type {};
|
|
||||||
|
|
||||||
template <std::size_t N, typename T>
|
|
||||||
struct is_dense<mat<1, N, T>> : std::true_type {};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
static constexpr auto is_dense_v = is_dense<T>::value;
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
struct is_tensor : std::false_type {};
|
|
||||||
|
|
||||||
template <typename T, std::size_t... Dims>
|
|
||||||
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
static constexpr auto is_tensor_v = is_tensor<T>::value;
|
|
||||||
|
|
||||||
} // namespace detail
|
|
||||||
|
|
||||||
struct layer_info {
|
|
||||||
protected:
|
|
||||||
template <class NN, std::size_t I>
|
|
||||||
struct input_type_s {
|
|
||||||
using type = std::tuple_element_t<I - 1, typename NN::layer_types>::output_type;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <class NN>
|
|
||||||
struct input_type_s<NN, 0> {
|
|
||||||
using type = typename NN::input_type;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
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 = 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;
|
|
||||||
output_type output;
|
|
||||||
|
|
||||||
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& forward(const input_type& input) { return output = (input * weights) + biases; }
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, 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 = 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& forward(const input_type& input) {
|
|
||||||
output.apply(input, [](auto unusd, auto in) { return sigmoid(in); });
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
|
|
||||||
return prevErr.hadamard(output.hadamard(static_cast<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 = input_type_s<NN, I>::type;
|
|
||||||
using output_type = input_type;
|
|
||||||
|
|
||||||
input_type savedInput;
|
|
||||||
output_type output;
|
|
||||||
|
|
||||||
struct gradient {
|
|
||||||
void reset() {}
|
|
||||||
};
|
|
||||||
|
|
||||||
void dump(std::ostream& os) const {}
|
|
||||||
|
|
||||||
void load(std::istream& is) {}
|
|
||||||
|
|
||||||
template <typename Dist>
|
|
||||||
void fill_random(const Dist& dist) {}
|
|
||||||
|
|
||||||
auto& forward(const input_type& input) {
|
|
||||||
savedInput = input;
|
|
||||||
output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
|
|
||||||
return prevErr.apply(savedInput, [](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 = 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;
|
|
||||||
output_type output;
|
|
||||||
|
|
||||||
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& forward(const input_type& input) {
|
|
||||||
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
|
|
||||||
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
||||||
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, 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 = 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>;
|
|
||||||
output_type output;
|
|
||||||
|
|
||||||
struct gradient final {
|
|
||||||
void reset() {}
|
|
||||||
};
|
|
||||||
|
|
||||||
void dump(std::ostream& os) const {}
|
|
||||||
|
|
||||||
void load(std::istream& is) {}
|
|
||||||
|
|
||||||
template <typename Dist>
|
|
||||||
void fill_random(const Dist& dist) {}
|
|
||||||
|
|
||||||
auto& forward(const input_type& input) {
|
|
||||||
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
|
|
||||||
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
|
|
||||||
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, 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 = 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>;
|
|
||||||
output_type output;
|
|
||||||
|
|
||||||
struct gradient final {
|
|
||||||
void reset() {}
|
|
||||||
};
|
|
||||||
|
|
||||||
void dump(std::ostream& os) const {}
|
|
||||||
|
|
||||||
void load(std::istream& is) {}
|
|
||||||
|
|
||||||
template <typename Dist>
|
|
||||||
void fill_random(const Dist& dist) {}
|
|
||||||
|
|
||||||
auto& forward(const input_type& input) {
|
|
||||||
std::copy(input.begin(), input.end(), output.data());
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Error>
|
|
||||||
auto backward(const input_type& input, 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) {}
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace cenet
|
|
||||||
|
|
||||||
#endif // CENET_LAYER_HPP
|
|
||||||
@@ -0,0 +1,437 @@
|
|||||||
|
#ifndef CENET_LAYERS_CONVOLUTIONAL_HPP
|
||||||
|
#define CENET_LAYERS_CONVOLUTIONAL_HPP
|
||||||
|
|
||||||
|
#include "../optim/adam.hpp"
|
||||||
|
#include "./layer_fwd.hpp"
|
||||||
|
#include "./layer_traits.hpp"
|
||||||
|
#include "./retained.hpp"
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include <iostream>
|
||||||
|
#include <tulip/tensor_fwd.hpp>
|
||||||
|
#include <tulip/tensor_shape.hpp>
|
||||||
|
#include <tulip/tensor_traits.hpp>
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace layers {
|
||||||
|
|
||||||
|
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
|
||||||
|
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(tulip::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 = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||||
|
|
||||||
|
using weights_type =
|
||||||
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||||
|
using biases_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS>;
|
||||||
|
|
||||||
|
weights_type weights{};
|
||||||
|
biases_type biases{};
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
auto feed(const input_type& input) {
|
||||||
|
typename output_type::template with_storage<tulip::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 += input[ic][iy][ix] * weights[oc][ic][ky][kx];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output[oc][oy][ox] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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(tulip::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 =
|
||||||
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||||
|
using biases_type = tulip::tensor<tulip::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(const data<N, I>& data, const input_type& retained, Error prevErr) {
|
||||||
|
typename input_type::template with_storage<tulip::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)));
|
||||||
|
|
||||||
|
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)) {
|
||||||
|
|
||||||
|
weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err;
|
||||||
|
|
||||||
|
backpropErr[ic][iy][ix] += data.weights[oc][ic][ky][kx] * err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return backpropErr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
static_assert(false, "unsupported optimizer");
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I>
|
||||||
|
struct optim<N, I, cenet::optim::adam> {
|
||||||
|
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
||||||
|
|
||||||
|
using input_type = typename traits::input_type;
|
||||||
|
static_assert(tulip::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 =
|
||||||
|
tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||||
|
using biases_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS>;
|
||||||
|
|
||||||
|
std::size_t time = 0;
|
||||||
|
|
||||||
|
weights_type momentumWeights{};
|
||||||
|
biases_type momentumBiases{};
|
||||||
|
weights_type varianceWeights{};
|
||||||
|
biases_type varianceBiases{};
|
||||||
|
|
||||||
|
void apply(data<N, I>& data, grad<N, I>& grad, double divisor, double rate) {
|
||||||
|
++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;
|
||||||
|
|
||||||
|
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 = momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, time));
|
||||||
|
auto varianceCorrected = varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, time));
|
||||||
|
|
||||||
|
data.weights[oc][ic][ky][kx] -=
|
||||||
|
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto avgGrad = grad.biases[oc] / divisor;
|
||||||
|
|
||||||
|
momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad);
|
||||||
|
varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad);
|
||||||
|
|
||||||
|
auto momentumCorrected = momentumBiases[oc] / (1.0 - std::pow(beta1, time));
|
||||||
|
auto varianceCorrected = varianceBiases[oc] / (1.0 - std::pow(beta2, time));
|
||||||
|
|
||||||
|
data.biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
|
||||||
|
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(tulip::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 = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||||
|
|
||||||
|
void dump(std::ostream& os) const {}
|
||||||
|
|
||||||
|
void load(std::istream& is) {}
|
||||||
|
|
||||||
|
template <typename Dist>
|
||||||
|
void fill_random(const Dist& dist) {}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(const data<N, I>& data, const input_type& retained, 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 = 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 (retained[ch][yIdx][xIdx] > maxValue) {
|
||||||
|
maxValue = retained[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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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(tulip::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 = tulip::matrix<value_type, 1, FEATURES>;
|
||||||
|
|
||||||
|
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<tulip::shape_of<1, FEATURES>>();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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>();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace layers
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_LAYERS_CONVOLUTIONAL_HPP
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
/**
|
||||||
|
* The "dense" layer class.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef CENET_LAYERS_DENSE_HPP
|
||||||
|
#define CENET_LAYERS_DENSE_HPP
|
||||||
|
|
||||||
|
#include "../optim/adam.hpp"
|
||||||
|
#include "./layer_fwd.hpp"
|
||||||
|
#include "./layer_traits.hpp"
|
||||||
|
#include "./retained.hpp"
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include <iostream>
|
||||||
|
#include <tulip/tensor.hpp>
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace layers {
|
||||||
|
|
||||||
|
template <std::size_t Features>
|
||||||
|
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 = tulip::matrix<value_type, 1, Features>;
|
||||||
|
|
||||||
|
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||||
|
|
||||||
|
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
|
||||||
|
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
|
||||||
|
|
||||||
|
weights_type weights;
|
||||||
|
biases_type biases;
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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 = tulip::matrix<value_type, 1, Features>;
|
||||||
|
|
||||||
|
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||||
|
|
||||||
|
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
|
||||||
|
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
|
||||||
|
|
||||||
|
weights_type weights;
|
||||||
|
biases_type biases;
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
weights.view().fill();
|
||||||
|
biases.view().fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Error>
|
||||||
|
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(data.weights.transpose());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
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 = tulip::matrix<value_type, 1, Features>;
|
||||||
|
|
||||||
|
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||||
|
|
||||||
|
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
|
||||||
|
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
|
||||||
|
|
||||||
|
weights_type weigths;
|
||||||
|
biases_type biases;
|
||||||
|
|
||||||
|
void apply(data<N, I>& data, grad<N, I>& grad, double divisor, double rate) {
|
||||||
|
data.weights -= (grad.weights / divisor) * rate;
|
||||||
|
data.biases -= (grad.biases / divisor) * rate;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I>
|
||||||
|
struct optim<N, I, cenet::optim::adam> {
|
||||||
|
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 = tulip::matrix<value_type, 1, Features>;
|
||||||
|
|
||||||
|
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||||
|
|
||||||
|
using weights_type = tulip::matrix<tulip::inline_storage<value_type>, input_cols, Features>;
|
||||||
|
using biases_type = tulip::matrix<tulip::inline_storage<value_type>, 1, Features>;
|
||||||
|
|
||||||
|
std::size_t time = 0;
|
||||||
|
|
||||||
|
weights_type momentumWeights;
|
||||||
|
biases_type momentumBiases;
|
||||||
|
weights_type varianceWeights;
|
||||||
|
biases_type varianceBiases;
|
||||||
|
|
||||||
|
void apply(data<N, I>& data, grad<N, I>& grad, double divisor, double rate) {
|
||||||
|
++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;
|
||||||
|
|
||||||
|
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 = momentumWeights[row][col] / (1.0 - std::pow(beta1, time));
|
||||||
|
auto varianceCorrected = varianceWeights[row][col] / (1.0 - std::pow(beta2, time));
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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 = momentumBiases[0][col] / (1.0 - std::pow(beta1, time));
|
||||||
|
auto varianceCorrected = varianceBiases[0][col] / (1.0 - std::pow(beta2, time));
|
||||||
|
|
||||||
|
data.biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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).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(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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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).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(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; });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I, class Optim>
|
||||||
|
struct optim {
|
||||||
|
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace layers
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_LAYERS_DENSE_HPP
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#ifndef CENET_LAYERS_LAYER_TRAITS_HPP
|
||||||
|
#define CENET_LAYERS_LAYER_TRAITS_HPP
|
||||||
|
|
||||||
|
#include "../network_fwd.hpp"
|
||||||
|
#include "../network_traits.hpp"
|
||||||
|
#include "./layer_fwd.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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#ifndef CENET_LAYERS_TOKEN_HPP
|
||||||
|
#define CENET_LAYERS_TOKEN_HPP
|
||||||
|
|
||||||
|
#include "./layer_fwd.hpp"
|
||||||
|
#include "./layer_traits.hpp"
|
||||||
|
#include "./retained.hpp"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iostream>
|
||||||
|
#include <random>
|
||||||
|
#include <tulip/tensor.hpp>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace layers {
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct is_tokens : std::false_type {};
|
||||||
|
|
||||||
|
template <std::size_t I>
|
||||||
|
struct is_tokens<std::array<std::uint32_t, I>> : std::true_type {};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct is_tokens<std::vector<std::uint32_t>> : std::true_type {};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static constexpr auto is_tokens_v = is_tokens<T>::value;
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
|
||||||
|
template <std::size_t VocabSize, std::size_t EmbedDims>
|
||||||
|
struct tok2vec 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<tok2vec, N, I>>;
|
||||||
|
|
||||||
|
using input_type = typename traits::input_type;
|
||||||
|
static_assert(detail::is_tokens_v<input_type>);
|
||||||
|
|
||||||
|
static_assert(VocabSize > 0);
|
||||||
|
static_assert(EmbedDims > 0);
|
||||||
|
|
||||||
|
using output_type = tulip::matrix<float, tulip::dynamic_extent, EmbedDims>;
|
||||||
|
using embedding_type = tulip::matrix<float, VocabSize, EmbedDims>;
|
||||||
|
|
||||||
|
embedding_type embedding;
|
||||||
|
|
||||||
|
void dump(std::ostream& os) const {
|
||||||
|
os.write(reinterpret_cast<const char*>(embedding.data()), sizeof(float) * embedding.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void load(std::istream& is) {
|
||||||
|
is.read(reinterpret_cast<char*>(embedding.data()), sizeof(float) * embedding.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Dist>
|
||||||
|
void fill_random(const Dist& dist) {
|
||||||
|
static std::random_device s_rd;
|
||||||
|
static std::mt19937 s_rng(s_rd());
|
||||||
|
|
||||||
|
auto distribution = dist;
|
||||||
|
|
||||||
|
const float scale = 1.0F / std::sqrt(static_cast<float>(EmbedDims));
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < embedding.size(); ++i) {
|
||||||
|
embedding.data()[i] = static_cast<float>(distribution(s_rng)) * scale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto feed(const input_type& input) {
|
||||||
|
output_type output;
|
||||||
|
output.set_dimensions(input.size(), EmbedDims);
|
||||||
|
for (std::size_t i = 0; i < input.size(); ++i) {
|
||||||
|
if (input[i] >= VocabSize) throw std::out_of_range("invalid token!");
|
||||||
|
output.view()[i].fill(embedding.view()[input[i]]);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class N, std::size_t I>
|
||||||
|
struct grad final {
|
||||||
|
using traits = typename detail::layer_traits<network_layer<tok2vec, N, I>>;
|
||||||
|
|
||||||
|
using input_type = typename traits::input_type;
|
||||||
|
static_assert(detail::is_tokens_v<input_type>);
|
||||||
|
|
||||||
|
static_assert(VocabSize > 0);
|
||||||
|
static_assert(EmbedDims > 0);
|
||||||
|
|
||||||
|
using output_type = tulip::matrix<float, tulip::dynamic_extent, EmbedDims>;
|
||||||
|
using embedding_type = tulip::matrix<float, VocabSize, EmbedDims>;
|
||||||
|
|
||||||
|
embedding_type embedding;
|
||||||
|
embedding_type momentum;
|
||||||
|
embedding_type variance;
|
||||||
|
|
||||||
|
std::size_t time = 0;
|
||||||
|
|
||||||
|
void reset() { embedding.view().fill(0); }
|
||||||
|
|
||||||
|
template <typename Error>
|
||||||
|
void backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
|
||||||
|
const auto errorShape = prevErr.shape();
|
||||||
|
if (errorShape.template get<0>() != retained.size() || errorShape.template get<1>() != EmbedDims) {
|
||||||
|
throw std::invalid_argument("unexpected embedding gradient shape");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < retained.size(); ++i) {
|
||||||
|
embedding.view()[retained[i]] += prevErr.view()[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply(data<N, I>& data, double divisor, double rate) {
|
||||||
|
if (divisor <= 0.0) return;
|
||||||
|
|
||||||
|
++time;
|
||||||
|
|
||||||
|
constexpr double beta1 = 0.9;
|
||||||
|
constexpr double beta2 = 0.999;
|
||||||
|
constexpr double epsilon = 1e-8;
|
||||||
|
|
||||||
|
const double correction1 = 1.0 - std::pow(beta1, time);
|
||||||
|
const double correction2 = 1.0 - std::pow(beta2, time);
|
||||||
|
|
||||||
|
float* weightsP = data.embedding.data();
|
||||||
|
float* momentumM = momentum.data();
|
||||||
|
float* varianceP = variance.data();
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < embedding.size(); ++i) {
|
||||||
|
const double avgGrad = static_cast<double>(embedding.coeff(i)) / divisor;
|
||||||
|
|
||||||
|
momentum.coeff(i) = static_cast<float>((beta1 * momentum.coeff(i)) + ((1.0 - beta1) * avgGrad));
|
||||||
|
variance.coeff(i) =
|
||||||
|
static_cast<float>((beta2 * variance.coeff(i)) + ((1.0 - beta2) * avgGrad * avgGrad));
|
||||||
|
|
||||||
|
const double momentumCorrected = momentum.coeff(i) / correction1;
|
||||||
|
const double varianceCorrected = variance.coeff(i) / correction2;
|
||||||
|
|
||||||
|
data.embedding.coeff(i) -=
|
||||||
|
static_cast<float>(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace layers
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_LAYERS_TOKEN_HPP
|
||||||
@@ -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
|
||||||
@@ -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
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
#ifndef CENET_MATH_TENSOR_HPP
|
|
||||||
#define CENET_MATH_TENSOR_HPP
|
|
||||||
|
|
||||||
#include "tensor_fwd.hpp"
|
|
||||||
#include "tensor_traits.hpp"
|
|
||||||
|
|
||||||
#include <cstddef>
|
|
||||||
#include <cstring>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <type_traits>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
namespace cenet {
|
|
||||||
namespace math {
|
|
||||||
|
|
||||||
template <typename T, std::size_t... Dims>
|
|
||||||
class tensor_view {
|
|
||||||
template <typename, std::size_t, std::size_t...>
|
|
||||||
friend class tensor;
|
|
||||||
public:
|
|
||||||
using traits = tensor_traits<tensor<T, Dims...>>;
|
|
||||||
using value_type = traits::value_type;
|
|
||||||
public:
|
|
||||||
private:
|
|
||||||
value_type* m_view;
|
|
||||||
|
|
||||||
std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> m_strides;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T, std::size_t... Dims>
|
|
||||||
class tensor {
|
|
||||||
public:
|
|
||||||
using traits = tensor_traits<tensor>;
|
|
||||||
using value_type = traits::value_type;
|
|
||||||
public:
|
|
||||||
tensor() {
|
|
||||||
if constexpr (traits::dynamic) {
|
|
||||||
m_items = nullptr;
|
|
||||||
} else if constexpr (traits::inplace_storage) {
|
|
||||||
std::memset(m_items, 0, sizeof(m_items));
|
|
||||||
} else {
|
|
||||||
m_items = new value_type[traits::size];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename... RtDims,
|
|
||||||
typename = std::enable_if_t<(
|
|
||||||
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
|
|
||||||
explicit tensor(RtDims... dimensions) {
|
|
||||||
set_dimensions(dimensions...);
|
|
||||||
}
|
|
||||||
|
|
||||||
~tensor() { release(); }
|
|
||||||
|
|
||||||
tensor(tensor&& other) noexcept { *this = std::move(other); }
|
|
||||||
tensor& operator=(tensor&& other) noexcept {
|
|
||||||
if (this == &other) return *this;
|
|
||||||
release();
|
|
||||||
m_items = other.m_items;
|
|
||||||
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
|
|
||||||
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
|
|
||||||
|
|
||||||
other.m_items = nullptr;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
tensor(const tensor& other) { *this = other; }
|
|
||||||
tensor& operator=(const tensor& other) {
|
|
||||||
if (this == &other) return *this;
|
|
||||||
release();
|
|
||||||
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
|
|
||||||
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
|
|
||||||
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
|
|
||||||
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{});
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
public:
|
|
||||||
template <typename... RtDims,
|
|
||||||
typename = std::enable_if_t<(
|
|
||||||
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
|
|
||||||
void set_dimensions(RtDims... dimensions) {
|
|
||||||
if constexpr (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
|
|
||||||
throw std::runtime_error("invalid dynamic tensor dimensions");
|
|
||||||
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
|
|
||||||
|
|
||||||
release();
|
|
||||||
m_items = new value_type[(dimensions * ... * 1)];
|
|
||||||
std::memset(m_items, 0, sizeof(*m_items) * (dimensions * ... * 1));
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
template <typename... RtDims, std::size_t... Is>
|
|
||||||
constexpr bool valid_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
|
|
||||||
return (valid_dim<Is>(dimensions) && ...);
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename RtDim, std::size_t I>
|
|
||||||
constexpr bool valid_dim(RtDim dim) const {
|
|
||||||
return traits::dimensions[I] == dynamic_extent || traits::dimensions[I] == dim;
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
template <typename... RtDims, std::size_t... Is>
|
|
||||||
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
|
|
||||||
return ((m_dimensions[Is] = dimensions) && ...);
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
template <std::size_t... Is>
|
|
||||||
void dyn_alloc(std::index_sequence<Is...>) {
|
|
||||||
m_items = new value_type[(m_dimensions[Is] * ...)];
|
|
||||||
}
|
|
||||||
|
|
||||||
template <std::size_t... Is>
|
|
||||||
void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
|
|
||||||
std::memcpy(m_items, src, sizeof(*m_items) * (m_dimensions[Is] * ... * 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
void release() {
|
|
||||||
if constexpr (!traits::inline_storage) {
|
|
||||||
delete[] m_items;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
traits::storage_type m_items;
|
|
||||||
|
|
||||||
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_dimensions;
|
|
||||||
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_strides;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T, std::size_t M, std::size_t N>
|
|
||||||
using matrix = tensor<T, M, N>;
|
|
||||||
|
|
||||||
} // namespace math
|
|
||||||
} // namespace cenet
|
|
||||||
|
|
||||||
#endif // CENET_MATH_TENSOR_HPP
|
|
||||||
+153
-71
@@ -1,9 +1,14 @@
|
|||||||
#ifndef CENET_NETWORK_HPP
|
#ifndef CENET_NETWORK_HPP
|
||||||
#define CENET_NETWORK_HPP
|
#define CENET_NETWORK_HPP
|
||||||
|
|
||||||
|
#include "./layers/retained.hpp"
|
||||||
|
#include "./network_traits.hpp"
|
||||||
|
#include "./optim/sgd.hpp"
|
||||||
|
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <istream>
|
#include <istream>
|
||||||
#include <ostream>
|
#include <ostream>
|
||||||
|
#include <tulip/expr.hpp>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
@@ -12,48 +17,28 @@ namespace cenet {
|
|||||||
template <typename Input, typename... Layers>
|
template <typename Input, typename... Layers>
|
||||||
class network {
|
class network {
|
||||||
friend class layer_info;
|
friend class layer_info;
|
||||||
private:
|
public:
|
||||||
template <typename Seq>
|
using traits = network_traits<network>;
|
||||||
struct layer_types_gen {};
|
|
||||||
|
|
||||||
template <std::size_t... I>
|
using input_type = typename traits::input_type;
|
||||||
struct layer_types_gen<std::index_sequence<I...>> {
|
using output_type = typename traits::output_type;
|
||||||
using type = std::tuple<typename Layers::template inner<network, I>...>;
|
public:
|
||||||
|
struct loss {
|
||||||
|
double value;
|
||||||
};
|
};
|
||||||
|
|
||||||
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 = output_layer_type::output_type;
|
|
||||||
public:
|
|
||||||
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; }
|
|
||||||
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:
|
||||||
template <std::size_t... I>
|
template <std::size_t... I>
|
||||||
void dump_network(std::ostream& os, std::index_sequence<I...>) const {
|
void dump_network(std::ostream& os, std::index_sequence<I...>) const {
|
||||||
(get_layer<I>().dump(os), ...);
|
(at<I>().dump(os), ...);
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
void load_network(std::istream& is) { load_network(is, std::make_index_sequence<sizeof...(Layers)>{}); }
|
void load_network(std::istream& is) { load_network(is, std::make_index_sequence<sizeof...(Layers)>{}); }
|
||||||
private:
|
private:
|
||||||
template <std::size_t... I>
|
template <std::size_t... I>
|
||||||
void load_network(std::istream& is, std::index_sequence<I...>) {
|
void load_network(std::istream& is, std::index_sequence<I...>) {
|
||||||
(get_layer<I>().load(is), ...);
|
(at<I>().load(is), ...);
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
template <typename Dist>
|
template <typename Dist>
|
||||||
@@ -63,23 +48,52 @@ public:
|
|||||||
private:
|
private:
|
||||||
template <typename Dist, std::size_t... I>
|
template <typename Dist, std::size_t... I>
|
||||||
void fill_random(const Dist& dist, std::index_sequence<I...>) {
|
void fill_random(const Dist& dist, std::index_sequence<I...>) {
|
||||||
(get_layer<I>().fill_random(dist), ...);
|
(at<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);
|
private:
|
||||||
return get_layer<sizeof...(Layers) - 1>().output;
|
template <std::size_t I, typename Current>
|
||||||
|
auto feed_impl(Current&& current) {
|
||||||
|
if constexpr (I == sizeof...(Layers)) {
|
||||||
|
return std::forward<Current>(current);
|
||||||
|
} else {
|
||||||
|
return feed_impl<I + 1>(at<I>().feed(std::forward<Current>(current)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
template <std::size_t I>
|
struct layers_grad_gen {
|
||||||
auto feed(const input_type& input) {
|
template <std::size_t I, typename LF, typename... LR>
|
||||||
if constexpr (I == 0) {
|
struct impl {
|
||||||
return get_layer<I>().forward(input);
|
using type = decltype(std::tuple_cat(std::tuple<typename LF::template grad<network, I>>{},
|
||||||
} else {
|
std::declval<typename impl<I + 1, LR...>::type>()));
|
||||||
return get_layer<I>().forward(feed<I - 1>(input));
|
};
|
||||||
}
|
|
||||||
}
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class Optim>
|
||||||
|
struct layers_optim_gen {
|
||||||
|
template <std::size_t I, typename LF, typename... LR>
|
||||||
|
struct impl {
|
||||||
|
using type = decltype(std::tuple_cat(std::tuple<typename LF::template optim<network, I, Optim>>{},
|
||||||
|
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 optim<network, I, Optim>>;
|
||||||
|
};
|
||||||
|
|
||||||
|
using type = typename impl<0, Layers...>::type;
|
||||||
|
};
|
||||||
public:
|
public:
|
||||||
|
template <class Optim = optim::sgd>
|
||||||
struct learning_state final {
|
struct learning_state final {
|
||||||
friend class network;
|
friend class network;
|
||||||
|
|
||||||
@@ -87,60 +101,128 @@ public:
|
|||||||
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>
|
||||||
|
decltype(auto) at() {
|
||||||
|
return std::get<I>(m_layers);
|
||||||
|
}
|
||||||
|
|
||||||
|
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:
|
private:
|
||||||
template <std::size_t... I>
|
template <std::size_t... I>
|
||||||
void reset(std::index_sequence<I...>) {
|
void reset(std::index_sequence<I...>) {
|
||||||
(std::get<I>(m_layers).reset(), ...);
|
(std::get<I>(m_layers).reset(), ...);
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
template <typename Seq>
|
template <std::size_t I, typename Error>
|
||||||
struct gen {};
|
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 empty {};
|
||||||
struct gen<std::index_sequence<I...>> {
|
|
||||||
using type = std::tuple<typename Layers::template inner<network, I>::gradient...>;
|
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:
|
private:
|
||||||
std::size_t m_count = 0;
|
std::size_t m_count = 0;
|
||||||
|
|
||||||
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;
|
||||||
|
typename layers_optim_gen<Optim>::type m_optimizer;
|
||||||
};
|
};
|
||||||
public:
|
public:
|
||||||
void backprop(const input_type& input, const output_type& expected, learning_state& state) {
|
template <class Optim>
|
||||||
feed(input);
|
output_type feed(input_type input, learning_state<Optim>& state) {
|
||||||
auto outputErr = get_output() - expected;
|
return feed_impl<0>(std::move(input), state);
|
||||||
get_layer<0>().backward(input,
|
|
||||||
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 Current, class Optim>
|
||||||
auto backprop_chain(learning_state& state, ErrorType error) {
|
auto feed_impl(Current&& current, learning_state<Optim>& state) {
|
||||||
if constexpr (I != 0) {
|
if constexpr (I == sizeof...(Layers)) {
|
||||||
auto next = get_layer<I>().backward(get_layer<I - 1>().output, std::get<I>(state.m_layers), error);
|
return std::forward<Current>(current);
|
||||||
return backprop_chain<I - 1>(state, next);
|
|
||||||
} else {
|
} 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:
|
public:
|
||||||
void apply(learning_state& state, double rate) {
|
template <class Optim>
|
||||||
apply(state, rate, std::make_index_sequence<sizeof...(Layers)>{});
|
void apply(learning_state<Optim>& state, double learningRate) {
|
||||||
|
apply(state, learningRate, std::make_index_sequence<sizeof...(Layers)>{});
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
template <std::size_t... I>
|
template <std::size_t... I, class Optim>
|
||||||
void apply(learning_state& state, double rate, std::index_sequence<I...>) {
|
void apply(learning_state<Optim>& 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>(state.m_optimizer).apply(at<I>(), std::get<I>(state.m_layers), state.count(), rate), ...);
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
void train(const input_type& input, const output_type& expected, double learningRate) {
|
template <std::size_t I>
|
||||||
learning_state state;
|
decltype(auto) at() {
|
||||||
backprop(input, expected, state);
|
return std::get<I>(m_layers);
|
||||||
apply(state, learningRate);
|
}
|
||||||
|
|
||||||
|
template <std::size_t I>
|
||||||
|
decltype(auto) at() const {
|
||||||
|
return std::get<I>(m_layers);
|
||||||
}
|
}
|
||||||
private:
|
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;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace cenet
|
} // namespace cenet
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#ifndef CENET_OPTIM_ADAM_HPP
|
||||||
|
#define CENET_OPTIM_ADAM_HPP
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace optim {
|
||||||
|
|
||||||
|
class adam {};
|
||||||
|
|
||||||
|
} // namespace optim
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_OPTIM_ADAM_HPP
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#ifndef CENET_OPTIM_SGD_HPP
|
||||||
|
#define CENET_OPTIM_SGD_HPP
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace optim {
|
||||||
|
|
||||||
|
class sgd {};
|
||||||
|
|
||||||
|
} // namespace optim
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_OPTIM_SGD_HPP
|
||||||
@@ -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
|
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#ifndef TULIP_DISPATCH_HPP
|
||||||
|
#define TULIP_DISPATCH_HPP
|
||||||
|
|
||||||
|
#include "./kernels/elementwise.hpp"
|
||||||
|
#include "./simd/simd.hpp"
|
||||||
|
#include "type_traits.hpp"
|
||||||
|
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace detail {
|
||||||
|
namespace dispatch {
|
||||||
|
|
||||||
|
template <typename Expr, typename Isa, typename = void>
|
||||||
|
struct is_simd_evaluable : std::false_type {};
|
||||||
|
|
||||||
|
template <typename Expr, typename Isa>
|
||||||
|
struct is_simd_evaluable<Expr,
|
||||||
|
Isa,
|
||||||
|
std::void_t<decltype(std::declval<const remove_cvref_t<Expr>&>().template eval_pack<Isa>(std::size_t{}))>>
|
||||||
|
: std::true_type {};
|
||||||
|
|
||||||
|
template <typename Expr, typename Isa>
|
||||||
|
inline constexpr auto is_simd_evaluable_v = is_simd_evaluable<Expr, Isa>::value;
|
||||||
|
|
||||||
|
template <typename T, typename Expr>
|
||||||
|
void elementwise(T* dst, const Expr& expr, std::size_t size) {
|
||||||
|
using value_type = std::remove_cv_t<T>;
|
||||||
|
using expr_value_type = remove_cvref_t<decltype(expr.coeff(std::size_t{}))>;
|
||||||
|
|
||||||
|
using isa = simd::detail::preferred_isa_t<value_type>;
|
||||||
|
|
||||||
|
if constexpr (std::is_same_v<value_type, expr_value_type> && is_simd_evaluable_v<Expr, isa>) {
|
||||||
|
kernels::elementwise<isa>(dst, expr, size);
|
||||||
|
} else {
|
||||||
|
kernels::elementwise_scalar(dst, expr, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace dispatch
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_DISPATCH_HPP
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#ifndef TULIP_EVALUATE_HPP
|
||||||
|
#define TULIP_EVALUATE_HPP
|
||||||
|
|
||||||
|
#include "./dispatch.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename T, typename Expr>
|
||||||
|
void evaluate_elementwise(T* dst, const Expr& expr, std::size_t size) {
|
||||||
|
dispatch::elementwise(dst, expr, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_EVALUATE_HPP
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
#ifndef TULIP_EXPR_HPP
|
||||||
|
#define TULIP_EXPR_HPP
|
||||||
|
|
||||||
|
#include "./ops.hpp"
|
||||||
|
#include "./tensor_traits.hpp"
|
||||||
|
#include "./type_traits.hpp"
|
||||||
|
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
|
||||||
|
struct expression_tag {};
|
||||||
|
struct expression_node_tag : expression_tag {};
|
||||||
|
|
||||||
|
template <typename E, typename Op>
|
||||||
|
struct unary_expression;
|
||||||
|
|
||||||
|
template <typename L, typename R, typename Op>
|
||||||
|
struct binary_expression;
|
||||||
|
|
||||||
|
template <typename CRTP>
|
||||||
|
struct ops_provider {
|
||||||
|
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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename R>
|
||||||
|
binary_expression<const 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 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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename R>
|
||||||
|
binary_expression<const 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<const 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 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<const 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<const 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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
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<const 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<const CRTP&, ops::transpose> transpose() const& {
|
||||||
|
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||||
|
return { self() };
|
||||||
|
}
|
||||||
|
|
||||||
|
unary_expression<CRTP&&, ops::transpose> transpose() && {
|
||||||
|
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||||
|
return { self() };
|
||||||
|
}
|
||||||
|
|
||||||
|
unary_expression<const 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<const CRTP&, ops::reshape<S>> reshape() const& {
|
||||||
|
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() && {
|
||||||
|
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||||
|
return { self() };
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename S>
|
||||||
|
unary_expression<const 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 static_cast<CRTP&>(*this); }
|
||||||
|
decltype(auto) self() && { return static_cast<CRTP&&>(*this); }
|
||||||
|
|
||||||
|
decltype(auto) self() const& { return static_cast<const CRTP&>(*this); }
|
||||||
|
decltype(auto) self() const&& { return static_cast<const CRTP&&>(*this); }
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename 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;
|
||||||
|
|
||||||
|
template <typename T, typename Isa, typename Operand, typename = void>
|
||||||
|
struct is_pack_operand : std::bool_constant<std::is_arithmetic_v<remove_cvref_t<Operand>>> {};
|
||||||
|
|
||||||
|
template <typename T, typename Isa, typename Operand>
|
||||||
|
struct is_pack_operand<T,
|
||||||
|
Isa,
|
||||||
|
Operand,
|
||||||
|
std::void_t<decltype(std::declval<const remove_cvref_t<Operand>&>().template eval_pack<Isa>(std::size_t{}))>>
|
||||||
|
: std::is_same<decltype(std::declval<const remove_cvref_t<Operand>&>().template eval_pack<Isa>(std::size_t{})),
|
||||||
|
simd::detail::pack_t<T, Isa>> {};
|
||||||
|
|
||||||
|
template <typename Op, typename T, typename Isa, typename = void>
|
||||||
|
struct has_pack_apply : std::false_type {};
|
||||||
|
|
||||||
|
template <typename Op, typename T, typename Isa>
|
||||||
|
struct has_pack_apply<Op,
|
||||||
|
T,
|
||||||
|
Isa,
|
||||||
|
std::void_t<decltype(std::declval<const Op&>().template apply_pack<T, Isa>(
|
||||||
|
std::declval<simd::detail::pack_t<T, Isa>>(),
|
||||||
|
std::declval<simd::detail::pack_t<T, Isa>>()))>> : std::true_type {};
|
||||||
|
|
||||||
|
template <typename T, typename Isa, typename Operand>
|
||||||
|
auto eval_pack_operand(const Operand& operand, std::size_t index) {
|
||||||
|
if constexpr (std::is_arithmetic_v<remove_cvref_t<Operand>>) {
|
||||||
|
return simd::detail::broadcast<T, Isa>(static_cast<T>(operand));
|
||||||
|
} else {
|
||||||
|
return operand.template eval_pack<Isa>(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // 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)); }
|
||||||
|
|
||||||
|
using value_type = remove_cvref_t<decltype(std::declval<const binary_expression&>().coeff(std::size_t{}))>;
|
||||||
|
|
||||||
|
template <typename Isa,
|
||||||
|
typename = std::enable_if_t<detail::is_pack_operand<value_type, Isa, lhs_type>::value &&
|
||||||
|
detail::is_pack_operand<value_type, Isa, rhs_type>::value &&
|
||||||
|
detail::has_pack_apply<Op, value_type, Isa>::value>>
|
||||||
|
auto eval_pack(std::size_t index) const {
|
||||||
|
return op.template apply_pack<value_type, Isa>(detail::eval_pack_operand<value_type, Isa>(lhs, index),
|
||||||
|
detail::eval_pack_operand<value_type, Isa>(rhs, index));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename T, typename = void>
|
||||||
|
struct operand {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct operand<T, std::void_t<typename remove_cvref_t<T>::view_type>> {
|
||||||
|
using type = typename remove_cvref_t<T>::view_type;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using operand_t = typename operand<T>::type;
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, remove_cvref_t<T>>;
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
|
||||||
|
template <typename L, typename R, typename Op = ops::plus>
|
||||||
|
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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R, typename Op = ops::minus>
|
||||||
|
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::multiply>
|
||||||
|
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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
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 tulip
|
||||||
|
|
||||||
|
#endif // TULIP_EXPR_HPP
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#ifndef TULIP_KERNELS_ELEMENTWISE_HPP
|
||||||
|
#define TULIP_KERNELS_ELEMENTWISE_HPP
|
||||||
|
|
||||||
|
#include "../simd/simd.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace kernels {
|
||||||
|
|
||||||
|
template <typename T, typename Expr>
|
||||||
|
void elementwise_scalar(T* dst, const Expr& expr, std::size_t size) {
|
||||||
|
for (std::size_t idx = 0; idx < size; ++idx) {
|
||||||
|
dst[idx] = expr.coeff(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Isa, typename T, typename Expr>
|
||||||
|
void elementwise(T* dst, const Expr& expr, std::size_t size) {
|
||||||
|
std::size_t idx = 0;
|
||||||
|
|
||||||
|
constexpr std::size_t width = simd::detail::width_v<T, Isa>;
|
||||||
|
|
||||||
|
for (; idx + width <= size; idx += width) {
|
||||||
|
auto value = expr.template eval_pack<Isa>(idx);
|
||||||
|
simd::detail::store<T, Isa>(dst + idx, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (; idx < size; ++idx) {
|
||||||
|
dst[idx] = expr.coeff(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace kernels
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_KERNELS_ELEMENTWISE_HPP
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
#ifndef TULIP_OPS_HPP
|
||||||
|
#define TULIP_OPS_HPP
|
||||||
|
|
||||||
|
#include "./simd/traits.hpp"
|
||||||
|
#include "./tensor_fwd.hpp"
|
||||||
|
#include "./tensor_shape.hpp"
|
||||||
|
#include "./type_traits.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace ops {
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
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>
|
||||||
|
static constexpr bool compatible(const L& lhs, const R& rhs) {
|
||||||
|
if constexpr (std::is_arithmetic_v<L> || std::is_arithmetic_v<R>) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return lhs.shape() == rhs.shape();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R>
|
||||||
|
static constexpr auto shape(const L& lhs, const R& rhs) {
|
||||||
|
if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
|
||||||
|
using best_shape = tulip::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();
|
||||||
|
} else {
|
||||||
|
return rhs.shape();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R>
|
||||||
|
constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct plus : generic_binary_op<std::plus<>> {
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto apply_pack(simd::detail::pack_t<T, Isa> lhs, simd::detail::pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return simd::detail::add<T, Isa>(lhs, rhs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct minus : generic_binary_op<std::minus<>> {
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto apply_pack(simd::detail::pack_t<T, Isa> lhs, simd::detail::pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return simd::detail::sub<T, Isa>(lhs, rhs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct multiply : generic_binary_op<std::multiplies<>> {
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto apply_pack(simd::detail::pack_t<T, Isa> lhs, simd::detail::pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return simd::detail::mul<T, Isa>(lhs, rhs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct divide : generic_binary_op<std::divides<>> {
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto apply_pack(simd::detail::pack_t<T, Isa> lhs, simd::detail::pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return simd::detail::div<T, Isa>(lhs, rhs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct matmul {
|
||||||
|
template <typename L, typename R>
|
||||||
|
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())>;
|
||||||
|
|
||||||
|
return lhs_shape::rank == 2 && rhs_shape::rank == 2 &&
|
||||||
|
lhs.shape().template get<1>() == rhs.shape().template get<0>();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R>
|
||||||
|
static constexpr auto shape(const L& lhs, const R& rhs) {
|
||||||
|
if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return static_shape<lhs_rows, rhs_cols>{};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R>
|
||||||
|
constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Func>
|
||||||
|
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>
|
||||||
|
static constexpr bool compatible(const L& lhs, const R& rhs) {
|
||||||
|
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>
|
||||||
|
static constexpr auto shape(const L& lhs, const R& rhs) {
|
||||||
|
if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
|
||||||
|
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 {
|
||||||
|
return static_shape<cols, rows>{};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename E>
|
||||||
|
constexpr auto operator()(std::size_t index, const E& expr) const {
|
||||||
|
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<::tulip::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 (!::tulip::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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace ops
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_OPS_HPP
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#ifndef TULIP_SIMD_AVX_HPP
|
||||||
|
#define TULIP_SIMD_AVX_HPP
|
||||||
|
|
||||||
|
#include "./traits.hpp"
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace simd {
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
#ifdef TULIP_AVX_SUPPORTED
|
||||||
|
template <>
|
||||||
|
struct traits<float, avx_isa> {
|
||||||
|
using pack_type = __m128;
|
||||||
|
|
||||||
|
static constexpr std::size_t width = 4;
|
||||||
|
|
||||||
|
static pack_type load(const float* ptr) noexcept { return _mm_loadu_ps(ptr); }
|
||||||
|
static void store(float* ptr, pack_type value) noexcept { _mm_storeu_ps(ptr, value); }
|
||||||
|
|
||||||
|
static pack_type broadcast(float value) noexcept { return _mm_set1_ps(value); }
|
||||||
|
|
||||||
|
static pack_type add(pack_type lhs, pack_type rhs) noexcept { return _mm_add_ps(lhs, rhs); }
|
||||||
|
static pack_type sub(pack_type lhs, pack_type rhs) noexcept { return _mm_sub_ps(lhs, rhs); }
|
||||||
|
static pack_type mul(pack_type lhs, pack_type rhs) noexcept { return _mm_mul_ps(lhs, rhs); }
|
||||||
|
static pack_type div(pack_type lhs, pack_type rhs) noexcept { return _mm_div_ps(lhs, rhs); }
|
||||||
|
};
|
||||||
|
#endif // TULIP_AVX_SUPPORTED
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace simd
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_AVX_HPP
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#ifndef TULIP_SIMD_AVX2_HPP
|
||||||
|
#define TULIP_SIMD_AVX2_HPP
|
||||||
|
|
||||||
|
#include "./traits.hpp"
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace simd {
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
#ifdef TULIP_AVX2_SUPPORTED
|
||||||
|
template <>
|
||||||
|
struct traits<float, avx2_isa> {
|
||||||
|
using pack_type = __m256;
|
||||||
|
|
||||||
|
static constexpr std::size_t width = 8;
|
||||||
|
|
||||||
|
static pack_type load(const float* ptr) noexcept { return _mm256_loadu_ps(ptr); }
|
||||||
|
static void store(float* ptr, pack_type value) noexcept { _mm256_storeu_ps(ptr, value); }
|
||||||
|
|
||||||
|
static pack_type broadcast(float value) noexcept { return _mm256_set1_ps(value); }
|
||||||
|
|
||||||
|
static pack_type add(pack_type lhs, pack_type rhs) noexcept { return _mm256_add_ps(lhs, rhs); }
|
||||||
|
static pack_type sub(pack_type lhs, pack_type rhs) noexcept { return _mm256_sub_ps(lhs, rhs); }
|
||||||
|
static pack_type mul(pack_type lhs, pack_type rhs) noexcept { return _mm256_mul_ps(lhs, rhs); }
|
||||||
|
static pack_type div(pack_type lhs, pack_type rhs) noexcept { return _mm256_div_ps(lhs, rhs); }
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct traits<double, avx2_isa> {
|
||||||
|
using pack_type = __m256d;
|
||||||
|
|
||||||
|
static constexpr std::size_t width = 4;
|
||||||
|
|
||||||
|
static pack_type load(const double* ptr) noexcept { return _mm256_loadu_pd(ptr); }
|
||||||
|
static void store(double* ptr, pack_type value) noexcept { _mm256_storeu_pd(ptr, value); }
|
||||||
|
|
||||||
|
static pack_type broadcast(float value) noexcept { return _mm256_set1_pd(value); }
|
||||||
|
|
||||||
|
static pack_type add(pack_type lhs, pack_type rhs) noexcept { return _mm256_add_pd(lhs, rhs); }
|
||||||
|
static pack_type sub(pack_type lhs, pack_type rhs) noexcept { return _mm256_sub_pd(lhs, rhs); }
|
||||||
|
static pack_type mul(pack_type lhs, pack_type rhs) noexcept { return _mm256_mul_pd(lhs, rhs); }
|
||||||
|
static pack_type div(pack_type lhs, pack_type rhs) noexcept { return _mm256_div_pd(lhs, rhs); }
|
||||||
|
};
|
||||||
|
#endif // TULIP_AVX2_SUPPORTED
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace simd
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_AVX2_HPP
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#ifndef TULIP_SIMD_CONFIG_HPP
|
||||||
|
#define TULIP_SIMD_CONFIG_HPP
|
||||||
|
|
||||||
|
#if !defined(TULIP_DISABLE_SIMD) && (defined(__AVX__) || defined(__AVX2__))
|
||||||
|
#include <immintrin.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace simd {
|
||||||
|
|
||||||
|
struct scalar_isa {};
|
||||||
|
struct avx_isa {};
|
||||||
|
struct avx2_isa {};
|
||||||
|
|
||||||
|
#if defined(__AVX__) && !defined(TULIP_DISABLE_SIMD)
|
||||||
|
#define TULIP_AVX_SUPPORTED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(__AVX2__) && !defined(TULIP_DISABLE_SIMD)
|
||||||
|
#define TULIP_AVX2_SUPPORTED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
} // namespace simd
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_CONFIG_HPP
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#ifndef TULIP_SIMD_DISPATCH_HPP
|
||||||
|
#define TULIP_SIMD_DISPATCH_HPP
|
||||||
|
|
||||||
|
#include "./config.hpp"
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace simd {
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct preferred_isa {
|
||||||
|
using type = simd::scalar_isa;
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifdef TULIP_AVX2_SUPPORT
|
||||||
|
template <>
|
||||||
|
struct preferrpreferred_isa<float> {
|
||||||
|
using type = simd::avx2_isa;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct preferrpreferred_isa<double> {
|
||||||
|
using type = simd::avx2_isa;
|
||||||
|
};
|
||||||
|
#elif defined(TULIP_AVX_SUPPORT)
|
||||||
|
template <>
|
||||||
|
struct preferrpreferred_isa<float> {
|
||||||
|
using type = simd::avx_isa;
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using preferred_isa_t = typename preferred_isa<T>::type;
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace simd
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_DISPATCH_HPP
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#ifndef TULIP_SIMD_HPP
|
||||||
|
#define TULIP_SIMD_HPP
|
||||||
|
|
||||||
|
#include "./avx.hpp" // IWYU pragma: export
|
||||||
|
#include "./avx2.hpp" // IWYU pragma: export
|
||||||
|
#include "./config.hpp" // IWYU pragma: export
|
||||||
|
#include "./dispatch.hpp" // IWYU pragma: export
|
||||||
|
#include "./traits.hpp" // IWYU pragma: export
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_HPP
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#ifndef TULIP_SIMD_TRAITS_HPP
|
||||||
|
#define TULIP_SIMD_TRAITS_HPP
|
||||||
|
|
||||||
|
#include "./config.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
namespace simd {
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
struct traits {};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct traits<T, scalar_isa> {
|
||||||
|
using pack_type = T;
|
||||||
|
|
||||||
|
static constexpr std::size_t width = 1;
|
||||||
|
|
||||||
|
static pack_type load(const T* ptr) noexcept { return *ptr; }
|
||||||
|
static void store(T* ptr, pack_type value) noexcept { *ptr = value; }
|
||||||
|
|
||||||
|
static pack_type broadcast(T value) noexcept { return value; }
|
||||||
|
|
||||||
|
static pack_type add(pack_type lhs, pack_type rhs) noexcept { return lhs + rhs; }
|
||||||
|
static pack_type sub(pack_type lhs, pack_type rhs) noexcept { return lhs - rhs; }
|
||||||
|
static pack_type mul(pack_type lhs, pack_type rhs) noexcept { return lhs * rhs; }
|
||||||
|
static pack_type div(pack_type lhs, pack_type rhs) noexcept { return lhs / rhs; }
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
using pack_t = typename traits<T, Isa>::pack_type;
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
inline constexpr auto width_v = traits<T, Isa>::width;
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto load(const T* ptr) noexcept {
|
||||||
|
return traits<T, Isa>::load(ptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static void store(T* ptr, pack_t<T, Isa> value) noexcept {
|
||||||
|
traits<T, Isa>::store(ptr, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto broadcast(T value) noexcept {
|
||||||
|
return traits<T, Isa>::broadcast(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto add(pack_t<T, Isa> lhs, pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return traits<T, Isa>::add(lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto sub(pack_t<T, Isa> lhs, pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return traits<T, Isa>::sub(lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto mul(pack_t<T, Isa> lhs, pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return traits<T, Isa>::mul(lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Isa>
|
||||||
|
static auto div(pack_t<T, Isa> lhs, pack_t<T, Isa> rhs) noexcept {
|
||||||
|
return traits<T, Isa>::div(lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
} // namespace simd
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_SIMD_TRAITS_HPP
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
#ifndef TULIP_TENSOR_HPP
|
||||||
|
#define TULIP_TENSOR_HPP
|
||||||
|
|
||||||
|
#include "./expr.hpp"
|
||||||
|
#include "./tensor_fwd.hpp"
|
||||||
|
#include "./tensor_shape.hpp"
|
||||||
|
#include "./tensor_traits.hpp"
|
||||||
|
#include "./tensor_view.hpp"
|
||||||
|
#include "tulip/evaluate.hpp"
|
||||||
|
#include "tulip/simd/traits.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstring>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
|
||||||
|
template <typename T, std::size_t... Dims>
|
||||||
|
class tensor : public expression_tag, public ops_provider<tensor<T, Dims...>> {
|
||||||
|
public:
|
||||||
|
using traits = tensor_traits<tensor>;
|
||||||
|
using value_type = typename traits::value_type;
|
||||||
|
using constant_value_type = const value_type;
|
||||||
|
using view_type = tensor_view<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...>>;
|
||||||
|
public:
|
||||||
|
template <typename ST>
|
||||||
|
using with_storage = typename traits::template with_storage_t<ST>;
|
||||||
|
public:
|
||||||
|
tensor() {
|
||||||
|
if constexpr (traits::dynamic) {
|
||||||
|
m_items = nullptr;
|
||||||
|
m_shape = {};
|
||||||
|
} else if constexpr (traits::inline_storage) {
|
||||||
|
view().fill();
|
||||||
|
} else {
|
||||||
|
m_items = new value_type[traits::size];
|
||||||
|
view().fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... RtDims,
|
||||||
|
typename = std::enable_if_t<(
|
||||||
|
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
|
||||||
|
explicit tensor(RtDims... dimensions) {
|
||||||
|
set_dimensions(dimensions...);
|
||||||
|
}
|
||||||
|
|
||||||
|
~tensor() { release(); }
|
||||||
|
|
||||||
|
tensor(tensor&& other) noexcept
|
||||||
|
: m_shape(std::move(other.m_shape)) {
|
||||||
|
if constexpr (!traits::inline_storage) {
|
||||||
|
m_items = other.m_items;
|
||||||
|
other.m_items = nullptr;
|
||||||
|
} else {
|
||||||
|
std::memcpy(m_items, other.m_items, sizeof(m_items));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tensor& operator=(tensor&& other) noexcept {
|
||||||
|
if (this == &other) return *this;
|
||||||
|
release();
|
||||||
|
m_shape = std::move(other.m_shape);
|
||||||
|
if constexpr (!traits::inline_storage) {
|
||||||
|
m_items = other.m_items;
|
||||||
|
other.m_items = nullptr;
|
||||||
|
} else {
|
||||||
|
std::memcpy(m_items, other.m_items, sizeof(m_items));
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
tensor(const tensor& other)
|
||||||
|
: m_shape(other.m_shape) {
|
||||||
|
set_dimensions(other.m_shape);
|
||||||
|
dyn_copy(other.m_items);
|
||||||
|
}
|
||||||
|
|
||||||
|
tensor& operator=(const tensor& other) {
|
||||||
|
if (this == &other) return *this;
|
||||||
|
release();
|
||||||
|
set_dimensions(other.m_shape);
|
||||||
|
dyn_copy(other.m_items);
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
// TODO: improve aliasing semantics
|
||||||
|
template <typename E,
|
||||||
|
typename = std::enable_if_t<detail::is_expression_v<E> && !std::is_same_v<std::decay_t<E>, tensor>>>
|
||||||
|
tensor(E&& exprFwd) { // NOLINT
|
||||||
|
set_dimensions(exprFwd.shape());
|
||||||
|
|
||||||
|
detail::evaluate_elementwise(m_items, std::forward<E>(exprFwd), size());
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
|
||||||
|
tensor& operator=(E&& exprFwd) {
|
||||||
|
if (m_shape != exprFwd.shape()) set_dimensions(exprFwd.shape());
|
||||||
|
|
||||||
|
detail::evaluate_elementwise(m_items, std::forward<E>(exprFwd), size());
|
||||||
|
|
||||||
|
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.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.coeff(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
view_type view() & { return { m_items, m_shape }; }
|
||||||
|
constant_view_type view() const& { return { m_items, m_shape }; }
|
||||||
|
|
||||||
|
view_type view() && = delete;
|
||||||
|
constant_view_type view() const&& = delete;
|
||||||
|
|
||||||
|
explicit operator view_type() { 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:
|
||||||
|
template <typename... RtDims,
|
||||||
|
typename = std::enable_if_t<(sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
|
||||||
|
void set_dimensions(RtDims... dimensions) {
|
||||||
|
if (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
|
||||||
|
throw std::runtime_error("unexpected shape");
|
||||||
|
if constexpr (!traits::inline_storage) {
|
||||||
|
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
|
||||||
|
|
||||||
|
release();
|
||||||
|
m_items = new value_type[(dimensions * ... * 1)];
|
||||||
|
std::memset(m_items, 0, sizeof(*m_items) * (dimensions * ... * 1));
|
||||||
|
} else {
|
||||||
|
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <template <std::size_t...> class Shape, std::size_t... ShapeDims>
|
||||||
|
void set_dimensions(const Shape<ShapeDims...>& shape) {
|
||||||
|
set_dimensions_impl(shape, std::make_index_sequence<sizeof...(ShapeDims)>{});
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <template <std::size_t...> class Shape, std::size_t... ShapeDims, std::size_t... Is>
|
||||||
|
void set_dimensions_impl(const Shape<ShapeDims...>& shape, std::index_sequence<Is...>) {
|
||||||
|
set_dimensions(shape.template get<Is>()...);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
|
||||||
|
|
||||||
|
auto dimensions() const { return dimensions_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
|
||||||
|
private:
|
||||||
|
template <std::size_t... Is>
|
||||||
|
constexpr std::size_t size_impl(std::index_sequence<Is...>) const {
|
||||||
|
return (dimension<Is>() * ... * 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t... Is>
|
||||||
|
constexpr auto dimensions_impl(std::index_sequence<Is...>) const {
|
||||||
|
return std::make_tuple(dimension<Is>()...);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
value_type& coeff(std::size_t index) { return m_items[index]; }
|
||||||
|
const value_type& coeff(std::size_t index) const { return m_items[index]; }
|
||||||
|
|
||||||
|
value_type* data() { return m_items; }
|
||||||
|
const value_type* data() const { return m_items; }
|
||||||
|
|
||||||
|
const shape_type& shape() const { return m_shape; }
|
||||||
|
public:
|
||||||
|
// WARN: eval_pack does not perform bounds checks!
|
||||||
|
template <typename Isa>
|
||||||
|
auto eval_pack(std::size_t idx) noexcept {
|
||||||
|
using scalar_type = std::remove_cv_t<value_type>;
|
||||||
|
return simd::detail::load<scalar_type, Isa>(m_items + idx);
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <typename... RtDims, std::size_t... Is>
|
||||||
|
constexpr bool valid_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
|
||||||
|
return (valid_dim<decltype(dimensions), Is>(dimensions) && ...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename RtDim, std::size_t I>
|
||||||
|
constexpr bool valid_dim(RtDim dim) const {
|
||||||
|
return traits::dimensions[I] == dynamic_extent || traits::dimensions[I] == dim;
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <typename... RtDims, std::size_t... Is>
|
||||||
|
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) {
|
||||||
|
if constexpr (!detail::is_static_shape_v<shape_type>) {
|
||||||
|
((m_shape.dimensions[Is] = static_cast<std::size_t>(dimensions)), ...);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <std::size_t I>
|
||||||
|
constexpr std::size_t dimension() const {
|
||||||
|
if constexpr (traits::dynamic && traits::dimensions[I] == dynamic_extent) {
|
||||||
|
return m_shape.dimensions[I];
|
||||||
|
} else {
|
||||||
|
return traits::dimensions[I];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <std::size_t... Is>
|
||||||
|
void dyn_alloc(std::index_sequence<Is...>) {
|
||||||
|
if constexpr (!traits::inline_storage) {
|
||||||
|
m_items = new value_type[size()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void dyn_copy(const value_type* src) { std::memcpy(m_items, src, sizeof(*m_items) * size()); }
|
||||||
|
|
||||||
|
void release() {
|
||||||
|
if constexpr (!traits::inline_storage) {
|
||||||
|
delete[] m_items;
|
||||||
|
m_items = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
typename traits::storage_type m_items{};
|
||||||
|
shape_type m_shape;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_TENSOR_HPP
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
#ifndef CENET_MATH_FWD_HPP
|
#ifndef TULIP_FWD_HPP
|
||||||
#define CENET_MATH_FWD_HPP
|
#define TULIP_FWD_HPP
|
||||||
|
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
|
||||||
namespace cenet {
|
namespace tulip {
|
||||||
namespace math {
|
|
||||||
|
|
||||||
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();
|
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();
|
||||||
|
|
||||||
@@ -14,6 +13,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;
|
||||||
|
|
||||||
@@ -23,7 +25,6 @@ class tensor;
|
|||||||
template <typename T, std::size_t M, std::size_t N>
|
template <typename T, std::size_t M, std::size_t N>
|
||||||
using matrix = tensor<T, M, N>;
|
using matrix = tensor<T, M, N>;
|
||||||
|
|
||||||
} // namespace math
|
} // namespace tulip
|
||||||
} // namespace cenet
|
|
||||||
|
|
||||||
#endif // CENET_MATH_FWD_HPP
|
#endif // TULIP_FWD_HPP
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
#ifndef TULIP_TENSOR_SHAPE_HPP
|
||||||
|
#define TULIP_TENSOR_SHAPE_HPP
|
||||||
|
|
||||||
|
#include "./tensor_fwd.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
struct shape {};
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
struct static_shape;
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
struct dynamic_shape;
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
struct static_shape : shape<Dims...> {
|
||||||
|
static_shape() = default;
|
||||||
|
|
||||||
|
template <std::size_t... ExtDims, typename = std::enable_if_t<(sizeof...(ExtDims) >= sizeof...(Dims))>>
|
||||||
|
explicit static_shape(const static_shape<ExtDims...>& oth) {}
|
||||||
|
|
||||||
|
template <std::size_t... OthDims>
|
||||||
|
static constexpr bool compatible() {
|
||||||
|
return ((Dims == OthDims) && ...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static constexpr bool compatible() {
|
||||||
|
return compatible_impl<T>::value;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t I>
|
||||||
|
constexpr auto get() const {
|
||||||
|
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:
|
||||||
|
template <typename T>
|
||||||
|
struct compatible_impl : std::false_type {};
|
||||||
|
|
||||||
|
template <typename T, std::size_t... OthDims>
|
||||||
|
struct compatible_impl<tensor<T, OthDims...>>
|
||||||
|
: std::conditional_t<((Dims == OthDims) && ...), std::true_type, std::false_type> {};
|
||||||
|
|
||||||
|
template <std::size_t I, std::size_t First, std::size_t... Rest>
|
||||||
|
struct get_impl : get_impl<I - 1, Rest...> {};
|
||||||
|
|
||||||
|
template <std::size_t First, std::size_t... Rest>
|
||||||
|
struct get_impl<0, First, Rest...> {
|
||||||
|
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>
|
||||||
|
struct dynamic_shape : shape<Dims...> {
|
||||||
|
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))>>
|
||||||
|
explicit dynamic_shape(const dynamic_shape<ExtRank>& oth) {
|
||||||
|
constexpr std::size_t ext_offset = ExtRank - sizeof...(Dims);
|
||||||
|
for (std::size_t i = 0; i < sizeof...(Dims); ++i) {
|
||||||
|
dimensions[i] = oth.dimensions[ext_offset + i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t... OthDims>
|
||||||
|
static constexpr bool compatible() {
|
||||||
|
return ((Dims == dynamic_extent || Dims == OthDims) && ...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static constexpr bool compatible() {
|
||||||
|
return compatible_impl<T>::value;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t I>
|
||||||
|
constexpr auto get() const {
|
||||||
|
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)]{};
|
||||||
|
private:
|
||||||
|
template <typename T>
|
||||||
|
struct compatible_impl : std::false_type {};
|
||||||
|
|
||||||
|
template <typename T, std::size_t... OthDims>
|
||||||
|
struct compatible_impl<tensor<T, OthDims...>>
|
||||||
|
: std::conditional_t<((Dims == dynamic_extent || Dims == OthDims) && ...), std::true_type, std::false_type> {};
|
||||||
|
|
||||||
|
template <template <std::size_t...> class R, std::size_t... RDims, std::size_t... Is>
|
||||||
|
constexpr bool compare_impl(std::index_sequence<Is...>, const R<RDims...>& rhs) const {
|
||||||
|
return ((get<Is>() == rhs.template get<Is>()) && ...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t I, std::size_t First, std::size_t... Rest>
|
||||||
|
struct get_impl : get_impl<I - 1, Rest...> {};
|
||||||
|
|
||||||
|
template <std::size_t First, std::size_t... Rest>
|
||||||
|
struct get_impl<0, First, Rest...> {
|
||||||
|
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...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t I, typename RDim>
|
||||||
|
void store_impl(RDim last) {
|
||||||
|
dimensions[I] = last;
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct is_static_shape : std::false_type {};
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
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>
|
||||||
|
inline constexpr auto is_static_shape_v = is_static_shape<T>::value;
|
||||||
|
|
||||||
|
template <template <std::size_t...> class L,
|
||||||
|
std::size_t... LDims,
|
||||||
|
template <std::size_t...> class R,
|
||||||
|
std::size_t... RDims,
|
||||||
|
std::size_t... Is>
|
||||||
|
static constexpr bool shape_compare_impl(std::index_sequence<Is...>, const L<LDims...>& lhs, const R<RDims...>& rhs) {
|
||||||
|
return ((lhs.template get<Is>() == rhs.template get<Is>()) && ...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename L, typename R>
|
||||||
|
struct is_shape_equivalent : std::false_type {};
|
||||||
|
|
||||||
|
template <template <std::size_t...> class L,
|
||||||
|
std::size_t LFirst,
|
||||||
|
std::size_t... LRest,
|
||||||
|
template <std::size_t...> class R,
|
||||||
|
std::size_t RFirst,
|
||||||
|
std::size_t... RRest>
|
||||||
|
struct is_shape_equivalent<L<LFirst, LRest...>, R<RFirst, RRest...>>
|
||||||
|
: std::conditional_t<(LFirst == RFirst || LFirst == dynamic_extent || RFirst == dynamic_extent),
|
||||||
|
is_shape_equivalent<L<LRest...>, R<RRest...>>,
|
||||||
|
std::false_type> {};
|
||||||
|
|
||||||
|
template <template <std::size_t...> class L, template <std::size_t...> class R>
|
||||||
|
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
|
||||||
|
|
||||||
|
template <std::size_t... Dims>
|
||||||
|
using shape_of = typename detail::shape_of_impl<Dims...>::type;
|
||||||
|
|
||||||
|
template <template <std::size_t...> class L,
|
||||||
|
std::size_t... LDims,
|
||||||
|
template <std::size_t...> class R,
|
||||||
|
std::size_t... RDims>
|
||||||
|
bool operator==(const L<LDims...>& lhs, const R<RDims...>& rhs) {
|
||||||
|
return sizeof...(LDims) == sizeof...(RDims) &&
|
||||||
|
detail::shape_compare_impl(std::make_index_sequence<sizeof...(LDims)>{}, lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <template <std::size_t...> class L,
|
||||||
|
std::size_t... LDims,
|
||||||
|
template <std::size_t...> class R,
|
||||||
|
std::size_t... RDims>
|
||||||
|
bool operator!=(const L<LDims...>& lhs, const R<RDims...>& rhs) {
|
||||||
|
return sizeof...(LDims) != sizeof...(RDims) ||
|
||||||
|
!detail::shape_compare_impl(std::make_index_sequence<sizeof...(LDims)>{}, lhs, rhs);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_TENSOR_SHAPE_HPP
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
#ifndef CENET_MATH_TENSOR_TRAITS_HPP
|
#ifndef TULIP_TENSOR_TRAITS_HPP
|
||||||
#define CENET_MATH_TENSOR_TRAITS_HPP
|
#define TULIP_TENSOR_TRAITS_HPP
|
||||||
|
|
||||||
#include "tensor_fwd.hpp"
|
#include "./tensor_fwd.hpp"
|
||||||
|
#include "./tensor_shape.hpp"
|
||||||
|
#include "./type_traits.hpp"
|
||||||
|
|
||||||
#include <type_traits>
|
#include <type_traits>
|
||||||
|
|
||||||
namespace cenet {
|
namespace tulip {
|
||||||
namespace math {
|
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
struct tensor_storage {};
|
struct tensor_storage {};
|
||||||
@@ -36,6 +37,19 @@ struct is_storage_inline<inline_storage<T>> : std::true_type {};
|
|||||||
template <typename T>
|
template <typename T>
|
||||||
static constexpr auto is_storage_inline_v = is_storage_inline<T>::value;
|
static constexpr auto is_storage_inline_v = is_storage_inline<T>::value;
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct detach_storage {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct detach_storage<inline_storage<T>> {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using detach_storage_t = typename detach_storage<T>::type;
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
struct is_tensor : std::false_type {};
|
struct is_tensor : std::false_type {};
|
||||||
|
|
||||||
@@ -60,14 +74,46 @@ 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...>;
|
||||||
|
};
|
||||||
|
|
||||||
|
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>
|
template <typename T>
|
||||||
struct tensor_traits {};
|
struct tensor_traits {};
|
||||||
|
|
||||||
template <typename T, std::size_t... Dims>
|
template <typename T, std::size_t... Dims>
|
||||||
struct tensor_traits<tensor<T, Dims...>> {
|
struct tensor_traits<tensor<T, Dims...>> {
|
||||||
using tensor_type = tensor<T, Dims...>;
|
using tensor_type = tensor<T, Dims...>;
|
||||||
using value_type = tensor_storage<tensor_type>::value_type;
|
using value_type = typename tensor_storage<tensor_type>::value_type;
|
||||||
using storage_type = tensor_storage<tensor_type>::storage_type;
|
using storage_type = typename tensor_storage<tensor_type>::storage_type;
|
||||||
|
|
||||||
static constexpr auto rank = sizeof...(Dims);
|
static constexpr auto rank = sizeof...(Dims);
|
||||||
static constexpr auto dynamic = is_tensor_dynamic_v<tensor_type>;
|
static constexpr auto dynamic = is_tensor_dynamic_v<tensor_type>;
|
||||||
@@ -78,9 +124,20 @@ 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
|
template <typename T, typename Shape>
|
||||||
} // namespace cenet
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
#endif // CENET_MATH_TENSOR_TRAITS_HPP
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_TENSOR_TRAITS_HPP
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
#ifndef TULIP_TENSOR_VIEW_HPP
|
||||||
|
#define TULIP_TENSOR_VIEW_HPP
|
||||||
|
|
||||||
|
#include "./expr.hpp"
|
||||||
|
#include "./tensor_fwd.hpp"
|
||||||
|
#include "./tensor_shape.hpp"
|
||||||
|
#include "./tensor_traits.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstring>
|
||||||
|
#include <random>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
|
||||||
|
template <typename T, std::size_t... Dims>
|
||||||
|
class tensor_view : public expression_tag, public ops_provider<tensor_view<T, Dims...>> {
|
||||||
|
static_assert(std::is_arithmetic_v<T>);
|
||||||
|
|
||||||
|
template <typename, std::size_t...>
|
||||||
|
friend class tensor;
|
||||||
|
|
||||||
|
template <typename, std::size_t...>
|
||||||
|
friend class tensor_view;
|
||||||
|
public:
|
||||||
|
using traits = tensor_traits<tensor<T, Dims...>>;
|
||||||
|
using shape_type = std::conditional_t<traits::dynamic, dynamic_shape<Dims...>, static_shape<Dims...>>;
|
||||||
|
using value_type = T;
|
||||||
|
public:
|
||||||
|
template <typename... Offs,
|
||||||
|
typename = std::enable_if_t<(
|
||||||
|
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
|
||||||
|
decltype(auto) slice(Offs... offs) {
|
||||||
|
auto* ptr = m_view + m_shape.calculate_offset(std::make_tuple(offs...));
|
||||||
|
if constexpr (sizeof...(Offs) == sizeof...(Dims))
|
||||||
|
return *ptr;
|
||||||
|
else
|
||||||
|
return inner_view<T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Offs,
|
||||||
|
typename = std::enable_if_t<(
|
||||||
|
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
|
||||||
|
decltype(auto) slice(Offs... offs) const {
|
||||||
|
const auto* ptr = m_view + m_shape.calculate_offset(std::make_tuple(offs...));
|
||||||
|
if constexpr (sizeof...(Offs) == sizeof...(Dims))
|
||||||
|
return *ptr;
|
||||||
|
else
|
||||||
|
return inner_view<const T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
|
||||||
|
decltype(auto) operator[](Off off) {
|
||||||
|
return slice(off);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
|
||||||
|
decltype(auto) operator[](Off off) const {
|
||||||
|
return slice(off);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
|
||||||
|
|
||||||
|
auto dimensions() const { return dimensions_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
|
||||||
|
private:
|
||||||
|
template <std::size_t... Is>
|
||||||
|
constexpr std::size_t size_impl(std::index_sequence<Is...>) const {
|
||||||
|
return (dimension<Is>() * ... * 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <std::size_t... Is>
|
||||||
|
constexpr auto dimensions_impl(std::index_sequence<Is...>) const {
|
||||||
|
return std::make_tuple(dimension<Is>()...);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
void fill(value_type fill = {}) {
|
||||||
|
for (std::size_t i = 0; i < size(); ++i) {
|
||||||
|
m_view[i] = fill;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
|
||||||
|
offset = std::min(offset, size());
|
||||||
|
std::memmove(m_view + offset, source, std::min(length, size() - offset) * sizeof(*m_view));
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill(const tensor_view& view) { fill(view.m_view, 0, view.size()); }
|
||||||
|
|
||||||
|
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:
|
||||||
|
value_type& coeff(std::size_t index) { return m_view[index]; }
|
||||||
|
const value_type& coeff(std::size_t index) const { return m_view[index]; }
|
||||||
|
|
||||||
|
value_type* data() { return m_view; }
|
||||||
|
const value_type* data() const { return m_view; }
|
||||||
|
|
||||||
|
const shape_type& shape() const { return m_shape; }
|
||||||
|
public:
|
||||||
|
// WARN: eval_pack does not perform bounds checks!
|
||||||
|
template <typename Isa>
|
||||||
|
auto eval_pack(std::size_t idx) noexcept {
|
||||||
|
using scalar_type = std::remove_cv_t<value_type>;
|
||||||
|
return simd::detail::load<scalar_type, Isa>(m_view + idx);
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <typename InT, std::size_t Off, std::size_t First, std::size_t... Rest>
|
||||||
|
auto inner_view(value_type* view, std::index_sequence<First, Rest...>) {
|
||||||
|
if constexpr (Off == 0)
|
||||||
|
return tensor_view<InT, First, Rest...>{ view, m_shape };
|
||||||
|
else
|
||||||
|
return inner_view<InT, Off - 1>(view, std::index_sequence<Rest...>{});
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <std::size_t I>
|
||||||
|
constexpr std::size_t dimension() const {
|
||||||
|
if constexpr (traits::dynamic && traits::dimensions[I] == dynamic_extent) {
|
||||||
|
return m_shape.dimensions[I];
|
||||||
|
} else {
|
||||||
|
return traits::dimensions[I];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
template <typename Fwd>
|
||||||
|
tensor_view(value_type* view, Fwd&& shape)
|
||||||
|
: m_view(view), m_shape(std::forward<Fwd>(shape)) {}
|
||||||
|
private:
|
||||||
|
value_type* m_view;
|
||||||
|
|
||||||
|
shape_type m_shape;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_TENSOR_VIEW_HPP
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#ifndef TULIP_TYPE_TRAITS_HPP
|
||||||
|
#define TULIP_TYPE_TRAITS_HPP
|
||||||
|
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace tulip {
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
|
||||||
|
|
||||||
|
} // namespace tulip
|
||||||
|
|
||||||
|
#endif // TULIP_TYPE_TRAITS_HPP
|
||||||
Binary file not shown.
+170
@@ -0,0 +1,170 @@
|
|||||||
|
// TODO: write actual tests
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <tulip/expr.hpp>
|
||||||
|
#include <tulip/tensor.hpp>
|
||||||
|
#include <tulip/tensor_fwd.hpp>
|
||||||
|
|
||||||
|
using tulip::dynamic_extent;
|
||||||
|
|
||||||
|
// Whatever
|
||||||
|
TEST(Tensor, View) {
|
||||||
|
tulip::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 };
|
||||||
|
tulip::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 };
|
||||||
|
tulip::tensor<tulip::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 };
|
||||||
|
tulip::tensor<tulip::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 };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::inline_storage<float>, 2, 2> lhs;
|
||||||
|
tulip::tensor<tulip::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) };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::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 };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::inline_storage<float>, 3, 2> lhs;
|
||||||
|
tulip::tensor<tulip::inline_storage<float>, 2, 1> rhs;
|
||||||
|
|
||||||
|
lhs.view().fill(lhsArray);
|
||||||
|
rhs.view().fill(rhsArray);
|
||||||
|
|
||||||
|
constexpr float expArray[3 * 1] = { 11, 39, 53 };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::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 };
|
||||||
|
tulip::tensor<tulip::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 };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::inline_storage<float>, 2, 2> lhs;
|
||||||
|
tulip::tensor<tulip::inline_storage<float>, 2, 2> rhs;
|
||||||
|
|
||||||
|
lhs.view().fill(lhsArray);
|
||||||
|
rhs.view().fill(rhsArray);
|
||||||
|
|
||||||
|
constexpr float expArray[2 * 2] = { 4, 3, 3, 4 };
|
||||||
|
|
||||||
|
tulip::tensor<tulip::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) {
|
||||||
|
tulip::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 = tulip::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);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Tensor, ElementwiseSimd) {
|
||||||
|
constexpr std::size_t count = 13;
|
||||||
|
|
||||||
|
tulip::tensor<float, count> lhs;
|
||||||
|
tulip::tensor<float, count> rhs;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < count; ++i) {
|
||||||
|
lhs.coeff(i) = static_cast<float>(i + 1);
|
||||||
|
rhs.coeff(i) = static_cast<float>(i + 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
tulip::tensor<float, count> add = lhs + rhs;
|
||||||
|
tulip::tensor<float, count> sub = lhs - rhs;
|
||||||
|
tulip::tensor<float, count> mul = lhs * rhs;
|
||||||
|
tulip::tensor<float, count> div = lhs / rhs;
|
||||||
|
|
||||||
|
// Tensor-scalar
|
||||||
|
tulip::tensor<float, count> ts = lhs * 2.0F;
|
||||||
|
|
||||||
|
// Scalar-tensor
|
||||||
|
tulip::tensor<float, count> st = 100.0F - lhs;
|
||||||
|
tulip::tensor<float, count> sd = 120.0F / lhs;
|
||||||
|
|
||||||
|
// Nested expression
|
||||||
|
tulip::tensor<float, count> nested = (lhs + rhs) * 2.0F;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < count; ++i) {
|
||||||
|
const float a = lhs.coeff(i);
|
||||||
|
const float b = rhs.coeff(i);
|
||||||
|
|
||||||
|
EXPECT_FLOAT_EQ(add.coeff(i), a + b);
|
||||||
|
EXPECT_FLOAT_EQ(sub.coeff(i), a - b);
|
||||||
|
EXPECT_FLOAT_EQ(mul.coeff(i), a * b);
|
||||||
|
EXPECT_FLOAT_EQ(div.coeff(i), a / b);
|
||||||
|
|
||||||
|
EXPECT_FLOAT_EQ(ts.coeff(i), a * 2.0F);
|
||||||
|
|
||||||
|
EXPECT_FLOAT_EQ(st.coeff(i), 100.0F - a);
|
||||||
|
EXPECT_FLOAT_EQ(sd.coeff(i), 120.0F / a);
|
||||||
|
|
||||||
|
EXPECT_FLOAT_EQ(nested.coeff(i), (a + b) * 2.0F);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user