Compare commits
7
Commits
e19b6b499d
...
math
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8b00b32d2
|
||
|
|
f98615fea4
|
||
|
|
3a27df500e
|
||
|
|
dea973ddd6
|
||
|
|
14292b1d97
|
||
|
|
2f24260cbf
|
||
|
|
a9ba1874f1
|
+43
-24
@@ -2,37 +2,56 @@ cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
project(cenet CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
option(CENET_BUILD_TESTS "Compile cenet tests" OFF)
|
||||
option(CENET_BUILD_EXAMPLES "Compile cenet examples" ON)
|
||||
|
||||
file(GLOB_RECURSE CENET_HEADERS "include/*.hpp")
|
||||
option(TULIP_DISABLE_SIMD "Disable SIMD backend for tulip" OFF)
|
||||
|
||||
file(GLOB_RECURSE TULIP_HEADERS CONFIGURE_DEPENDS "include/tulip/*.hpp")
|
||||
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)
|
||||
|
||||
if(TULIP_DISABLE_SIMD)
|
||||
target_compile_definitions(tulip INTERFACE TULIP_DISABLE_SIMD)
|
||||
endif()
|
||||
|
||||
file(GLOB_RECURSE CENET_HEADERS CONFIGURE_DEPENDS "include/cenet/*.hpp")
|
||||
add_library(cenet INTERFACE ${CENET_HEADERS})
|
||||
target_include_directories(cenet INTERFACE include/)
|
||||
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)
|
||||
|
||||
add_executable(xor example/xor.cpp)
|
||||
target_link_libraries(xor PRIVATE 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(mnist example/mnist.cpp)
|
||||
target_link_libraries(mnist PRIVATE cenet)
|
||||
|
||||
add_executable(tokenizer example/tokenizer.cpp)
|
||||
target_link_libraries(tokenizer 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)
|
||||
add_executable(gpt example/gpt.cpp)
|
||||
target_link_libraries(gpt PRIVATE cenet)
|
||||
endif()
|
||||
|
||||
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)
|
||||
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()
|
||||
enable_testing()
|
||||
|
||||
add_executable(math_test test/tensor.cpp)
|
||||
target_link_libraries(math_test GTest::gtest_main cenet)
|
||||
add_executable(math_test test/tensor.cpp)
|
||||
target_link_libraries(math_test GTest::gtest_main cenet)
|
||||
|
||||
include(GoogleTest)
|
||||
gtest_discover_tests(math_test)
|
||||
include(GoogleTest)
|
||||
gtest_discover_tests(math_test)
|
||||
endif()
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
#include "cenet/layers/token.hpp"
|
||||
#include "cenet/network.hpp"
|
||||
#include "tokenizer.hpp"
|
||||
|
||||
@@ -7,7 +8,7 @@
|
||||
|
||||
static constexpr std::size_t VOCAB_SIZE = 2256;
|
||||
|
||||
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::tok2vec_layer<2256, 512>>;
|
||||
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::layers::tok2vec<2256, 512>>;
|
||||
|
||||
int main(void) {
|
||||
tokenizer<VOCAB_SIZE> bpe;
|
||||
|
||||
+5
-5
@@ -15,7 +15,7 @@
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
using network_type = cenet::network<cenet::math::tensor<float, 1, 28, 28>,
|
||||
using network_type = cenet::network<tulip::tensor<float, 1, 28, 28>,
|
||||
cenet::layers::conv2d<8, 3, 1, 1>,
|
||||
cenet::layers::relu,
|
||||
cenet::layers::maxpool<>,
|
||||
@@ -29,14 +29,14 @@ using network_type = cenet::network<cenet::math::tensor<float, 1, 28, 28>,
|
||||
static std::uniform_real_distribution<> dist(-1, 1);
|
||||
|
||||
struct data {
|
||||
cenet::math::tensor<float, 1, 28, 28> xs{};
|
||||
cenet::math::matrix<float, 1, 10> ys{};
|
||||
tulip::tensor<float, 1, 28, 28> xs{};
|
||||
tulip::matrix<float, 1, 10> ys{};
|
||||
};
|
||||
|
||||
using dataset = std::vector<data>;
|
||||
|
||||
template <std::size_t N, typename T>
|
||||
static std::size_t col_largest_idx(const cenet::math::tensor_view<T, N>& col) {
|
||||
static std::size_t col_largest_idx(const tulip::tensor_view<T, N>& col) {
|
||||
std::size_t maxIdx = 0;
|
||||
std::remove_cv_t<T> max = col[0];
|
||||
for (std::size_t i = 1; i < N; ++i) {
|
||||
@@ -135,7 +135,7 @@ int main(void) {
|
||||
|
||||
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) {
|
||||
shuffle_dataset(trainSet);
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
#include "cenet/layers/dense.hpp"
|
||||
#include "cenet/loss/mse.hpp"
|
||||
#include "cenet/math/tensor_fwd.hpp"
|
||||
#include "tulip/tensor_fwd.hpp"
|
||||
|
||||
#include <cenet/cenet.hpp>
|
||||
#include <cstddef>
|
||||
@@ -11,7 +11,7 @@
|
||||
static std::uniform_real_distribution<> dist(-1, 1);
|
||||
|
||||
int main(void) {
|
||||
static cenet::math::matrix<cenet::math::inline_storage<float>, 1, 1> s_trainData[4] = {};
|
||||
static tulip::matrix<tulip::inline_storage<float>, 1, 1> s_trainData[4] = {};
|
||||
for (std::size_t i = 0; i < 4; ++i) {
|
||||
const bool x0 = (i & 1U) != 0;
|
||||
const bool x1 = (i & 2U) != 0;
|
||||
@@ -20,7 +20,7 @@ int main(void) {
|
||||
}
|
||||
|
||||
// network net;
|
||||
using network_type = cenet::network<cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2>,
|
||||
using network_type = cenet::network<tulip::matrix<tulip::inline_storage<float>, 1, 2>,
|
||||
cenet::layers::dense<2>,
|
||||
cenet::layers::sigmoid,
|
||||
cenet::layers::dense<1>,
|
||||
@@ -45,7 +45,7 @@ int main(void) {
|
||||
learningState.reset();
|
||||
|
||||
for (std::size_t i = 0; i < 4; ++i) {
|
||||
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
|
||||
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);
|
||||
|
||||
@@ -60,7 +60,7 @@ int main(void) {
|
||||
double acc = 0.0;
|
||||
|
||||
for (std::size_t i = 0; i < 4; ++i) {
|
||||
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
|
||||
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);
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// The most useless header
|
||||
// I am keeping it for the memes
|
||||
|
||||
#ifndef CENET_HPP
|
||||
#define CENET_HPP
|
||||
|
||||
#include "layer.hpp" // IWYU pragma: export
|
||||
#include "network.hpp" // IWYU pragma: export
|
||||
|
||||
#endif // CENET_HPP
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
#ifndef CENET_LAYER_HPP
|
||||
#define CENET_LAYER_HPP
|
||||
|
||||
#include "math/tensor.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <stdexcept>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
namespace cenet {
|
||||
|
||||
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
|
||||
|
||||
struct layer_info {
|
||||
protected:
|
||||
template <class NN, std::size_t I>
|
||||
struct input_type_s {
|
||||
using type = typename std::template 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 VocabSize, std::size_t EmbedDims>
|
||||
class tok2vec_layer final : public layer_info {
|
||||
template <typename Input, typename... Layers>
|
||||
friend class network;
|
||||
private:
|
||||
template <class NN, std::size_t I>
|
||||
struct inner final {
|
||||
using input_type = typename input_type_s<NN, I>::type;
|
||||
static_assert(detail::is_tokens_v<input_type>);
|
||||
|
||||
static_assert(VocabSize > 0);
|
||||
static_assert(EmbedDims > 0);
|
||||
|
||||
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
|
||||
using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
|
||||
|
||||
input_type input;
|
||||
|
||||
embedding_type embedding;
|
||||
|
||||
struct gradient final {
|
||||
void reset() { embedding.view().fill(0); }
|
||||
|
||||
embedding_type embedding;
|
||||
embedding_type momentum;
|
||||
embedding_type variance;
|
||||
|
||||
std::size_t time = 0;
|
||||
};
|
||||
|
||||
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(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]]);
|
||||
}
|
||||
this->input = std::move(input);
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Error>
|
||||
void backward(gradient& grad, Error prevErr) {
|
||||
const auto errorShape = prevErr.shape();
|
||||
if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) {
|
||||
throw std::invalid_argument("unexpected embedding gradient shape");
|
||||
}
|
||||
|
||||
for (std::size_t i = 0; i < input.size(); ++i) {
|
||||
grad.embedding.view()[input[i]] += prevErr.view()[i];
|
||||
}
|
||||
}
|
||||
|
||||
void apply_grad(gradient& grad, double divisor, double rate) {
|
||||
if (divisor <= 0.0) return;
|
||||
|
||||
++grad.time;
|
||||
|
||||
constexpr double beta1 = 0.9;
|
||||
constexpr double beta2 = 0.999;
|
||||
constexpr double epsilon = 1e-8;
|
||||
|
||||
const double correction1 = 1.0 - std::pow(beta1, grad.time);
|
||||
const double correction2 = 1.0 - std::pow(beta2, grad.time);
|
||||
|
||||
float* weights = embedding.data();
|
||||
float* momentum = grad.momentum.data();
|
||||
float* variance = grad.variance.data();
|
||||
|
||||
for (std::size_t i = 0; i < embedding.size(); ++i) {
|
||||
const double avgGrad = static_cast<double>(grad.embedding.coeff(i)) / divisor;
|
||||
|
||||
grad.momentum.coeff(i) = static_cast<float>(beta1 * grad.momentum.coeff(i) + (1.0 - beta1) * avgGrad);
|
||||
grad.variance.coeff(i) =
|
||||
static_cast<float>(beta2 * grad.variance.coeff(i) + (1.0 - beta2) * avgGrad * avgGrad);
|
||||
|
||||
const double momentumCorrected = grad.momentum.coeff(i) / correction1;
|
||||
const double varianceCorrected = grad.variance.coeff(i) / correction2;
|
||||
|
||||
embedding.coeff(i) -=
|
||||
static_cast<float>(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon));
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace cenet
|
||||
|
||||
#endif // CENET_LAYER_HPP
|
||||
@@ -1,15 +1,16 @@
|
||||
#ifndef CENET_LAYERS_CONVOLUTIONAL_HPP
|
||||
#define CENET_LAYERS_CONVOLUTIONAL_HPP
|
||||
|
||||
#include "../math/tensor_fwd.hpp"
|
||||
#include "../math/tensor_shape.hpp"
|
||||
#include "../math/tensor_traits.hpp"
|
||||
#include "../optim/adam.hpp"
|
||||
#include "./layer_fwd.hpp"
|
||||
#include "./layer_traits.hpp"
|
||||
#include "cenet/layers/retained.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 {
|
||||
@@ -23,7 +24,7 @@ struct conv2d final : public layer_tag {
|
||||
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
static_assert(math::is_tensor_v<input_type>);
|
||||
static_assert(tulip::is_tensor_v<input_type>);
|
||||
static_assert(input_type::shape_type::rank == 3);
|
||||
|
||||
using value_type = typename input_type::value_type;
|
||||
@@ -43,11 +44,11 @@ struct conv2d final : public layer_tag {
|
||||
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
|
||||
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
|
||||
|
||||
using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||
using output_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||
|
||||
using weights_type =
|
||||
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||
using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
|
||||
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{};
|
||||
@@ -74,7 +75,7 @@ struct conv2d final : public layer_tag {
|
||||
}
|
||||
|
||||
auto feed(const input_type& input) {
|
||||
typename output_type::template with_storage<math::heap_storage_tag> output;
|
||||
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) {
|
||||
@@ -108,7 +109,7 @@ struct conv2d final : public layer_tag {
|
||||
using traits = typename detail::layer_traits<network_layer<conv2d, N, I>>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
static_assert(math::is_tensor_v<input_type>);
|
||||
static_assert(tulip::is_tensor_v<input_type>);
|
||||
static_assert(input_type::shape_type::rank == 3);
|
||||
|
||||
using value_type = typename input_type::value_type;
|
||||
@@ -129,8 +130,8 @@ struct conv2d final : public layer_tag {
|
||||
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
|
||||
|
||||
using weights_type =
|
||||
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
|
||||
using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
|
||||
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{};
|
||||
@@ -149,7 +150,7 @@ struct conv2d final : public layer_tag {
|
||||
|
||||
template <typename Error>
|
||||
auto backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
|
||||
typename input_type::template with_storage<math::heap_storage_tag> backpropErr;
|
||||
typename input_type::template with_storage<tulip::heap_storage_tag> backpropErr;
|
||||
backpropErr.view().fill();
|
||||
|
||||
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
|
||||
@@ -184,8 +185,50 @@ struct conv2d final : public layer_tag {
|
||||
|
||||
return backpropErr;
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>& data, double divisor, double rate) {
|
||||
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;
|
||||
@@ -196,7 +239,7 @@ struct conv2d final : public layer_tag {
|
||||
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 = weights[oc][ic][ky][kx] / divisor;
|
||||
double avgGrad = grad.weights[oc][ic][ky][kx] / divisor;
|
||||
|
||||
momentumWeights[oc][ic][ky][kx] =
|
||||
(beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad);
|
||||
@@ -212,7 +255,7 @@ struct conv2d final : public layer_tag {
|
||||
}
|
||||
}
|
||||
|
||||
auto avgGrad = biases[oc] / divisor;
|
||||
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);
|
||||
@@ -235,7 +278,7 @@ struct maxpool final : public layer_tag {
|
||||
using traits = typename detail::layer_traits<network_layer<maxpool, N, I>>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
static_assert(math::is_tensor_v<input_type>);
|
||||
static_assert(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");
|
||||
|
||||
@@ -249,7 +292,7 @@ struct maxpool final : public layer_tag {
|
||||
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
|
||||
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
|
||||
|
||||
using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||
using output_type = tulip::tensor<tulip::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
@@ -330,8 +373,11 @@ struct maxpool final : public layer_tag {
|
||||
|
||||
return backpropErr;
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
template <typename N, std::size_t I, class Optim>
|
||||
struct optim {
|
||||
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -343,14 +389,14 @@ struct flatten final : public layer_tag {
|
||||
using traits = typename detail::layer_traits<network_layer<flatten, N, I>>;
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
static_assert(math::is_tensor_v<input_type>);
|
||||
static_assert(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 = math::matrix<value_type, 1, FEATURES>;
|
||||
using output_type = tulip::matrix<value_type, 1, FEATURES>;
|
||||
|
||||
void dump(std::ostream& os) const {}
|
||||
|
||||
@@ -361,7 +407,7 @@ struct flatten final : public layer_tag {
|
||||
|
||||
template <typename Fwd>
|
||||
auto feed(Fwd&& fwd) {
|
||||
return std::forward<Fwd>(fwd).template reshape<math::shape_of<1, FEATURES>>();
|
||||
return std::forward<Fwd>(fwd).template reshape<tulip::shape_of<1, FEATURES>>();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -377,8 +423,11 @@ struct flatten final : public layer_tag {
|
||||
auto backward(const data<N, I>& data, R, Error&& prevErr) {
|
||||
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
template <typename N, std::size_t I, class Optim>
|
||||
struct optim {
|
||||
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -5,18 +5,18 @@
|
||||
#ifndef CENET_LAYERS_DENSE_HPP
|
||||
#define CENET_LAYERS_DENSE_HPP
|
||||
|
||||
#include "../math/tensor_fwd.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 {
|
||||
|
||||
// TODO: redesign the layer interface after porting the old layers
|
||||
template <std::size_t Features>
|
||||
struct dense final : public layer_tag {
|
||||
static constexpr auto retain = retain::Input;
|
||||
@@ -27,12 +27,12 @@ struct dense final : public layer_tag {
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
using value_type = typename input_type::value_type;
|
||||
using output_type = math::matrix<value_type, 1, Features>;
|
||||
using output_type = tulip::matrix<value_type, 1, Features>;
|
||||
|
||||
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||
|
||||
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
|
||||
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
|
||||
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;
|
||||
@@ -67,24 +67,16 @@ struct dense final : public layer_tag {
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
using value_type = typename input_type::value_type;
|
||||
using output_type = math::matrix<value_type, 1, Features>;
|
||||
using output_type = tulip::matrix<value_type, 1, Features>;
|
||||
|
||||
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||
|
||||
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
|
||||
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
|
||||
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;
|
||||
|
||||
// TODO: move Adam into optimizer state
|
||||
weights_type momentumWeights;
|
||||
biases_type momentumBiases;
|
||||
weights_type varianceWeights;
|
||||
biases_type varianceBiases;
|
||||
|
||||
std::size_t time = 0;
|
||||
|
||||
void reset() {
|
||||
weights.view().fill();
|
||||
biases.view().fill();
|
||||
@@ -97,8 +89,51 @@ struct dense final : public layer_tag {
|
||||
|
||||
return std::forward<Error>(prevErr).matmul(data.weights.transpose());
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>& data, double divisor, double rate) {
|
||||
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;
|
||||
@@ -107,7 +142,7 @@ struct dense final : public layer_tag {
|
||||
|
||||
for (std::size_t row = 0; row < input_cols; ++row) {
|
||||
for (std::size_t col = 0; col < Features; ++col) {
|
||||
auto avgGrad = weights[row][col] / divisor;
|
||||
auto avgGrad = grad.weights[row][col] / divisor;
|
||||
|
||||
momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad);
|
||||
varianceWeights[row][col] =
|
||||
@@ -121,7 +156,7 @@ struct dense final : public layer_tag {
|
||||
}
|
||||
|
||||
for (std::size_t col = 0; col < Features; ++col) {
|
||||
double avgGrad = biases[0][col] / divisor;
|
||||
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));
|
||||
@@ -172,8 +207,11 @@ struct sigmoid final : public layer_tag {
|
||||
return std::forward<Error>(prevErr) * retained *
|
||||
(static_cast<typename output_type::value_type>(1) - retained);
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
template <class N, std::size_t I, class Optim>
|
||||
struct optim {
|
||||
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -213,8 +251,11 @@ struct relu final : public layer_tag {
|
||||
return std::forward<Error>(prevErr).apply(retained,
|
||||
[](auto in, auto check) { return check > 0.0 ? in : 0.0; });
|
||||
}
|
||||
};
|
||||
|
||||
void apply(data<N, I>&, double, double) {}
|
||||
template <class N, std::size_t I, class Optim>
|
||||
struct optim {
|
||||
void apply(data<N, I>&, grad<N, I>&, double, double) {}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
#define CENET_LAYERS_LAYER_TRAITS_HPP
|
||||
|
||||
#include "../network_fwd.hpp"
|
||||
#include "../network_traits.hpp"
|
||||
#include "./layer_fwd.hpp"
|
||||
#include "cenet/network_traits.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
|
||||
@@ -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
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef CENET_MATH_TYPE_TRAITS_HPP
|
||||
#define CENET_MATH_TYPE_TRAITS_HPP
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
|
||||
template <typename T>
|
||||
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
|
||||
|
||||
}
|
||||
} // namespace cenet
|
||||
|
||||
#endif // CENET_MATH_TYPE_TRAITS_HPP
|
||||
+34
-15
@@ -1,13 +1,14 @@
|
||||
#ifndef CENET_NETWORK_HPP
|
||||
#define CENET_NETWORK_HPP
|
||||
|
||||
#include "./layers/retained.hpp"
|
||||
#include "./network_traits.hpp"
|
||||
#include "cenet/layers/retained.hpp"
|
||||
#include "cenet/math/expr.hpp"
|
||||
#include "./optim/sgd.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <tulip/expr.hpp>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
@@ -21,8 +22,6 @@ public:
|
||||
|
||||
using input_type = typename traits::input_type;
|
||||
using output_type = typename traits::output_type;
|
||||
public:
|
||||
const output_type& get_output() const { return m_output; }
|
||||
public:
|
||||
struct loss {
|
||||
double value;
|
||||
@@ -63,7 +62,6 @@ private:
|
||||
}
|
||||
}
|
||||
private:
|
||||
// TODO: pass in the optimizer
|
||||
struct layers_grad_gen {
|
||||
template <std::size_t I, typename LF, typename... LR>
|
||||
struct impl {
|
||||
@@ -78,7 +76,24 @@ private:
|
||||
|
||||
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:
|
||||
template <class Optim = optim::sgd>
|
||||
struct learning_state final {
|
||||
friend class network;
|
||||
|
||||
@@ -132,14 +147,18 @@ public:
|
||||
private:
|
||||
std::size_t m_count = 0;
|
||||
|
||||
detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct
|
||||
typename layers_grad_gen::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:
|
||||
output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); }
|
||||
template <class Optim>
|
||||
output_type feed(input_type input, learning_state<Optim>& state) {
|
||||
return feed_impl<0>(std::move(input), state);
|
||||
}
|
||||
private:
|
||||
template <std::size_t I, typename Current>
|
||||
auto feed_impl(Current&& current, learning_state& state) {
|
||||
template <std::size_t I, typename Current, class Optim>
|
||||
auto feed_impl(Current&& current, learning_state<Optim>& state) {
|
||||
if constexpr (I == sizeof...(Layers)) {
|
||||
return std::forward<Current>(current);
|
||||
} else {
|
||||
@@ -157,13 +176,14 @@ private:
|
||||
}
|
||||
}
|
||||
public:
|
||||
void apply(learning_state& state, double learningRate) {
|
||||
template <class Optim>
|
||||
void apply(learning_state<Optim>& state, double learningRate) {
|
||||
apply(state, learningRate, std::make_index_sequence<sizeof...(Layers)>{});
|
||||
}
|
||||
private:
|
||||
template <std::size_t... I>
|
||||
void apply(learning_state& state, double rate, std::index_sequence<I...>) {
|
||||
(std::get<I>(state.m_layers).apply(at<I>(), state.count(), rate), ...);
|
||||
template <std::size_t... I, class Optim>
|
||||
void apply(learning_state<Optim>& state, double rate, std::index_sequence<I...>) {
|
||||
(std::get<I>(state.m_optimizer).apply(at<I>(), std::get<I>(state.m_layers), state.count(), rate), ...);
|
||||
}
|
||||
public:
|
||||
template <std::size_t I>
|
||||
@@ -203,7 +223,6 @@ public:
|
||||
using layer = typename layers_data_gen::template at<I, I, Layers...>::type;
|
||||
private:
|
||||
typename layers_data_gen::type m_layers;
|
||||
output_type m_output;
|
||||
};
|
||||
|
||||
} // namespace cenet
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -1,16 +1,15 @@
|
||||
#ifndef CENET_MATH_EXPR_HPP
|
||||
#define CENET_MATH_EXPR_HPP
|
||||
#ifndef TULIP_EXPR_HPP
|
||||
#define TULIP_EXPR_HPP
|
||||
|
||||
#include "cenet/math/tensor_traits.hpp"
|
||||
#include "ops.hpp"
|
||||
#include "type_traits.hpp"
|
||||
#include "./ops.hpp"
|
||||
#include "./tensor_traits.hpp"
|
||||
#include "./type_traits.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
struct expression_tag {};
|
||||
struct expression_node_tag : expression_tag {};
|
||||
@@ -24,68 +23,126 @@ struct binary_expression;
|
||||
template <typename CRTP>
|
||||
struct ops_provider {
|
||||
template <typename R>
|
||||
binary_expression<CRTP, R, ops::matmul> matmul(R&& rhs) {
|
||||
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<CRTP, R, ops::matmul> matmul(R&& rhs) const {
|
||||
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) {
|
||||
unary_expression<CRTP&, ops::apply<Func>> apply(Func&& func) & {
|
||||
if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
unary_expression<CRTP, ops::apply<Func>> apply(Func&& func) const {
|
||||
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) {
|
||||
binary_expression<CRTP&, R, ops::apply<Func>> apply(R&& rhs, Func&& func) & {
|
||||
if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self(), std::forward<R>(rhs), std::forward<Func>(func) };
|
||||
}
|
||||
|
||||
template <typename R, typename Func>
|
||||
binary_expression<CRTP, R, ops::apply<Func>> apply(R&& rhs, Func&& func) const {
|
||||
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() {
|
||||
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<CRTP, ops::transpose> transpose() const {
|
||||
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() {
|
||||
unary_expression<CRTP&, ops::reshape<S>> reshape() & {
|
||||
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
|
||||
return { self() };
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
unary_expression<CRTP, ops::reshape<S>> reshape() const {
|
||||
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 reinterpret_cast<CRTP&>(*this); }
|
||||
decltype(auto) self() && { return reinterpret_cast<CRTP&&>(*this); }
|
||||
decltype(auto) self() & { return static_cast<CRTP&>(*this); }
|
||||
decltype(auto) self() && { return static_cast<CRTP&&>(*this); }
|
||||
|
||||
decltype(auto) self() const& { return reinterpret_cast<const CRTP&>(*this); }
|
||||
decltype(auto) self() const&& { return reinterpret_cast<const CRTP&&>(*this); }
|
||||
decltype(auto) self() const& { return static_cast<const CRTP&>(*this); }
|
||||
decltype(auto) self() const&& { return static_cast<const CRTP&&>(*this); }
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
@@ -101,6 +158,37 @@ struct operand_storage {
|
||||
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>
|
||||
@@ -138,6 +226,17 @@ struct binary_expression : expression_node_tag, ops_provider<binary_expression<L
|
||||
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 {
|
||||
@@ -196,7 +295,6 @@ constexpr decltype(auto) eval(T&& fwd) {
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_EXPR_HPP
|
||||
#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
|
||||
@@ -1,17 +1,17 @@
|
||||
#ifndef CENET_MATH_OPS_HPP
|
||||
#define CENET_MATH_OPS_HPP
|
||||
#ifndef TULIP_OPS_HPP
|
||||
#define TULIP_OPS_HPP
|
||||
|
||||
#include "tensor_fwd.hpp"
|
||||
#include "tensor_shape.hpp"
|
||||
#include "type_traits.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 cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
namespace ops {
|
||||
|
||||
namespace detail {
|
||||
@@ -38,7 +38,7 @@ struct generic_binary_op {
|
||||
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 = cenet::math::detail::best_shape<decltype(shape_wrapper(lhs)), decltype(shape_wrapper(rhs))>;
|
||||
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();
|
||||
@@ -68,10 +68,33 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
struct plus : generic_binary_op<std::plus<>> {};
|
||||
struct minus : generic_binary_op<std::minus<>> {};
|
||||
struct multiply : generic_binary_op<std::multiplies<>> {};
|
||||
struct divide : generic_binary_op<std::divides<>> {};
|
||||
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>
|
||||
@@ -191,12 +214,12 @@ struct transpose {
|
||||
};
|
||||
|
||||
// TODO: introduce dynamic reshape
|
||||
template <typename S, typename = std::enable_if_t<::cenet::math::detail::is_static_shape_v<S>>>
|
||||
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 (!::cenet::math::detail::is_static_shape<shape_type>::value) {
|
||||
if constexpr (!::tulip::detail::is_static_shape<shape_type>::value) {
|
||||
return false;
|
||||
} else {
|
||||
return shape_type::size == S::size;
|
||||
@@ -216,7 +239,6 @@ struct reshape {
|
||||
};
|
||||
|
||||
} // namespace ops
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_OPS_HPP
|
||||
#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
|
||||
@@ -1,11 +1,13 @@
|
||||
#ifndef CENET_MATH_TENSOR_HPP
|
||||
#define CENET_MATH_TENSOR_HPP
|
||||
#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 "./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>
|
||||
@@ -13,8 +15,7 @@
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
template <typename T, std::size_t... Dims>
|
||||
class tensor : public expression_tag, public ops_provider<tensor<T, Dims...>> {
|
||||
@@ -44,8 +45,7 @@ public:
|
||||
template <typename... RtDims,
|
||||
typename = std::enable_if_t<(
|
||||
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
|
||||
explicit tensor(RtDims... dimensions)
|
||||
: m_shape(dynamic_shape<Dims...>{}) {
|
||||
explicit tensor(RtDims... dimensions) {
|
||||
set_dimensions(dimensions...);
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ public:
|
||||
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;
|
||||
@@ -75,52 +76,33 @@ public:
|
||||
|
||||
tensor(const tensor& other)
|
||||
: m_shape(other.m_shape) {
|
||||
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
|
||||
dyn_copy(other.m_items, std::make_index_sequence<sizeof...(Dims)>{});
|
||||
set_dimensions(other.m_shape);
|
||||
dyn_copy(other.m_items);
|
||||
}
|
||||
|
||||
tensor& operator=(const tensor& other) {
|
||||
if (this == &other) return *this;
|
||||
release();
|
||||
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
|
||||
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{});
|
||||
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
|
||||
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
|
||||
set_dimensions(exprFwd.shape());
|
||||
|
||||
if constexpr (!traits::inline_storage) {
|
||||
if constexpr (traits::dynamic) {
|
||||
set_dimensions(exprFwd.shape());
|
||||
} else {
|
||||
m_items = new value_type[traits::size];
|
||||
}
|
||||
}
|
||||
|
||||
E expr = std::forward<E>(exprFwd);
|
||||
for (std::size_t i = 0; i < size(); ++i) {
|
||||
m_items[i] = expr.coeff(i);
|
||||
}
|
||||
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()) throw std::runtime_error("tensor shape mismatch");
|
||||
if (m_shape != exprFwd.shape()) set_dimensions(exprFwd.shape());
|
||||
|
||||
if constexpr (traits::dynamic) {
|
||||
if (m_shape != exprFwd.shape()) {
|
||||
set_dimensions(exprFwd.shape());
|
||||
}
|
||||
}
|
||||
|
||||
E expr = std::forward<E>(exprFwd);
|
||||
for (std::size_t i = 0; i < view().size(); ++i) {
|
||||
m_items[i] = expr.coeff(i);
|
||||
}
|
||||
detail::evaluate_elementwise(m_items, std::forward<E>(exprFwd), size());
|
||||
|
||||
return *this;
|
||||
}
|
||||
@@ -167,14 +149,17 @@ public:
|
||||
|
||||
E expr = std::forward<E>(exprFwd);
|
||||
for (std::size_t i = 0; i < view().size(); ++i) {
|
||||
m_items[i] /= expr;
|
||||
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() & { 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(); }
|
||||
@@ -190,16 +175,19 @@ public:
|
||||
}
|
||||
public:
|
||||
template <typename... RtDims,
|
||||
typename = std::enable_if_t<(
|
||||
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<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("invalid dynamic tensor dimensions");
|
||||
store_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));
|
||||
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>
|
||||
@@ -233,6 +221,13 @@ public:
|
||||
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 {
|
||||
@@ -246,7 +241,9 @@ private:
|
||||
private:
|
||||
template <typename... RtDims, std::size_t... Is>
|
||||
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) {
|
||||
((m_shape.dimensions[Is] = static_cast<std::size_t>(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>
|
||||
@@ -265,10 +262,7 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template <std::size_t... Is>
|
||||
void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
|
||||
std::memcpy(m_items, src, sizeof(*m_items) * size());
|
||||
}
|
||||
void dyn_copy(const value_type* src) { std::memcpy(m_items, src, sizeof(*m_items) * size()); }
|
||||
|
||||
void release() {
|
||||
if constexpr (!traits::inline_storage) {
|
||||
@@ -281,7 +275,6 @@ private:
|
||||
shape_type m_shape;
|
||||
};
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_TENSOR_HPP
|
||||
#endif // TULIP_TENSOR_HPP
|
||||
@@ -1,11 +1,10 @@
|
||||
#ifndef CENET_MATH_FWD_HPP
|
||||
#define CENET_MATH_FWD_HPP
|
||||
#ifndef TULIP_FWD_HPP
|
||||
#define TULIP_FWD_HPP
|
||||
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();
|
||||
|
||||
@@ -26,7 +25,6 @@ class tensor;
|
||||
template <typename T, std::size_t M, std::size_t N>
|
||||
using matrix = tensor<T, M, N>;
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_FWD_HPP
|
||||
#endif // TULIP_FWD_HPP
|
||||
@@ -1,14 +1,13 @@
|
||||
#ifndef CENET_MATH_TENSOR_SHAPE_HPP
|
||||
#define CENET_MATH_TENSOR_SHAPE_HPP
|
||||
#ifndef TULIP_TENSOR_SHAPE_HPP
|
||||
#define TULIP_TENSOR_SHAPE_HPP
|
||||
|
||||
#include "tensor_fwd.hpp"
|
||||
#include "./tensor_fwd.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
template <std::size_t... Dims>
|
||||
struct shape {};
|
||||
@@ -176,6 +175,11 @@ private:
|
||||
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;
|
||||
@@ -310,7 +314,6 @@ bool operator!=(const L<LDims...>& lhs, const R<RDims...>& rhs) {
|
||||
!detail::shape_compare_impl(std::make_index_sequence<sizeof...(LDims)>{}, lhs, rhs);
|
||||
}
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_TENSOR_SHAPE_HPP
|
||||
#endif // TULIP_TENSOR_SHAPE_HPP
|
||||
@@ -1,14 +1,13 @@
|
||||
#ifndef CENET_MATH_TENSOR_TRAITS_HPP
|
||||
#define CENET_MATH_TENSOR_TRAITS_HPP
|
||||
#ifndef TULIP_TENSOR_TRAITS_HPP
|
||||
#define TULIP_TENSOR_TRAITS_HPP
|
||||
|
||||
#include "cenet/math/tensor_shape.hpp"
|
||||
#include "cenet/math/type_traits.hpp"
|
||||
#include "tensor_fwd.hpp"
|
||||
#include "./tensor_fwd.hpp"
|
||||
#include "./tensor_shape.hpp"
|
||||
#include "./type_traits.hpp"
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
template <typename T>
|
||||
struct tensor_storage {};
|
||||
@@ -139,7 +138,6 @@ constexpr decltype(auto) tensor_from_shape(const Shape& shape) {
|
||||
return tensor;
|
||||
}
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_TENSOR_TRAITS_HPP
|
||||
#endif // TULIP_TENSOR_TRAITS_HPP
|
||||
@@ -1,10 +1,10 @@
|
||||
#ifndef CENET_MATH_TENSOR_VIEW_HPP
|
||||
#define CENET_MATH_TENSOR_VIEW_HPP
|
||||
#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 "./expr.hpp"
|
||||
#include "./tensor_fwd.hpp"
|
||||
#include "./tensor_shape.hpp"
|
||||
#include "./tensor_traits.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
@@ -12,8 +12,7 @@
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace cenet {
|
||||
namespace math {
|
||||
namespace tulip {
|
||||
|
||||
template <typename T, std::size_t... Dims>
|
||||
class tensor_view : public expression_tag, public ops_provider<tensor_view<T, Dims...>> {
|
||||
@@ -83,10 +82,10 @@ public:
|
||||
|
||||
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
|
||||
offset = std::min(offset, size());
|
||||
std::memcpy(m_view + offset, source, std::min(length, size() - offset) * sizeof(*m_view));
|
||||
std::memmove(m_view + offset, source, std::min(length, size() - offset) * sizeof(*m_view));
|
||||
}
|
||||
|
||||
void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size() * sizeof(*m_view)); }
|
||||
void fill(const tensor_view& view) { fill(view.m_view, 0, view.size()); }
|
||||
|
||||
template <typename Dist>
|
||||
void fill_random(Dist dist) {
|
||||
@@ -105,6 +104,13 @@ public:
|
||||
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...>) {
|
||||
@@ -132,7 +138,6 @@ private:
|
||||
shape_type m_shape;
|
||||
};
|
||||
|
||||
} // namespace math
|
||||
} // namespace cenet
|
||||
} // namespace tulip
|
||||
|
||||
#endif // CENET_MATH_TENSOR_VIEW_HPP
|
||||
#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.
+68
-24
@@ -1,33 +1,33 @@
|
||||
// TODO: write actual tests
|
||||
|
||||
#include <algorithm>
|
||||
#include <cenet/math/expr.hpp>
|
||||
#include <cenet/math/tensor.hpp>
|
||||
#include <cenet/math/tensor_fwd.hpp>
|
||||
#include <cstring>
|
||||
#include <gtest/gtest.h>
|
||||
#include <tulip/expr.hpp>
|
||||
#include <tulip/tensor.hpp>
|
||||
#include <tulip/tensor_fwd.hpp>
|
||||
|
||||
using cenet::math::dynamic_extent;
|
||||
using tulip::dynamic_extent;
|
||||
|
||||
// Whatever
|
||||
TEST(Tensor, View) {
|
||||
cenet::math::tensor<float, 3, 2, 2> tensor;
|
||||
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 };
|
||||
cenet::math::tensor<float, dynamic_extent, 3> lhs;
|
||||
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 };
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 3> rhs;
|
||||
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 };
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 3> result = lhs + rhs - 1;
|
||||
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) {
|
||||
@@ -39,15 +39,15 @@ TEST(Tensor, MatMul) {
|
||||
constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 };
|
||||
constexpr float rhsArray[2 * 2] = { 5, 6, 7, 8 };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> lhs;
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> rhs;
|
||||
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) };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> result = lhs.matmul(rhs);
|
||||
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]);
|
||||
}
|
||||
@@ -58,23 +58,23 @@ TEST(Tensor, MatMul2) {
|
||||
constexpr float lhsArray[3 * 2] = { 1, 2, 5, 6, 7, 8 };
|
||||
constexpr float rhsArray[2 * 1] = { 3, 4 };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 3, 2> lhs;
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 1> rhs;
|
||||
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 };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 3, 1> result = lhs.matmul(rhs);
|
||||
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 };
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> tensor;
|
||||
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 };
|
||||
@@ -89,15 +89,15 @@ TEST(Tensor, Apply2) {
|
||||
constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 };
|
||||
constexpr float rhsArray[2 * 2] = { 4, 3, 2, 1 };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> lhs;
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> rhs;
|
||||
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 };
|
||||
|
||||
cenet::math::tensor<cenet::math::inline_storage<float>, 2, 2> result =
|
||||
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]);
|
||||
@@ -105,7 +105,7 @@ TEST(Tensor, Apply2) {
|
||||
}
|
||||
|
||||
TEST(Tensor, Offsets) {
|
||||
cenet::math::tensor<float, 2, 3, 4> tensor;
|
||||
tulip::tensor<float, 2, 3, 4> tensor;
|
||||
|
||||
for (std::size_t i = 0; i < tensor.size(); ++i)
|
||||
tensor.coeff(i) = static_cast<float>(i);
|
||||
@@ -116,7 +116,7 @@ TEST(Tensor, Offsets) {
|
||||
}
|
||||
|
||||
TEST(Tensor, Offsets2) {
|
||||
using shape_type = cenet::math::static_shape<2, 3, 4>;
|
||||
using shape_type = tulip::static_shape<2, 3, 4>;
|
||||
|
||||
shape_type shape;
|
||||
|
||||
@@ -124,3 +124,47 @@ TEST(Tensor, Offsets2) {
|
||||
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