Compare commits

...
6 Commits
7 changed files with 482 additions and 39 deletions
+61 -8
View File
@@ -2,13 +2,16 @@
#define CENET_LAYER_HPP
#include "mat.hpp"
#include "math/tensor.hpp"
#include "tensor.hpp"
#include <array>
#include <cstddef>
#include <istream>
#include <ostream>
#include <tuple>
#include <type_traits>
#include <vector>
namespace cenet {
@@ -32,13 +35,25 @@ struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
template <typename T>
struct is_tokens : std::false_type {};
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 = std::tuple_element_t<I - 1, typename NN::layer_types>::output_type;
using type = typename std::tuple_element_t<I - 1, typename NN::layer_types>::output_type;
};
template <class NN>
@@ -57,7 +72,7 @@ class dense_layer final : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = mat<1, Features, T>;
@@ -161,7 +176,7 @@ class sigmoid_layer final : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = input_type;
@@ -188,7 +203,7 @@ private:
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.hadamard(static_cast<output_type::inner_type>(1) - output));
return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
}
void apply_grad(gradient&, double, double) {}
@@ -201,7 +216,7 @@ class relu_layer final : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type;
input_type savedInput;
@@ -244,7 +259,7 @@ class conv2d_layer final : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(input_type::RANK == 3);
@@ -425,7 +440,7 @@ class maxpool_layer : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(std::is_same_v<typename input_type::inner_type, T>);
static_assert(input_type::RANK == 3);
@@ -515,7 +530,7 @@ class flatten_layer : public layer_info {
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static constexpr std::size_t FEATURES = input_type::SIZE;
@@ -552,6 +567,44 @@ private:
};
};
template <std::size_t VocabSize, std::size_t EmbedDims>
class tok2vec_layer : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tokens_v<input_type>);
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
output_type output;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
output.set_dimensions(input.size(), EmbedDims);
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
return std::move(prevErr);
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
} // namespace cenet
#endif // CENET_LAYER_HPP
+101
View File
@@ -0,0 +1,101 @@
#ifndef CENET_MATH_EXPR_HPP
#define CENET_MATH_EXPR_HPP
#include "ops.hpp"
#include "tensor_traits.hpp"
#include <type_traits>
#include <utility>
namespace cenet {
namespace math {
struct expression_tag {};
template <typename E, typename Op>
struct unary_expression : expression_tag {
E expr;
auto eval(std::size_t index) { return Op{}(expr.coeff(index)); }
};
template <typename L, typename R, typename Op>
struct binary_expression : expression_tag {
L lhs;
R rhs;
template <typename LFwd = L, typename RFwd = R>
binary_expression(LFwd&& lhs, RFwd&& rhs)
: lhs(std::forward<LFwd>(lhs)), rhs(std::forward<RFwd>(rhs)) {}
auto eval(std::size_t index) { return Op{}(index, lhs.coeff(index), as_operand(rhs)); }
private:
template <typename T>
static decltype(auto) as_operand(T&& value) {
if constexpr (is_tensor_v<T>) {
return std::as_const(value).view();
} else {
return std::forward<T>(value);
}
}
};
namespace detail {
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
template <typename T, typename = void>
struct operand {
using type = T;
};
template <typename T>
struct operand<T, std::void_t<typename remove_cvref_t<T>::view_type>> {
using type = typename remove_cvref_t<T>::view_type;
};
template <typename T>
using operand_t = typename operand<T>::type;
template <typename T>
static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, std::remove_cv_t<T>>;
template <typename E>
struct expression_result {
using type = remove_cvref_t<E>;
};
template <typename E, typename Op>
struct expression_result<unary_expression<E, Op>> {
using type = typename Op::template result_type<operand_t<typename expression_result<remove_cvref_t<E>>::type>>;
};
template <typename L, typename R, typename Op>
struct expression_result<binary_expression<L, R, Op>> {
using type = typename Op::template result_type<operand_t<typename expression_result<remove_cvref_t<L>>::type>,
operand_t<typename expression_result<remove_cvref_t<R>>::type>>;
};
} // namespace detail
template <typename L,
typename R,
typename Op = ops::plus,
typename = std::void_t<typename detail::expression_result<binary_expression<L, R, Op>>::type>>
binary_expression<L, R, Op> operator+(L&& lhs, R&& rhs) {
return { std::forward<L>(lhs), std::forward<R>(rhs) };
}
template <typename L,
typename R,
typename Op = ops::minus,
typename = std::void_t<typename detail::expression_result<binary_expression<L, R, Op>>::type>>
binary_expression<L, R, Op> operator-(L&& lhs, R&& rhs) {
return { std::forward<L>(lhs), std::forward<R>(rhs) };
}
} // namespace math
} // namespace cenet
#endif // CENET_MATH_EXPR_HPP
+56
View File
@@ -0,0 +1,56 @@
#ifndef CENET_MATH_OPS_HPP
#define CENET_MATH_OPS_HPP
#include "tensor_traits.hpp"
#include <cstddef>
namespace cenet {
namespace math {
namespace ops {
class plus {
private:
template <typename L, typename R>
struct result_type_impl {};
template <typename LT, typename RT, std::size_t... Dims>
struct result_type_impl<tensor_view<LT, Dims...>, tensor_view<RT, Dims...>> {
using type =
tensor<decltype(std::declval<detach_storage_t<LT>>() + std::declval<detach_storage_t<RT>>()), Dims...>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename LT, typename R>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const {
return lhs + rhs.coeff(index);
}
};
class minus {
private:
template <typename L, typename R>
struct result_type_impl {};
template <typename LT, typename RT, std::size_t... Dims>
struct result_type_impl<tensor_view<LT, Dims...>, tensor_view<RT, Dims...>> {
using type =
tensor<decltype(std::declval<detach_storage_t<LT>>() - std::declval<detach_storage_t<RT>>()), Dims...>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename LT, typename R>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const {
return lhs - rhs.coeff(index);
}
};
} // namespace ops
} // namespace math
} // namespace cenet
#endif // CENET_MATH_OPS_HPP
+246 -26
View File
@@ -1,6 +1,7 @@
#ifndef CENET_MATH_TENSOR_HPP
#define CENET_MATH_TENSOR_HPP
#include "expr.hpp"
#include "tensor_fwd.hpp"
#include "tensor_traits.hpp"
@@ -13,30 +14,187 @@
namespace cenet {
namespace math {
namespace detail {
template <std::size_t... Dims>
struct static_shape {
static_shape() = default;
template <std::size_t... ExtDims, typename = std::enable_if_t<(sizeof...(ExtDims) >= sizeof...(Dims))>>
explicit static_shape(const static_shape<ExtDims...>& oth) {}
template <std::size_t... OthDims>
static constexpr bool compatible() {
return ((Dims == OthDims) && ...);
}
template <typename T>
static constexpr bool compatible() {
return compatible_impl<T>::value;
}
private:
template <typename T>
struct compatible_impl : std::false_type {};
template <typename T, std::size_t... OthDims>
struct compatible_impl<tensor<T, OthDims...>>
: std::conditional_t<((Dims == OthDims) && ...), std::true_type, std::false_type> {};
};
template <std::size_t... Dims>
struct dynamic_shape {
dynamic_shape() = default;
template <std::size_t ExtRank, typename = std::enable_if_t<(ExtRank >= sizeof...(Dims))>>
explicit dynamic_shape(const dynamic_shape<ExtRank>& oth) {
constexpr std::size_t ext_offset = ExtRank - sizeof...(Dims);
for (std::size_t i = 0; i < sizeof...(Dims); ++i) {
dimensions[i] = oth.dimensions[ext_offset + i];
}
}
template <std::size_t... OthDims>
static constexpr bool compatible() {
return ((Dims == dynamic_extent || Dims == OthDims) && ...);
}
template <typename T>
static constexpr bool compatible() {
return compatible_impl<T>::value;
}
std::size_t dimensions[sizeof...(Dims)]{};
private:
template <typename T>
struct compatible_impl : std::false_type {};
template <typename T, std::size_t... OthDims>
struct compatible_impl<tensor<T, OthDims...>>
: std::conditional_t<((Dims == dynamic_extent || Dims == OthDims) && ...), std::true_type, std::false_type> {};
};
} // namespace detail
template <typename T, std::size_t... Dims>
class tensor_view {
template <typename, std::size_t, std::size_t...>
static_assert(std::is_arithmetic_v<T>);
template <typename, std::size_t...>
friend class tensor;
template <typename, std::size_t...>
friend class tensor_view;
public:
using traits = tensor_traits<tensor<T, Dims...>>;
using value_type = traits::value_type;
using value_type = T;
public:
template <typename... Offs,
typename = std::enable_if_t<(
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
decltype(auto) slice(Offs... offs) {
auto* ptr = m_view + calculate_offset(std::make_tuple(offs...));
if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr;
return inner_view<T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
}
template <typename... Offs,
typename = std::enable_if_t<(
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
decltype(auto) slice(Offs... offs) const {
const auto* ptr = m_view + calculate_offset(std::make_tuple(offs...));
if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr;
return inner_view<const T, sizeof...(Offs)>(ptr, std::index_sequence<Dims...>{});
}
public:
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
decltype(auto) operator[](Off off) {
return slice(off);
}
template <typename Off, typename = std::enable_if_t<std::is_integral_v<Off>>>
decltype(auto) operator[](Off off) const {
return slice(off);
}
private:
template <typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
return calculate_offset_impl<sizeof...(Offs) - 1, sizeof...(Dims) - sizeof...(Offs)>(offs);
}
template <std::size_t I, std::size_t Start, typename... Offs>
std::size_t calculate_offset_impl(const std::tuple<Offs...>& offs) const {
if constexpr (I == 0)
return std::get<I>(offs) * dimension<Start + I>();
else
return (calculate_offset_impl<I - 1, Start>(offs) + std::get<I>(offs)) * dimension<Start + I>();
}
public:
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
auto dimensions() const { return dimensions_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
private:
template <std::size_t... Is>
constexpr std::size_t size_impl(std::index_sequence<Is...>) const {
return (dimension<Is>() * ... * 1);
}
template <std::size_t... Is>
constexpr auto dimensions_impl(std::index_sequence<Is...>) const {
return std::make_tuple(dimension<Is>()...);
}
public:
value_type& coeff(std::size_t index) { return m_view[index]; }
const value_type& coeff(std::size_t index) const { return m_view[index]; }
value_type* data() { return m_view; }
const value_type* data() const { return m_view; }
private:
template <typename InT, std::size_t Off, std::size_t First, std::size_t... Rest>
auto inner_view(value_type* view, std::index_sequence<First, Rest...>) {
if constexpr (Off == 0)
return tensor_view<InT, First, Rest...>{ view, m_shape };
else
return inner_view<InT, Off - 1>(view, std::index_sequence<Rest...>{});
}
private:
template <std::size_t I>
constexpr std::size_t dimension() const {
if constexpr (traits::dynamic && traits::dimensions[I] == dynamic_extent) {
return m_shape.dimensions[I];
} else {
return traits::dimensions[I];
}
}
private:
using shape_type =
std::conditional_t<traits::dynamic, detail::dynamic_shape<Dims...>, detail::static_shape<Dims...>>;
template <typename Fwd>
tensor_view(value_type* view, Fwd&& shape)
: m_view(view), m_shape(std::forward<Fwd>(shape)) {}
private:
value_type* m_view;
std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> m_strides;
shape_type m_shape;
};
template <typename T, std::size_t... Dims>
class tensor {
public:
using traits = tensor_traits<tensor>;
using value_type = traits::value_type;
using value_type = typename traits::value_type;
using constant_value_type = const value_type;
using view_type = tensor_view<value_type, Dims...>;
using constant_view_type = tensor_view<constant_value_type, Dims...>;
private:
using shape_type =
std::conditional_t<traits::dynamic, detail::dynamic_shape<Dims...>, detail::static_shape<Dims...>>;
public:
tensor() {
if constexpr (traits::dynamic) {
m_items = nullptr;
} else if constexpr (traits::inplace_storage) {
m_shape = {};
} else if constexpr (traits::inline_storage) {
std::memset(m_items, 0, sizeof(m_items));
} else {
m_items = new value_type[traits::size];
@@ -46,41 +204,78 @@ public:
template <typename... RtDims,
typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
explicit tensor(RtDims... dimensions) {
explicit tensor(RtDims... dimensions)
: m_shape(detail::dynamic_shape<Dims...>{}) {
set_dimensions(dimensions...);
}
~tensor() { release(); }
tensor(tensor&& other) noexcept { *this = std::move(other); }
tensor(tensor&& other) noexcept
: m_shape(std::move(other.m_shape)) {
if constexpr (!traits::inline_storage) m_items = nullptr;
*this = std::move(other);
}
tensor& operator=(tensor&& other) noexcept {
if (this == &other) return *this;
release();
m_items = other.m_items;
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
other.m_items = nullptr;
if constexpr (!traits::inline_storage) other.m_items = nullptr;
return *this;
}
tensor(const tensor& other) { *this = other; }
tensor(const tensor& other)
: m_shape(other.m_shape) {
if constexpr (!traits::inline_storage) m_items = nullptr;
*this = other;
}
tensor& operator=(const tensor& other) {
if (this == &other) return *this;
release();
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
std::memcpy(m_shape.dimensions, other.m_shape.dimensions, sizeof(m_shape.dimensions));
std::memcpy(m_shape.strides, other.m_shape.strides, sizeof(m_shape.strides));
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{});
return *this;
}
public:
template <typename E,
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
shape_type::template compatible<typename detail::expression_result<E>::type>()>>
tensor(E&& expr) { // NOLINT
if constexpr (!traits::inline_storage) {
static_assert(!traits::dynamic, "Dynamic tensors are not supported yet!");
m_items = new value_type[traits::size];
}
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] = std::forward<E>(expr).eval(i);
}
}
template <typename E,
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator=(E&& expr) {
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] = std::forward<E>(expr);
}
}
public:
view_type view() { return { m_items, m_shape }; }
constant_view_type view() const { return { m_items, m_shape }; }
explicit operator view_type() { return view(); }
explicit operator constant_view_type() const { return view(); }
public:
template <typename... RtDims,
typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
void set_dimensions(RtDims... dimensions) {
if constexpr (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
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...);
@@ -88,6 +283,26 @@ public:
m_items = new value_type[(dimensions * ... * 1)];
std::memset(m_items, 0, sizeof(*m_items) * (dimensions * ... * 1));
}
public:
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
auto dimensions() const { return dimensions_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
private:
template <std::size_t... Is>
constexpr std::size_t size_impl(std::index_sequence<Is...>) const {
return (dimension<Is>() * ... * 1);
}
template <std::size_t... Is>
constexpr auto dimensions_impl(std::index_sequence<Is...>) const {
return std::make_tuple(dimension<Is>()...);
}
public:
value_type& coeff(std::size_t index) { return m_items[index]; }
const value_type& coeff(std::size_t index) const { return m_items[index]; }
value_type* data() { return m_items; }
const value_type* data() const { return m_items; }
private:
template <typename... RtDims, std::size_t... Is>
constexpr bool valid_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
@@ -100,35 +315,40 @@ private:
}
private:
template <typename... RtDims, std::size_t... Is>
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
return ((m_dimensions[Is] = dimensions) && ...);
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) {
((m_shape.dimensions[Is] = static_cast<std::size_t>(dimensions)), ...);
}
private:
template <std::size_t I>
constexpr std::size_t dimension() const {
if constexpr (traits::dynamic && traits::dimensions[I] == dynamic_extent) {
return m_shape.dimensions[I];
} else {
return traits::dimensions[I];
}
}
private:
template <std::size_t... Is>
void dyn_alloc(std::index_sequence<Is...>) {
m_items = new value_type[(m_dimensions[Is] * ...)];
m_items = new value_type[(m_shape.dimensions[Is] * ...)];
}
template <std::size_t... Is>
void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
std::memcpy(m_items, src, sizeof(*m_items) * (m_dimensions[Is] * ... * 1));
std::memcpy(m_items, src, sizeof(*m_items) * (m_shape.dimensions[Is] * ... * 1));
}
void release() {
if constexpr (!traits::inline_storage) {
delete[] m_items;
m_items = nullptr;
}
}
private:
traits::storage_type m_items;
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_dimensions;
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_strides;
typename traits::storage_type m_items;
shape_type m_shape;
};
template <typename T, std::size_t M, std::size_t N>
using matrix = tensor<T, M, N>;
} // namespace math
} // namespace cenet
+15 -2
View File
@@ -36,6 +36,19 @@ struct is_storage_inline<inline_storage<T>> : std::true_type {};
template <typename T>
static constexpr auto is_storage_inline_v = is_storage_inline<T>::value;
template <typename T>
struct detach_storage {
using type = T;
};
template <typename T>
struct detach_storage<inline_storage<T>> {
using type = T;
};
template <typename T>
using detach_storage_t = typename detach_storage<T>::type;
template <typename T>
struct is_tensor : std::false_type {};
@@ -66,8 +79,8 @@ struct tensor_traits {};
template <typename T, std::size_t... Dims>
struct tensor_traits<tensor<T, Dims...>> {
using tensor_type = tensor<T, Dims...>;
using value_type = tensor_storage<tensor_type>::value_type;
using storage_type = tensor_storage<tensor_type>::storage_type;
using value_type = typename tensor_storage<tensor_type>::value_type;
using storage_type = typename tensor_storage<tensor_type>::storage_type;
static constexpr auto rank = sizeof...(Dims);
static constexpr auto dynamic = is_tensor_dynamic_v<tensor_type>;
+2 -2
View File
@@ -38,7 +38,7 @@ private:
}
public:
using input_type = Input;
using output_type = output_layer_type::output_type;
using output_type = typename output_layer_type::output_type;
public:
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; }
public:
@@ -103,7 +103,7 @@ public:
private:
std::size_t m_count = 0;
gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
};
public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) {
BIN
View File
Binary file not shown.