Compare commits

...
2 Commits
12 changed files with 303 additions and 109 deletions
+27 -22
View File
@@ -2,37 +2,42 @@ cmake_minimum_required(VERSION 3.14)
project(cenet CXX) project(cenet CXX)
set(CMAKE_CXX_STANDARD 17) option(CENET_BUILD_TESTS "Compile cenet tests" OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON) option(CENET_BUILD_EXAMPLES "Compile cenet examples" ON)
file(GLOB_RECURSE CENET_HEADERS "include/*.hpp") file(GLOB_RECURSE CENET_HEADERS CONFIGURE_DEPENDS "include/*.hpp")
add_library(cenet INTERFACE ${CENET_HEADERS}) add_library(cenet INTERFACE ${CENET_HEADERS})
target_include_directories(cenet INTERFACE include/) target_include_directories(cenet INTERFACE include)
target_compile_features(cenet INTERFACE cxx_std_17)
add_executable(xor example/xor.cpp) if(CENET_BUILD_EXAMPLES)
target_link_libraries(xor PRIVATE cenet) add_executable(xor example/xor.cpp)
target_link_libraries(xor PRIVATE cenet)
add_executable(mnist example/mnist.cpp) add_executable(mnist example/mnist.cpp)
target_link_libraries(mnist PRIVATE cenet) target_link_libraries(mnist PRIVATE cenet)
add_executable(tokenizer example/tokenizer.cpp) add_executable(tokenizer example/tokenizer.cpp)
target_link_libraries(tokenizer PRIVATE cenet) target_link_libraries(tokenizer PRIVATE cenet)
add_executable(gpt example/gpt.cpp) add_executable(gpt example/gpt.cpp)
target_link_libraries(gpt PRIVATE cenet) target_link_libraries(gpt PRIVATE cenet)
endif()
include(FetchContent) if(CENET_BUILD_TESTS)
FetchContent_Declare( include(FetchContent)
FetchContent_Declare(
googletest googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
) )
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest) FetchContent_MakeAvailable(googletest)
enable_testing() enable_testing()
add_executable(math_test test/tensor.cpp) add_executable(math_test test/tensor.cpp)
target_link_libraries(math_test GTest::gtest_main cenet) target_link_libraries(math_test GTest::gtest_main cenet)
include(GoogleTest) include(GoogleTest)
gtest_discover_tests(math_test) gtest_discover_tests(math_test)
endif()
+1 -1
View File
@@ -135,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);
+54 -5
View File
@@ -7,6 +7,7 @@
#include "./layer_fwd.hpp" #include "./layer_fwd.hpp"
#include "./layer_traits.hpp" #include "./layer_traits.hpp"
#include "cenet/layers/retained.hpp" #include "cenet/layers/retained.hpp"
#include "cenet/optim/adam.hpp"
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
@@ -184,8 +185,50 @@ struct conv2d final : public layer_tag {
return backpropErr; 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(math::is_tensor_v<input_type>);
static_assert(input_type::shape_type::rank == 3);
using value_type = typename input_type::value_type;
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
static_assert(!input_type::traits::dynamic, "dynamic input to conv2d is currently unsupported");
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static constexpr std::size_t OUT_CHANS = OutChannels;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
using weights_type =
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
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; ++time;
constexpr double beta1 = 0.9; 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 ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) { for (std::size_t ky = 0; ky < KernelSize; ++ky) {
for (std::size_t kx = 0; kx < KernelSize; ++kx) { 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] = momentumWeights[oc][ic][ky][kx] =
(beta1 * momentumWeights[oc][ic][ky][kx]) + ((1.0 - beta1) * avgGrad); (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); momentumBiases[oc] = (beta1 * momentumBiases[oc]) + ((1.0 - beta1) * avgGrad);
varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad); varianceBiases[oc] = (beta2 * varianceBiases[oc]) + ((1.0 - beta2) * avgGrad * avgGrad);
@@ -330,8 +373,11 @@ struct maxpool final : public layer_tag {
return backpropErr; 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) {}
}; };
}; };
@@ -377,8 +423,11 @@ struct flatten final : public layer_tag {
auto backward(const data<N, I>& data, R, Error&& prevErr) { auto backward(const data<N, I>& data, R, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>(); 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) {}
}; };
}; };
+55 -13
View File
@@ -10,6 +10,7 @@
#include "./layer_fwd.hpp" #include "./layer_fwd.hpp"
#include "./layer_traits.hpp" #include "./layer_traits.hpp"
#include "./retained.hpp" #include "./retained.hpp"
#include "cenet/optim/adam.hpp"
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
@@ -77,14 +78,6 @@ struct dense final : public layer_tag {
weights_type weights; weights_type weights;
biases_type biases; 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() { void reset() {
weights.view().fill(); weights.view().fill();
biases.view().fill(); biases.view().fill();
@@ -97,8 +90,51 @@ struct dense final : public layer_tag {
return std::forward<Error>(prevErr).matmul(data.weights.transpose()); 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 = math::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
weights_type 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 = math::matrix<value_type, 1, Features>;
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
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; ++time;
constexpr double beta1 = 0.9; constexpr double beta1 = 0.9;
@@ -107,7 +143,7 @@ struct dense final : public layer_tag {
for (std::size_t row = 0; row < input_cols; ++row) { for (std::size_t row = 0; row < input_cols; ++row) {
for (std::size_t col = 0; col < Features; ++col) { 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); momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad);
varianceWeights[row][col] = varianceWeights[row][col] =
@@ -121,7 +157,7 @@ struct dense final : public layer_tag {
} }
for (std::size_t col = 0; col < Features; ++col) { 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); momentumBiases[0][col] = (beta1 * momentumBiases[0][col]) + ((1.0 - beta1) * avgGrad);
varianceBiases[0][col] = (beta2 * varianceBiases[0][col]) + ((1.0 - beta2) * (avgGrad * avgGrad)); varianceBiases[0][col] = (beta2 * varianceBiases[0][col]) + ((1.0 - beta2) * (avgGrad * avgGrad));
@@ -172,8 +208,11 @@ struct sigmoid final : public layer_tag {
return std::forward<Error>(prevErr) * retained * return std::forward<Error>(prevErr) * retained *
(static_cast<typename output_type::value_type>(1) - 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 +252,11 @@ struct relu final : public layer_tag {
return std::forward<Error>(prevErr).apply(retained, return std::forward<Error>(prevErr).apply(retained,
[](auto in, auto check) { return check > 0.0 ? in : 0.0; }); [](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) {}
}; };
}; };
+72 -14
View File
@@ -24,68 +24,126 @@ struct binary_expression;
template <typename CRTP> template <typename CRTP>
struct ops_provider { struct ops_provider {
template <typename R> 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"); if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs) }; return { self(), std::forward<R>(rhs) };
} }
template <typename R> 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"); if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs) }; return { self(), std::forward<R>(rhs) };
} }
template <typename Func> 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"); if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<Func>(func) }; return { self(), std::forward<Func>(func) };
} }
template <typename 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"); if (!ops::apply<Func>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<Func>(func) }; return { self(), std::forward<Func>(func) };
} }
template <typename R, typename 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"); if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs), std::forward<Func>(func) }; return { self(), std::forward<R>(rhs), std::forward<Func>(func) };
} }
template <typename R, typename 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"); if (!ops::apply<Func>::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch");
return { self(), std::forward<R>(rhs), std::forward<Func>(func) }; 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"); if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() }; 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"); if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() }; return { self() };
} }
template <typename S> 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"); if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() }; return { self() };
} }
template <typename S> 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"); if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() }; return { self() };
} }
private: private:
decltype(auto) self() & { return reinterpret_cast<CRTP&>(*this); } decltype(auto) self() & { return static_cast<CRTP&>(*this); }
decltype(auto) self() && { return reinterpret_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 static_cast<const CRTP&>(*this); }
decltype(auto) self() const&& { return reinterpret_cast<const CRTP&&>(*this); } decltype(auto) self() const&& { return static_cast<const CRTP&&>(*this); }
}; };
namespace detail { namespace detail {
+22 -30
View File
@@ -44,8 +44,7 @@ public:
template <typename... RtDims, template <typename... RtDims,
typename = std::enable_if_t<( typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>> traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
explicit tensor(RtDims... dimensions) explicit tensor(RtDims... dimensions) {
: m_shape(dynamic_shape<Dims...>{}) {
set_dimensions(dimensions...); set_dimensions(dimensions...);
} }
@@ -64,6 +63,7 @@ public:
tensor& operator=(tensor&& other) noexcept { tensor& operator=(tensor&& other) noexcept {
if (this == &other) return *this; if (this == &other) return *this;
release(); release();
m_shape = std::move(other.m_shape);
if constexpr (!traits::inline_storage) { if constexpr (!traits::inline_storage) {
m_items = other.m_items; m_items = other.m_items;
other.m_items = nullptr; other.m_items = nullptr;
@@ -75,31 +75,24 @@ public:
tensor(const tensor& other) tensor(const tensor& other)
: m_shape(other.m_shape) { : m_shape(other.m_shape) {
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{}); set_dimensions(other.m_shape);
dyn_copy(other.m_items, std::make_index_sequence<sizeof...(Dims)>{}); dyn_copy(other.m_items);
} }
tensor& operator=(const tensor& other) { tensor& operator=(const tensor& other) {
if (this == &other) return *this; if (this == &other) return *this;
release(); release();
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{}); set_dimensions(other.m_shape);
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{}); dyn_copy(other.m_items);
return *this; return *this;
} }
public: public:
// TODO: improve aliasing semantics
template <typename E, template <typename E,
typename = std::enable_if_t<detail::is_expression_v<E> && !std::is_same_v<std::decay_t<E>, tensor>>> typename = std::enable_if_t<detail::is_expression_v<E> && !std::is_same_v<std::decay_t<E>, tensor>>>
tensor(E&& exprFwd) { // NOLINT tensor(E&& exprFwd) { // NOLINT
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
if constexpr (!traits::inline_storage) {
if constexpr (traits::dynamic) {
set_dimensions(exprFwd.shape()); set_dimensions(exprFwd.shape());
} else {
m_items = new value_type[traits::size];
}
}
E expr = std::forward<E>(exprFwd); E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < size(); ++i) { for (std::size_t i = 0; i < size(); ++i) {
@@ -109,13 +102,7 @@ public:
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>> template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator=(E&& exprFwd) { tensor& operator=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
if constexpr (traits::dynamic) {
if (m_shape != exprFwd.shape()) {
set_dimensions(exprFwd.shape()); set_dimensions(exprFwd.shape());
}
}
E expr = std::forward<E>(exprFwd); E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
@@ -167,14 +154,17 @@ public:
E expr = std::forward<E>(exprFwd); E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] /= expr; m_items[i] /= expr.coeff(i);
} }
return *this; return *this;
} }
public: public:
view_type view() { return { m_items, m_shape }; } view_type view() & { return { m_items, m_shape }; }
constant_view_type view() const { 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 view_type() { return view(); }
explicit operator constant_view_type() const { return view(); } explicit operator constant_view_type() const { return view(); }
@@ -190,16 +180,19 @@ public:
} }
public: public:
template <typename... RtDims, template <typename... RtDims,
typename = std::enable_if_t<( typename = std::enable_if_t<(sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
void set_dimensions(RtDims... dimensions) { void set_dimensions(RtDims... dimensions) {
if (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...)) if (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
throw std::runtime_error("invalid dynamic tensor dimensions"); throw std::runtime_error("unexpected shape");
if constexpr (!traits::inline_storage) {
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...); store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
release(); release();
m_items = new value_type[(dimensions * ... * 1)]; m_items = new value_type[(dimensions * ... * 1)];
std::memset(m_items, 0, sizeof(*m_items) * (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> template <template <std::size_t...> class Shape, std::size_t... ShapeDims>
@@ -246,8 +239,10 @@ private:
private: private:
template <typename... RtDims, std::size_t... Is> template <typename... RtDims, std::size_t... Is>
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) { 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)), ...); ((m_shape.dimensions[Is] = static_cast<std::size_t>(dimensions)), ...);
} }
}
private: private:
template <std::size_t I> template <std::size_t I>
constexpr std::size_t dimension() const { constexpr std::size_t dimension() const {
@@ -265,10 +260,7 @@ private:
} }
} }
template <std::size_t... Is> void dyn_copy(const value_type* src) { std::memcpy(m_items, src, sizeof(*m_items) * size()); }
void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
std::memcpy(m_items, src, sizeof(*m_items) * size());
}
void release() { void release() {
if constexpr (!traits::inline_storage) { if constexpr (!traits::inline_storage) {
+5
View File
@@ -176,6 +176,11 @@ private:
dimensions[I] = first; dimensions[I] = first;
store_impl<I + 1>(rest...); store_impl<I + 1>(rest...);
} }
template <std::size_t I, typename RDim>
void store_impl(RDim last) {
dimensions[I] = last;
}
public: public:
static constexpr auto rank = sizeof...(Dims); static constexpr auto rank = sizeof...(Dims);
static constexpr auto score = score_impl<0, Dims...>::value; static constexpr auto score = score_impl<0, Dims...>::value;
+2 -2
View File
@@ -83,10 +83,10 @@ public:
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) { void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
offset = std::min(offset, size()); offset = std::min(offset, size());
std::memcpy(m_view + offset, source, std::min(length, size() - offset) * 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> template <typename Dist>
void fill_random(Dist dist) { void fill_random(Dist dist) {
+30 -11
View File
@@ -4,6 +4,7 @@
#include "./network_traits.hpp" #include "./network_traits.hpp"
#include "cenet/layers/retained.hpp" #include "cenet/layers/retained.hpp"
#include "cenet/math/expr.hpp" #include "cenet/math/expr.hpp"
#include "cenet/optim/sgd.hpp"
#include <cstddef> #include <cstddef>
#include <istream> #include <istream>
@@ -21,8 +22,6 @@ public:
using input_type = typename traits::input_type; using input_type = typename traits::input_type;
using output_type = typename traits::output_type; using output_type = typename traits::output_type;
public:
const output_type& get_output() const { return m_output; }
public: public:
struct loss { struct loss {
double value; double value;
@@ -63,7 +62,6 @@ private:
} }
} }
private: private:
// TODO: pass in the optimizer
struct layers_grad_gen { struct layers_grad_gen {
template <std::size_t I, typename LF, typename... LR> template <std::size_t I, typename LF, typename... LR>
struct impl { struct impl {
@@ -78,7 +76,24 @@ private:
using type = typename impl<0, Layers...>::type; 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;
@@ -134,12 +149,16 @@ public:
detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct detail::network_retained_t<network> m_retained; // TODO: move retained state to its own struct
typename layers_grad_gen::type m_layers; typename layers_grad_gen::type m_layers;
typename layers_optim_gen<Optim>::type m_optimizer;
}; };
public: 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: private:
template <std::size_t I, typename Current> template <std::size_t I, typename Current, class Optim>
auto feed_impl(Current&& current, learning_state& state) { auto feed_impl(Current&& current, learning_state<Optim>& state) {
if constexpr (I == sizeof...(Layers)) { if constexpr (I == sizeof...(Layers)) {
return std::forward<Current>(current); return std::forward<Current>(current);
} else { } else {
@@ -157,13 +176,14 @@ private:
} }
} }
public: 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)>{}); 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>(state.m_layers).apply(at<I>(), state.count(), rate), ...); (std::get<I>(state.m_optimizer).apply(at<I>(), std::get<I>(state.m_layers), state.count(), rate), ...);
} }
public: public:
template <std::size_t I> template <std::size_t I>
@@ -203,7 +223,6 @@ public:
using layer = typename layers_data_gen::template at<I, I, Layers...>::type; using layer = typename layers_data_gen::template at<I, I, Layers...>::type;
private: private:
typename layers_data_gen::type m_layers; typename layers_data_gen::type m_layers;
output_type m_output;
}; };
} // namespace cenet } // namespace cenet
+12
View File
@@ -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
+12
View File
@@ -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
BIN
View File
Binary file not shown.