Compare commits

...
21 Commits
Author SHA1 Message Date
CHatingPython 513413515e build: enforce C++17 and add gpt example 2026-10-30 17:01:51 +01:00
CHatingPython 2702167244 feat(nn): implement tok2vec layer 2026-10-30 17:01:11 +01:00
CHatingPython 1b8db65330 fix(examples): fix tokenizer 2026-10-30 17:00:56 +01:00
CHatingPython a0ca8e572d feat(math): add compound operators and fill(value) 2026-10-30 16:37:23 +01:00
CHatingPython bdb0198640 refactor(math): move tensor_view to new file
Move tensor_view to its own new file and add fill() functions.
2026-10-30 16:04:10 +01:00
CHatingPython e8edbe7b7e feat(math): add multiply operation 2026-10-30 14:55:22 +01:00
CHatingPython 5360b4f9b0 fix(math): fix nested expressions 2026-10-30 14:53:49 +01:00
CHatingPython a4640c4835 feat(math): add support for dynamic tensor ops 2026-10-29 22:19:06 +01:00
CHatingPython 22bf8db5e8 refactor(math): improve tensor shapes 2026-10-29 10:55:29 +01:00
CHatingPython 814050baca fix(math): use decltype(auto) instead of auto 2026-10-29 10:03:42 +01:00
CHatingPython 0734de1386 feat(math): operation fundamentals 2026-10-29 10:01:26 +01:00
CHatingPython 1f95dd51db feat(math): add size() and data() to tensor view 2026-10-29 06:44:50 +01:00
CHatingPython 94276e68d3 feat(math): implement slice for tensor_view 2026-10-28 21:35:43 +01:00
CHatingPython a47302d532 fix(math): fix tensor.hpp 2026-10-28 18:42:54 +01:00
CHatingPython 5598ff06cd feat(math): begin work on the tensor/math library 2026-10-28 17:43:52 +01:00
CHatingPython 8da41abbca feat: add dump and load to tokenizer 2026-10-27 22:50:59 +01:00
CHatingPython 806652fd86 feat: implement a basic tokenizer 2026-10-27 19:58:15 +01:00
CHatingPython fa0418914a refactor: remove input.hpp 2026-10-25 19:21:17 +01:00
CHatingPython 471c9c8997 fix: fill biases with zeros in fill_random 2026-10-25 18:37:50 +01:00
CHatingPython 490661ebc0 refactor: add type parameter to layer inputs 2026-10-25 15:55:07 +01:00
CHatingPython aa438bfac7 fix: remove sigmoid derivative from backprop 2026-10-25 15:40:58 +01:00
20 changed files with 1647 additions and 193 deletions
+24 -2
View File
@@ -2,12 +2,12 @@ cmake_minimum_required(VERSION 3.14)
project(cenet CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(cenet INTERFACE
include/cenet/mat.hpp
include/cenet/tensor.hpp
include/cenet/input.hpp
include/cenet/layer.hpp
include/cenet/network.hpp
include/cenet/cenet.hpp)
@@ -18,3 +18,25 @@ target_link_libraries(xor PRIVATE cenet)
add_executable(mnist example/mnist.cpp)
target_link_libraries(mnist PRIVATE cenet)
add_executable(tokenizer example/tokenizer.cpp)
target_link_libraries(tokenizer PRIVATE cenet)
add_executable(gpt example/gpt.cpp)
target_link_libraries(gpt PRIVATE cenet)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(math_test test/tensor.cpp)
target_link_libraries(math_test GTest::gtest_main cenet)
include(GoogleTest)
gtest_discover_tests(math_test)
+20
View File
@@ -0,0 +1,20 @@
#include "cenet/network.hpp"
#include "tokenizer.hpp"
#include <cenet/cenet.hpp>
#include <iostream>
#include <vector>
static constexpr std::size_t VOCAB_SIZE = 2256;
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::tok2vec_layer<2256, 512>>;
int main(void) {
tokenizer<VOCAB_SIZE> bpe;
if (!bpe.load("./gpt/shakespeare.bpe")) return 1;
std::cout << "Vocabulary loaded!\n";
auto* gpt = new network_type();
return 0;
}
+6 -6
View File
@@ -11,7 +11,7 @@
#include <random>
#include <vector>
using network_type = cenet::network<cenet::tensor_input<1, 28, 28>,
using network_type = cenet::network<cenet::tensor<float, 1, 28, 28>,
cenet::conv2d_layer<8, 3, 1, 1>,
cenet::relu_layer,
cenet::maxpool_layer<>,
@@ -25,8 +25,8 @@ using network_type = cenet::network<cenet::tensor_input<1, 28, 28>,
static std::uniform_real_distribution<> dist(-1, 1);
struct data {
cenet::tensor<double, 1, 28, 28> xs;
cenet::mat<1, 10> ys;
cenet::tensor<float, 1, 28, 28> xs;
cenet::mat<1, 10, float> ys;
};
using dataset = std::vector<data>;
@@ -81,7 +81,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::uint8_t pixel = 0;
images.read(reinterpret_cast<char*>(&pixel), sizeof(pixel));
set[i].xs[0][row][col] = static_cast<double>(pixel) / 255.0;
set[i].xs[0][row][col] = static_cast<float>(pixel) / 255.0F;
}
}
@@ -157,11 +157,11 @@ int main(void) {
const auto& output = mnistNet->feed(validationSet[i].xs);
for (std::size_t j = 0; j < 10; ++j) {
double diff = output.get()[0][j] - validationSet[i].ys[0][j];
float diff = output[0][j] - validationSet[i].ys[0][j];
totalLoss += diff * diff;
}
if (col_largest_idx(output.get()[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits;
if (col_largest_idx(output[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits;
}
currentLoss = totalLoss / static_cast<double>(validationSet.size());
+26
View File
@@ -0,0 +1,26 @@
#include "tokenizer.hpp"
#include <cstdio>
#include <fstream>
#include <iostream>
int main(void) {
static constexpr const char* filepath = "./gpt/shakespeare.txt";
std::ifstream file(filepath, std::ios::binary);
if (!file.is_open()) return 1;
std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
tokenizer<2256> bpe;
bpe.train(contents);
bpe.dump("./gpt/shakespeare.bpe");
auto tokens = bpe.encode("Hello, World!");
for (auto tok : tokens) {
std::printf("0x%08X: ", tok); // NOLINT
std::cout << bpe.token_text(tok) << '\n';
}
std::cout << bpe.decode(tokens) << '\n';
return 0;
}
+351
View File
@@ -0,0 +1,351 @@
#ifndef TOKENIZER_HPP
#define TOKENIZER_HPP
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
class string_storage {
private:
static constexpr std::size_t MIN_CHUNK_CAP = 8ULL * 1024;
public:
string_storage() = default;
~string_storage() { free(); }
string_storage(string_storage&& other) noexcept { *this = std::move(other); }
string_storage& operator=(string_storage&& other) noexcept {
if (this == &other) return *this;
free();
m_head = other.m_head;
m_tail = other.m_tail;
other.m_head = nullptr;
other.m_tail = nullptr;
return *this;
}
string_storage(const string_storage&) = delete;
string_storage& operator=(const string_storage&) = delete;
public:
std::string_view allocate(const char* begin, std::size_t length) {
region* reg = m_head;
while (reg != nullptr && reg->size > reg->used + length)
reg = reg->next;
if (reg == nullptr) {
const std::size_t size = (std::max(MIN_CHUNK_CAP, length) + 3) & ~0x4ULL;
reg = reinterpret_cast<region*>(std::malloc(sizeof(region) + size)); // NOLINT
new (reg) region(size);
if (m_head == nullptr) {
m_head = m_tail = reg;
} else {
m_tail = m_tail->next = reg;
}
}
char* string = reg->data() + reg->used;
std::memcpy(string, begin, length);
reg->used += length;
return { string, length };
}
std::string_view allocate(std::string_view lhs, std::string_view rhs) {
std::size_t length = lhs.size() + rhs.size();
region* reg = m_head;
while (reg != nullptr && reg->size > reg->used + length)
reg = reg->next;
if (reg == nullptr) {
const std::size_t size = (std::max(MIN_CHUNK_CAP, length) + 3) & ~0x4ULL;
reg = reinterpret_cast<region*>(std::malloc(sizeof(region) + size)); // NOLINT
new (reg) region(size);
if (m_head == nullptr) {
m_head = m_tail = reg;
} else {
m_tail = m_tail->next = reg;
}
}
char* string = reg->data() + reg->used;
std::memcpy(string, lhs.data(), lhs.size());
std::memcpy(string + lhs.size(), rhs.data(), rhs.size());
reg->used += length;
return { string, length };
}
private:
void free() {
while (m_head != nullptr) {
region* next = m_head->next;
std::free(m_head); // NOLINT
m_head = next;
}
m_tail = m_head = nullptr;
}
private:
struct region {
region* next = nullptr;
std::size_t size;
std::size_t used = 0;
explicit region(std::size_t size)
: size(size) {}
char* data() { return reinterpret_cast<char*>(this + 1); }
};
private:
region* m_head = nullptr;
region* m_tail = nullptr;
};
template <std::uint32_t DictionarySize>
class tokenizer {
static_assert(DictionarySize >= 256);
public:
tokenizer() {
m_dict.reserve(DictionarySize);
for (int i = 0; i < 256; ++i) {
char ch = static_cast<char>(i);
m_dict.push_back(m_strings.allocate(&ch, 1));
}
}
public:
void train(std::string_view text, std::size_t minFreq = 2) {
// TODO: split the tokens into groupings so that "abc123" is treated as "abc" and "123"
std::vector<std::uint32_t> tokens;
std::unordered_map<std::uint64_t, std::size_t> freaks{};
const auto* it = text.begin();
for (; it + 1 < text.end(); ++it) {
tokens.push_back(static_cast<std::uint8_t>(*it) & 0xFFULL);
++freaks[(static_cast<std::uint8_t>(*it) & 0xFFULL) |
(((static_cast<std::uint8_t>(*(it + 1))) & 0xFFULL) << 32ULL)];
}
if (it < text.end()) tokens.push_back(static_cast<std::uint8_t>(*it) & 0xFFULL);
if (tokens.empty()) return;
while (tokens.size() > 1 && m_dict.size() < DictionarySize) {
auto best = freaks.begin();
auto it = freaks.begin();
++it;
while (it != freaks.end()) {
if (it->second == 0) {
it = freaks.erase(it);
continue;
}
if (it->second > best->second || (it->second == best->second && it->first > best->first)) best = it;
++it;
}
if (best->second < minFreq) break;
std::uint32_t newToken = m_dict.size();
m_merges.emplace(best->first, newToken);
m_dict.push_back(
m_strings.allocate(m_dict[best->first & 0xFFFFFFFF], m_dict[(best->first >> 32ULL) & 0xFFFFFFFF]));
std::size_t newIdx = 0; // Index pointing to the current element in the "new version" of tokens vector.
// Essentially, we just override tokens instead of back buffering or whatever.
for (std::size_t i = 0; i < tokens.size();) {
if (i + 1 >= tokens.size()) {
tokens[newIdx++] = tokens[i++];
continue;
}
std::uint64_t pair = (tokens[i] & 0xFFFFFFFF) | ((tokens[i + 1] & 0xFFFFFFFFULL) << 32ULL);
if (pair == best->first) {
if (i > 0) {
pair <<= 32ULL;
pair |= (tokens[newIdx - 1] & 0xFFFFFFFF);
auto it = freaks.find(pair);
assert(it != freaks.end());
assert(it != freaks.end() && it->second > 0);
--it->second;
pair &= 0xFFFFFFFF;
pair |= (newToken & 0xFFFFFFFFULL) << 32ULL;
++freaks[pair];
}
pair = best->first;
auto it = freaks.find(pair);
assert(it != freaks.end());
assert(it->second > 0);
--it->second;
tokens[(++i, newIdx++)] = newToken;
if (i + 1 < tokens.size()) {
pair = tokens[i] | (tokens[i + 1] & 0xFFFFFFFFULL) << 32ULL;
auto it = freaks.find(pair);
assert(it != freaks.end() && it->second > 0);
--it->second;
pair &= ~0xFFFFFFFFULL;
pair |= newToken & 0xFFFFFFFFULL;
++freaks[pair];
}
++i;
continue;
}
tokens[newIdx++] = tokens[i++];
}
tokens.resize(newIdx);
}
}
std::vector<std::uint32_t> encode(std::string_view source) const {
if (source.empty()) return {};
std::vector<std::uint32_t> tokens;
const auto* it = source.begin();
std::uint64_t pair = (extend_char(*it++) << 32);
while ((pair & 0xFFFFFFFF00000000) != 0) {
pair >>= 32ULL;
if (it != source.end()) pair |= (extend_char(*it++) << 32);
auto jt = m_merges.find(pair);
if (jt == m_merges.end()) {
tokens.push_back(pair & 0xFFFFFFFF);
continue;
}
pair = (jt->second & 0xFFFFFFFFULL) << 32ULL;
if (!tokens.empty()) {
while (!tokens.empty()) {
jt = m_merges.find(tokens.back() | pair);
if (jt == m_merges.end()) break;
pair = (jt->second & 0xFFFFFFFFULL) << 32ULL;
tokens.pop_back();
}
}
}
return tokens;
}
std::string decode(const std::vector<std::uint32_t>& tokens) const {
if (tokens.empty()) return {};
std::string string;
for (auto tok : tokens) {
string.append(m_dict.at(tok));
}
return string;
}
public:
bool dump(const char* filepath) const {
std::ofstream file(filepath, std::ios::binary | std::ios::out | std::ios::trunc);
if (!file.is_open()) return false;
dump_u64(file, m_dict.size());
for (auto sv : m_dict) {
dump_sv(file, sv);
}
dump_u64(file, m_merges.size());
for (const auto& [pair, merge] : m_merges) {
dump_u32(file, (pair >> 0ULL) & 0xFFFFFFFF);
dump_u32(file, (pair >> 32ULL) & 0xFFFFFFFF);
dump_u32(file, merge);
}
return true;
}
private:
void dump_u64(std::ofstream& file, std::uint64_t value) const {
dump(file, value, std::make_index_sequence<sizeof(value)>{});
}
void dump_u32(std::ofstream& file, std::uint32_t value) const {
dump(file, value, std::make_index_sequence<sizeof(value)>{});
}
void dump_sv(std::ofstream& file, std::string_view value) const {
dump_u32(file, value.size());
file.write(value.data(), static_cast<std::streamsize>(value.size()));
}
template <typename T, std::size_t... Is>
void dump(std::ofstream& file, T value, std::index_sequence<Is...>) const {
char buf[] = { static_cast<char>((value >> (Is << 3ULL)) & 0xFF)... };
file.write(buf, sizeof(buf));
}
public:
bool load(const char* filepath) {
std::ifstream file(filepath, std::ios::binary | std::ios::in);
if (!file.is_open()) return false;
m_dict.clear();
auto dictSize = load_u64(file);
assert(dictSize <= DictionarySize);
m_dict.resize(dictSize);
for (std::uint64_t i = 0; i < dictSize; ++i) {
m_dict[i] = load_sv(file);
}
m_merges.clear();
auto mergesSize = load_u64(file);
m_merges.reserve(mergesSize);
for (std::uint64_t i = 0; i < mergesSize; ++i) {
auto lhs = load_u32(file);
auto rhs = load_u32(file);
auto merge = load_u32(file);
m_merges.emplace(lhs | (static_cast<std::uint64_t>(rhs) << 32ULL), merge);
}
return true;
}
private:
auto load_u64(std::ifstream& file) const { return load<std::uint64_t>(file); }
auto load_u32(std::ifstream& file) const { return load<std::uint32_t>(file); }
auto load_sv(std::ifstream& file) {
auto length = load_u32(file);
char buf[length];
file.read(buf, length);
return m_strings.allocate(buf, length);
}
template <typename T>
T load(std::ifstream& file) const {
return load<T>(file, std::make_index_sequence<sizeof(T)>{});
}
template <typename T, std::size_t... Is>
T load(std::ifstream& file, std::index_sequence<Is...>) const {
char buf[sizeof(T)];
file.read(buf, sizeof(buf));
return (((buf[Is] & 0xFFULL) << Is) | ...);
}
public:
std::string_view token_text(std::uint32_t token) const { return m_dict.at(token); }
private:
constexpr std::uint64_t extend_char(char ch) const {
return static_cast<std::uint64_t>(static_cast<std::uint8_t>(ch));
}
private:
string_storage m_strings;
std::vector<std::string_view> m_dict;
std::unordered_map<std::uint64_t, std::uint32_t> m_merges;
};
#endif // TOKENIZER_HPP
+10 -10
View File
@@ -7,7 +7,7 @@
static std::uniform_real_distribution<> dist(-1, 1);
int main(void) {
static constexpr double s_trainData[4] = {
static constexpr float s_trainData[4] = {
0, // 0 ^ 0
1, // 1 ^ 0
1, // 0 ^ 1
@@ -15,7 +15,7 @@ int main(void) {
};
// network net;
using network_type = cenet::network<cenet::dense_input<2>,
using network_type = cenet::network<cenet::mat<1, 2, float>,
cenet::dense_layer<2>,
cenet::sigmoid_layer,
cenet::dense_layer<1>,
@@ -36,9 +36,9 @@ int main(void) {
while (gen <= 10'000'000) {
for (std::size_t i = 0; i < 4; ++i) {
cenet::mat<1, 2> xs;
xs[0][0] = static_cast<double>(i & 1);
xs[0][1] = static_cast<double>(i > 1);
cenet::mat<1, 2, float> xs;
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
xorNet.train(xs, s_trainData[i], EPSILON);
}
@@ -46,12 +46,12 @@ int main(void) {
double acc = 0.0;
for (std::size_t i = 0; i < 4; ++i) {
cenet::mat<1, 2> xs;
xs[0][0] = static_cast<double>(i & 1);
xs[0][1] = static_cast<double>(i > 1);
cenet::mat<1, 2, float> xs;
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
double yHat = xorNet.feed(xs).get()[0][0];
double error = yHat - s_trainData[i];
float yHat = xorNet.feed(xs)[0][0];
float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) {
std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n";
+2 -3
View File
@@ -1,8 +1,7 @@
#ifndef CENET_HPP
#define CENET_HPP
#include "input.hpp"
#include "layer.hpp"
#include "network.hpp"
#include "layer.hpp" // IWYU pragma: export
#include "network.hpp" // IWYU pragma: export
#endif // CENET_HPP
-83
View File
@@ -1,83 +0,0 @@
#ifndef CENET_INPUT_HPP
#define CENET_INPUT_HPP
#include "mat.hpp"
#include "tensor.hpp"
#include <cstdint>
#include <type_traits>
namespace cenet {
struct layer_input {
static constexpr std::uint32_t DENSE_TAG = 0x444E5345;
static constexpr std::uint32_t TENSOR_TAG = 0x544E5352;
};
template <std::size_t Features>
class dense_input : public layer_input {
template <typename Input, typename... Layers>
friend class network;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = DENSE_TAG;
static constexpr std::size_t FEATURES = Features;
using type = mat<1, FEATURES>;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<type, Args...>>>
inner(Args&&... args)
: xs(std::forward<Args>(args)...) {}
operator type&() { return xs; }
operator const type&() const { return xs; }
type& get() { return xs; }
const type& get() const { return xs; }
type xs;
};
};
template <std::size_t... Dims>
class tensor_input : public layer_input {
template <typename Input, typename... Layers>
friend class network;
friend class layer_info;
private:
struct inner final {
static constexpr std::uint32_t TAG = TENSOR_TAG;
using type = tensor<double, Dims...>;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<type, Args...>>>
inner(Args&&... args)
: xs(std::forward<Args>(args)...) {}
operator type&() { return xs; }
operator const type&() const { return xs; }
type& get() { return xs; }
const type& get() const { return xs; }
type xs;
};
};
namespace detail {
template <typename T, typename = void>
struct is_layer_input : std::false_type {};
template <typename T>
struct is_layer_input<T, std::enable_if_t<std::is_base_of_v<layer_input, T>>> : std::true_type {};
} // namespace detail
} // namespace cenet
#endif // CENET_INPUT_HPP
+233 -82
View File
@@ -1,20 +1,60 @@
#ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP
#include "input.hpp"
#include "mat.hpp"
#include "math/tensor.hpp"
#include "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_dense : std::false_type {};
template <std::size_t N, typename T>
struct is_dense<mat<1, N, T>> : std::true_type {};
template <typename T>
static constexpr auto is_dense_v = is_dense<T>::value;
template <typename T>
struct is_tensor : std::false_type {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
template <typename T>
struct is_tokens : std::false_type {};
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>
@@ -26,23 +66,23 @@ protected:
using input_inner_t = typename T::inner;
};
template <std::size_t Features>
template <std::size_t Features, typename T = float>
class dense_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::DENSE_TAG);
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = input_inner_t<dense_input<Features>>;
using output_type = mat<1, Features, T>;
static constexpr std::size_t INPUT_FEATURES = input_type::FEATURES;
static constexpr std::size_t INPUT_FEATURES = input_type::COLS;
static constexpr std::size_t OUTPUT_FEATURES = Features;
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES>;
using biases_type = mat<1, OUTPUT_FEATURES>;
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES, T>;
using biases_type = mat<1, OUTPUT_FEATURES, T>;
struct gradient final {
using parent_type = inner;
@@ -68,27 +108,27 @@ private:
output_type output;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size());
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size());
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
double scale = std::sqrt(2.0 / static_cast<double>(INPUT_FEATURES));
T scale = std::sqrt(2.0 / static_cast<T>(INPUT_FEATURES));
weights = decltype(weights)::random(dist) * scale;
biases = decltype(biases)::random(dist) * scale;
biases = decltype(biases){};
}
auto& forward(const input_type& input) { return output = (input.get() * weights) + biases; }
auto& forward(const input_type& input) { return output = (input * weights) + biases; }
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
grad.weights += input.get().transpose() * prevErr;
grad.weights += input.transpose() * prevErr;
grad.biases += prevErr;
return prevErr * weights.transpose();
@@ -103,14 +143,14 @@ private:
for (std::size_t row = 0; row < INPUT_FEATURES; ++row) {
for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) {
double avgGrad = grad.weights[row][col] / divisor;
auto avgGrad = grad.weights[row][col] / divisor;
grad.momentumWeights[row][col] = beta1 * grad.momentumWeights[row][col] + (1.0 - beta1) * avgGrad;
grad.varianceWeights[row][col] =
beta2 * grad.varianceWeights[row][col] + (1.0 - beta2) * (avgGrad * avgGrad);
double momentumCorrected = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time));
double varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time));
auto momentumCorrected = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time));
auto varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time));
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
@@ -122,8 +162,8 @@ private:
grad.momentumBiases[0][col] = beta1 * grad.momentumBiases[0][col] + (1.0 - beta1) * avgGrad;
grad.varianceBiases[0][col] = beta2 * grad.varianceBiases[0][col] + (1.0 - beta2) * (avgGrad * avgGrad);
double momentumCorrected = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time));
double varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time));
auto momentumCorrected = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time));
auto varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time));
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
@@ -137,8 +177,8 @@ 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;
static_assert(input_type::TAG == layer_input::DENSE_TAG);
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = input_type;
output_type output;
@@ -147,6 +187,7 @@ private:
void reset() {}
};
static float sigmoid(float in) { return 1 / (1 + std::exp(-in)); }
static double sigmoid(double in) { return 1 / (1 + std::exp(-in)); }
void dump(std::ostream& os) const {}
@@ -157,13 +198,13 @@ private:
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
output.get().apply(input, [](double unusd, double in) { return sigmoid(in); });
output.apply(input, [](auto unusd, auto in) { return sigmoid(in); });
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.get().hadamard(1.0 - output.get()));
return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
}
void apply_grad(gradient&, double, double) {}
@@ -176,7 +217,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;
@@ -195,44 +236,51 @@ private:
auto& forward(const input_type& input) {
savedInput = input;
output.get().apply(input, [](double unusd, double in) { return in > 0.0 ? in : 0.0; });
output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const {
return prevErr.apply(savedInput, [](double in, double check) { return check > 0.0 ? in : 0.0; });
return prevErr.apply(savedInput, [](auto in, auto check) { return check > 0.0 ? in : 0.0; });
}
void apply_grad(gradient&, double, double) {}
};
};
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
template <std::size_t OutChannels,
std::size_t KernelSize,
std::size_t Stride = 1,
std::size_t Padding = 0,
typename T = float>
class conv2d_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(input_type::RANK == 3);
using input_tensor = input_type::type;
static_assert(input_tensor::RANK == 3);
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_tensor::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_tensor::template dimension<2>();
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static constexpr std::size_t OUT_CHANS = OutChannels;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
using output_type = input_inner_t<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type = tensor<double, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<double, OUT_CHANS>;
using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<T, OUT_CHANS>;
struct gradient final {
using parent_type = inner;
@@ -258,20 +306,20 @@ private:
output_type output;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(double) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(double) * biases.size());
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(double) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(double) * biases.size());
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr double fanIn = static_cast<double>(IN_CHANS * KernelSize * KernelSize);
constexpr T fanIn = static_cast<T>(IN_CHANS * KernelSize * KernelSize);
const double scale = std::sqrt(2.0 / fanIn);
const T scale = std::sqrt(2.0 / fanIn);
weights = decltype(weights)::random(dist);
weights *= scale;
@@ -282,7 +330,7 @@ private:
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) {
double value = biases[oc];
auto value = biases[oc];
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
@@ -293,13 +341,13 @@ private:
static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
value += input.get()[ic][iy][ix] * weights[oc][ic][ky][kx];
value += input[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output.get()[oc][oy][ox] = value;
output[oc][oy][ox] = value;
}
}
}
@@ -308,12 +356,12 @@ private:
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
input_type backpropErr;
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
const double err = prevErr[oc][oy][ox];
const auto err = prevErr[oc][oy][ox];
grad.biases[oc] += err;
@@ -329,7 +377,7 @@ private:
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
grad.weights[oc][ic][ky][kx] += input.get()[ic][iy][ix] * err;
grad.weights[oc][ic][ky][kx] += input[ic][iy][ix] * err;
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err;
}
@@ -361,9 +409,9 @@ private:
grad.varianceWeights[oc][ic][ky][kx] =
beta2 * grad.varianceWeights[oc][ic][ky][kx] + (1.0 - beta2) * avgGrad * avgGrad;
double momentumCorrected =
auto momentumCorrected =
grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time));
double varianceCorrected =
auto varianceCorrected =
grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time));
weights[oc][ic][ky][kx] -=
@@ -372,13 +420,13 @@ private:
}
}
double avgGrad = grad.biases[oc] / divisor;
auto avgGrad = grad.biases[oc] / divisor;
grad.momentumBiases[oc] = beta1 * grad.momentumBiases[oc] + (1.0 - beta1) * avgGrad;
grad.varianceBiases[oc] = beta2 * grad.varianceBiases[oc] + (1.0 - beta2) * avgGrad * avgGrad;
double momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time));
double varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time));
auto momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time));
auto varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time));
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
}
@@ -386,28 +434,27 @@ private:
};
};
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
template <std::size_t PoolSize = 2, std::size_t Stride = 2, typename T = float>
class maxpool_layer : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = input_type_s<NN, I>::type;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
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);
using input_tensor = input_type::type;
static_assert(input_tensor::RANK == 3);
static constexpr std::size_t IN_CHANS = input_tensor::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_tensor::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_tensor::template dimension<2>();
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
static constexpr std::size_t OUT_CHANS = IN_CHANS;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
using output_type = input_inner_t<tensor_input<OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output;
struct gradient final {
@@ -425,15 +472,15 @@ private:
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
double maxValue = input.get()[ch][oy * Stride][ox * Stride];
auto maxValue = input[ch][oy * Stride][ox * Stride];
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
maxValue = std::max(maxValue, input.get()[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
maxValue = std::max(maxValue, input[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
}
}
output.get()[ch][oy][ox] = maxValue;
output[ch][oy][ox] = maxValue;
}
}
}
@@ -443,7 +490,7 @@ private:
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
input_type backpropErr;
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
@@ -451,15 +498,15 @@ private:
std::size_t maxY = oy * Stride;
std::size_t maxX = ox * Stride;
double maxValue = input.get()[ch][maxY][maxX];
auto maxValue = input[ch][maxY][maxX];
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
const std::size_t yIdx = (oy * Stride) + ky;
const std::size_t xIdx = (ox * Stride) + kx;
if (input.get()[ch][yIdx][xIdx] > maxValue) {
maxValue = input.get()[ch][yIdx][xIdx];
if (input[ch][yIdx][xIdx] > maxValue) {
maxValue = input[ch][yIdx][xIdx];
maxY = yIdx;
maxX = xIdx;
}
@@ -484,14 +531,12 @@ 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;
static_assert(input_type::TAG == layer_input::TENSOR_TAG);
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
using input_tensor = input_type::type;
static constexpr std::size_t FEATURES = input_type::SIZE;
static constexpr std::size_t FEATURES = input_tensor::SIZE;
using output_type = input_inner_t<dense_input<FEATURES>>;
using output_type = mat<1, FEATURES, typename input_type::inner_type>;
output_type output;
struct gradient final {
@@ -506,13 +551,13 @@ private:
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
std::copy(input.get().begin(), input.get().end(), output.xs.data());
std::copy(input.begin(), input.end(), output.data());
return output;
}
template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) {
typename input_type::type backpropErr;
input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
@@ -523,6 +568,112 @@ 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>);
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>;
output_type output;
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& forward(const input_type& input) {
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 <typename Error>
void backward(const input_type& input, 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
+4
View File
@@ -25,7 +25,11 @@ private:
template <std::size_t M, std::size_t N, typename T = double, typename = std::enable_if_t<(M >= 1 && N >= 1)>>
class mat {
public:
static constexpr std::size_t ROWS = M;
static constexpr std::size_t COLS = N;
using col_type = mat_col<N, T>;
using inner_type = T;
public:
mat() { std::memset(m_items, 0, sizeof(m_items)); }
+113
View File
@@ -0,0 +1,113 @@
#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;
constexpr auto shape() const { return expr.shape(); }
auto coeff(std::size_t index) const { 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)) {}
constexpr auto shape() const { return Op::shape(lhs, rhs); }
auto coeff(std::size_t index) const { 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) };
}
template <typename L,
typename R,
typename Op = ops::multiply,
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
+136
View File
@@ -0,0 +1,136 @@
#ifndef CENET_MATH_OPS_HPP
#define CENET_MATH_OPS_HPP
#include "tensor_shape.hpp"
#include "tensor_traits.hpp"
#include <cstddef>
#include <stdexcept>
#include <type_traits>
namespace cenet {
namespace math {
namespace ops {
class plus {
private:
template <typename L, typename R>
struct result_type_impl {};
template <typename LT, std::size_t... LDims, typename RT, std::size_t... RDims>
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> {
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() + std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape();
}
template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) {
return lhs.shape();
} else {
return rhs.shape();
}
}
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, std::size_t... LDims, typename RT, std::size_t... RDims>
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> {
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() - std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape();
}
template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) {
return lhs.shape();
} else {
return rhs.shape();
}
}
template <typename LT, typename R>
constexpr auto operator()(std::size_t index, LT lhs, const R& rhs) const {
return lhs - rhs.coeff(index);
}
};
class multiply {
private:
template <typename L, typename R>
struct result_type_impl {};
template <typename LT, std::size_t... LDims, typename RT, std::size_t... RDims>
struct result_type_impl<tensor_view<LT, LDims...>, tensor_view<RT, RDims...>> {
using lhs_view = tensor_view<LT, LDims...>;
using rhs_view = tensor_view<RT, RDims...>;
using type = std::enable_if_t<
detail::is_shape_equivalent<typename lhs_view::shape_type, typename rhs_view::shape_type>::value,
tensor<decltype(std::declval<detach_storage_t<LT>>() * std::declval<detach_storage_t<RT>>()), LDims...>>;
};
public:
template <typename L, typename R>
using result_type = typename result_type_impl<L, R>::type;
template <typename L, typename R, typename = std::enable_if_t<(is_tensor_v<L> && is_tensor_v<R>)>>
static bool compatible(const L& lhs, const R& rhs) {
return lhs.shape() == rhs.shape();
}
template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) {
if (lhs.shape() != rhs.shape()) throw std::runtime_error("unexpected tensor shape");
if constexpr (detail::is_static_shape_v<decltype(lhs.shape())>) {
return lhs.shape();
} else {
return rhs.shape();
}
}
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
+253
View File
@@ -0,0 +1,253 @@
#ifndef CENET_MATH_TENSOR_HPP
#define CENET_MATH_TENSOR_HPP
#include "expr.hpp"
#include "tensor_fwd.hpp"
#include "tensor_shape.hpp"
#include "tensor_traits.hpp"
#include "tensor_view.hpp"
#include <cstddef>
#include <cstring>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace cenet {
namespace math {
template <typename T, std::size_t... Dims>
class tensor {
public:
using traits = tensor_traits<tensor>;
using value_type = typename traits::value_type;
using constant_value_type = const value_type;
using view_type = tensor_view<value_type, Dims...>;
using constant_view_type = tensor_view<constant_value_type, Dims...>;
using shape_type = std::conditional_t<traits::dynamic, dynamic_shape<Dims...>, static_shape<Dims...>>;
public:
tensor() {
if constexpr (traits::dynamic) {
m_items = nullptr;
m_shape = {};
} else if constexpr (traits::inline_storage) {
std::memset(m_items, 0, sizeof(m_items));
} else {
m_items = new value_type[traits::size];
}
}
template <typename... RtDims,
typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
explicit tensor(RtDims... dimensions)
: m_shape(dynamic_shape<Dims...>{}) {
set_dimensions(dimensions...);
}
~tensor() { release(); }
tensor(tensor&& other) noexcept
: m_shape(std::move(other.m_shape)) {
if constexpr (!traits::inline_storage) {
m_items = other.m_items;
other.m_items = nullptr;
} else {
std::memcpy(m_items, other.m_items, sizeof(m_items));
}
}
tensor& operator=(tensor&& other) noexcept {
if (this == &other) return *this;
release();
if constexpr (!traits::inline_storage) {
m_items = other.m_items;
other.m_items = nullptr;
} else {
std::memcpy(m_items, other.m_items, sizeof(m_items));
}
return *this;
}
tensor(const tensor& other)
: m_shape(other.m_shape) {
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{});
}
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)>{});
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) {
if constexpr (traits::dynamic) {
set_dimensions(expr.shape());
} else {
m_items = new value_type[traits::size];
}
}
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] = std::forward<E>(expr).coeff(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) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] = std::forward<E>(expr);
}
}
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) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] += std::forward<E>(expr);
}
}
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) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] -= std::forward<E>(expr);
}
}
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) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] *= std::forward<E>(expr);
}
}
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) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
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 (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
throw std::runtime_error("invalid dynamic tensor dimensions");
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
release();
m_items = new value_type[(dimensions * ... * 1)];
std::memset(m_items, 0, sizeof(*m_items) * (dimensions * ... * 1));
}
template <template <std::size_t...> class Shape, std::size_t... ShapeDims>
void set_dimensions(const Shape<ShapeDims...>& shape) {
set_dimensions_impl(shape, std::make_index_sequence<sizeof...(ShapeDims)>{});
}
private:
template <template <std::size_t...> class Shape, std::size_t... ShapeDims, std::size_t... Is>
void set_dimensions_impl(const Shape<ShapeDims...>& shape, std::index_sequence<Is...>) {
set_dimensions(shape.template get<Is>()...);
}
public:
constexpr std::size_t size() const { return size_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
auto dimensions() const { return dimensions_impl(std::make_index_sequence<sizeof...(Dims)>{}); }
private:
template <std::size_t... Is>
constexpr std::size_t size_impl(std::index_sequence<Is...>) const {
return (dimension<Is>() * ... * 1);
}
template <std::size_t... Is>
constexpr auto dimensions_impl(std::index_sequence<Is...>) const {
return std::make_tuple(dimension<Is>()...);
}
public:
value_type& coeff(std::size_t index) { return m_items[index]; }
const value_type& coeff(std::size_t index) const { return m_items[index]; }
value_type* data() { return m_items; }
const value_type* data() const { return m_items; }
const shape_type& shape() const { return m_shape; }
private:
template <typename... RtDims, std::size_t... Is>
constexpr bool valid_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
return (valid_dim<decltype(dimensions), Is>(dimensions) && ...);
}
template <typename RtDim, std::size_t I>
constexpr bool valid_dim(RtDim dim) const {
return traits::dimensions[I] == dynamic_extent || traits::dimensions[I] == dim;
}
private:
template <typename... RtDims, std::size_t... Is>
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) {
((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_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_shape.dimensions[Is] * ... * 1));
}
void release() {
if constexpr (!traits::inline_storage) {
delete[] m_items;
m_items = nullptr;
}
}
private:
typename traits::storage_type m_items{};
shape_type m_shape;
};
} // namespace math
} // namespace cenet
#endif // CENET_MATH_TENSOR_HPP
+29
View File
@@ -0,0 +1,29 @@
#ifndef CENET_MATH_FWD_HPP
#define CENET_MATH_FWD_HPP
#include <cstddef>
#include <limits>
namespace cenet {
namespace math {
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();
template <typename T>
struct inline_storage {
using value_type = T;
};
template <typename T, std::size_t... Dims>
class tensor_view;
template <typename T, std::size_t... Dims>
class tensor;
template <typename T, std::size_t M, std::size_t N>
using matrix = tensor<T, M, N>;
} // namespace math
} // namespace cenet
#endif // CENET_MATH_FWD_HPP
+196
View File
@@ -0,0 +1,196 @@
#ifndef CENET_MATH_TENSOR_SHAPE_HPP
#define CENET_MATH_TENSOR_SHAPE_HPP
#include "tensor_fwd.hpp"
#include <cstddef>
#include <type_traits>
#include <utility>
namespace cenet {
namespace math {
template <std::size_t... Dims>
struct shape {};
template <std::size_t... Dims>
struct static_shape;
template <std::size_t... Dims>
struct dynamic_shape;
template <std::size_t... Dims>
struct static_shape : shape<Dims...> {
static_shape() = default;
template <std::size_t... ExtDims, typename = std::enable_if_t<(sizeof...(ExtDims) >= sizeof...(Dims))>>
explicit static_shape(const static_shape<ExtDims...>& oth) {}
template <std::size_t... OthDims>
static constexpr bool compatible() {
return ((Dims == OthDims) && ...);
}
template <typename T>
static constexpr bool compatible() {
return compatible_impl<T>::value;
}
template <std::size_t... RDims>
bool operator==(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) && ((Dims == RDims) && ...);
}
template <std::size_t... RDims>
bool operator!=(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) != sizeof...(RDims) || ((Dims != RDims) || ...);
}
template <std::size_t I>
constexpr auto get() const {
return get_impl<I, Dims...>::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 I, std::size_t First, std::size_t... Rest>
struct get_impl : get_impl<I - 1, Rest...> {};
template <std::size_t First, std::size_t... Rest>
struct get_impl<0, First, Rest...> {
static constexpr auto value = First;
};
};
template <std::size_t... Dims>
struct dynamic_shape : shape<Dims...> {
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;
}
template <std::size_t... RDims>
bool operator==(const static_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) &&
compare_impl<decltype(rhs), RDims...>(std::make_index_sequence<sizeof...(Dims)>{}, rhs);
}
template <std::size_t... RDims>
bool operator==(const dynamic_shape<RDims...>& rhs) const {
return sizeof...(Dims) == sizeof...(RDims) &&
compare_impl<decltype(rhs), RDims...>(std::make_index_sequence<sizeof...(Dims)>{}, rhs);
}
template <std::size_t I>
constexpr auto get() const {
return get_impl<I, Dims...>::value == dynamic_extent ? dimensions[I] : get_impl<I, Dims...>::value;
}
std::size_t dimensions[sizeof...(Dims)]{};
private:
template <typename T>
struct compatible_impl : std::false_type {};
template <typename T, std::size_t... OthDims>
struct compatible_impl<tensor<T, OthDims...>>
: std::conditional_t<((Dims == dynamic_extent || Dims == OthDims) && ...), std::true_type, std::false_type> {};
template <template <std::size_t...> class L,
std::size_t... LDims,
template <std::size_t...> class R,
std::size_t... RDims,
std::size_t... Is>
static constexpr bool compare_impl(std::index_sequence<Is...>, const L<LDims...>& lhs, const R<RDims...>& rhs) {
return ((lhs.template get<Is>() == rhs.template get<Is>()) && ...);
}
template <std::size_t I, std::size_t First, std::size_t... Rest>
struct get_impl : get_impl<I - 1, Rest...> {};
template <std::size_t First, std::size_t... Rest>
struct get_impl<0, First, Rest...> {
static constexpr auto value = First;
};
};
namespace detail {
template <typename T>
struct is_static_shape : std::false_type {};
template <std::size_t... Dims>
struct is_static_shape<static_shape<Dims...>> : std::true_type {};
template <typename T>
inline constexpr auto is_static_shape_v = is_static_shape<T>::value;
template <template <std::size_t...> class L,
std::size_t... LDims,
template <std::size_t...> class R,
std::size_t... RDims,
std::size_t... Is>
static constexpr bool shape_compare_impl(std::index_sequence<Is...>, const L<LDims...>& lhs, const R<RDims...>& rhs) {
return ((lhs.template get<Is>() == rhs.template get<Is>()) && ...);
}
template <typename L, typename R>
struct is_shape_equivalent : std::false_type {};
template <template <std::size_t...> class L,
std::size_t LFirst,
std::size_t... LRest,
template <std::size_t...> class R,
std::size_t RFirst,
std::size_t... RRest>
struct is_shape_equivalent<L<LFirst, LRest...>, R<RFirst, RRest...>>
: std::conditional_t<(LFirst == RFirst || LFirst == dynamic_extent || RFirst == dynamic_extent),
is_shape_equivalent<L<LRest...>, R<RRest...>>,
std::false_type> {};
template <template <std::size_t...> class L, template <std::size_t...> class R>
struct is_shape_equivalent<L<>, R<>> : std::true_type {};
} // namespace detail
template <template <std::size_t...> class L,
std::size_t... LDims,
template <std::size_t...> class R,
std::size_t... RDims>
bool operator==(const L<LDims...>& lhs, const R<RDims...>& rhs) {
return sizeof...(LDims) == sizeof...(RDims) &&
detail::shape_compare_impl(std::make_index_sequence<sizeof...(LDims)>{}, lhs, rhs);
}
template <template <std::size_t...> class L,
std::size_t... LDims,
template <std::size_t...> class R,
std::size_t... RDims>
bool operator!=(const L<LDims...>& lhs, const R<RDims...>& rhs) {
return sizeof...(LDims) != sizeof...(RDims) ||
!detail::shape_compare_impl(std::make_index_sequence<sizeof...(LDims)>{}, lhs, rhs);
}
} // namespace math
} // namespace cenet
#endif // CENET_MATH_TENSOR_SHAPE_HPP
+99
View File
@@ -0,0 +1,99 @@
#ifndef CENET_MATH_TENSOR_TRAITS_HPP
#define CENET_MATH_TENSOR_TRAITS_HPP
#include "tensor_fwd.hpp"
#include <type_traits>
namespace cenet {
namespace math {
template <typename T>
struct tensor_storage {};
template <typename T, std::size_t... Dims>
struct tensor_storage<tensor<T, Dims...>> {
static_assert(std::is_arithmetic_v<T>);
using value_type = T;
using storage_type = T*;
};
template <typename T, std::size_t... Dims>
struct tensor_storage<tensor<inline_storage<T>, Dims...>> {
static_assert(std::is_arithmetic_v<T>);
using value_type = T;
using storage_type = T[(Dims * ... * 1)];
};
template <typename T>
struct is_storage_inline : std::false_type {};
template <typename T>
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 {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
template <typename T>
struct is_tensor_dynamic : std::false_type {};
template <typename T>
struct is_tensor_dynamic<tensor<T>> : std::false_type {};
template <typename T, std::size_t First, std::size_t... Rest>
struct is_tensor_dynamic<tensor<T, First, Rest...>> : is_tensor_dynamic<tensor<T, Rest...>> {};
template <typename T, std::size_t... Rest>
struct is_tensor_dynamic<tensor<T, dynamic_extent, Rest...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_dynamic_v = is_tensor_dynamic<T>::value;
template <typename T>
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 = 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>;
static constexpr auto inline_storage = is_storage_inline_v<T>;
static_assert(!inline_storage || !dynamic, "Tensor storage set to inline with dynamic extents!");
static constexpr std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> dimensions = { Dims... };
static constexpr std::size_t size = dynamic ? dynamic_extent : (Dims * ... * 1);
};
} // namespace math
} // namespace cenet
#endif // CENET_MATH_TENSOR_TRAITS_HPP
+136
View File
@@ -0,0 +1,136 @@
#ifndef CENET_MATH_TENSOR_VIEW_HPP
#define CENET_MATH_TENSOR_VIEW_HPP
#include "expr.hpp"
#include "tensor_fwd.hpp"
#include "tensor_shape.hpp"
#include "tensor_traits.hpp"
#include <cstddef>
#include <cstring>
#include <type_traits>
#include <utility>
namespace cenet {
namespace math {
template <typename T, std::size_t... Dims>
class tensor_view {
static_assert(std::is_arithmetic_v<T>);
template <typename, std::size_t...>
friend class tensor;
template <typename, std::size_t...>
friend class tensor_view;
public:
using traits = tensor_traits<tensor<T, Dims...>>;
using shape_type = std::conditional_t<traits::dynamic, dynamic_shape<Dims...>, static_shape<Dims...>>;
using value_type = T;
public:
template <typename... Offs,
typename = std::enable_if_t<(
sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v<Offs> && ...))>>
decltype(auto) slice(Offs... offs) {
auto* ptr = m_view + 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:
void fill(value_type fill = {}) {
for (std::size_t i = 0; i < size(); ++i) {
m_view[i] = fill;
}
}
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
offset = std::min(offset, size());
std::memcpy(m_view + offset, source, std::min(length, size() - offset));
}
void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size()); }
public:
value_type& coeff(std::size_t index) { return m_view[index]; }
const value_type& coeff(std::size_t index) const { return m_view[index]; }
value_type* data() { return m_view; }
const value_type* data() const { return m_view; }
const shape_type& shape() const { return m_shape; }
private:
template <typename InT, std::size_t Off, std::size_t First, std::size_t... Rest>
auto inner_view(value_type* view, std::index_sequence<First, Rest...>) {
if constexpr (Off == 0)
return tensor_view<InT, First, Rest...>{ view, m_shape };
else
return inner_view<InT, Off - 1>(view, std::index_sequence<Rest...>{});
}
private:
template <std::size_t I>
constexpr std::size_t dimension() const {
if constexpr (traits::dynamic && traits::dimensions[I] == dynamic_extent) {
return m_shape.dimensions[I];
} else {
return traits::dimensions[I];
}
}
private:
template <typename Fwd>
tensor_view(value_type* view, Fwd&& shape)
: m_view(view), m_shape(std::forward<Fwd>(shape)) {}
private:
value_type* m_view;
shape_type m_shape;
};
} // namespace math
} // namespace cenet
#endif // CENET_MATH_TENSOR_VIEW_HPP
+4 -4
View File
@@ -37,8 +37,8 @@ private:
return std::get<I>(m_layers);
}
public:
using input_type = Input::inner;
using output_type = output_layer_type::output_type;
using input_type = Input;
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,12 +103,12 @@ 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) {
feed(input);
auto outputErr = (get_output().get() - expected).hadamard(get_output()).hadamard(1.0 - get_output().get());
auto outputErr = get_output() - expected;
get_layer<0>().backward(input,
std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
+2
View File
@@ -21,6 +21,8 @@ public:
}
static constexpr std::size_t RANK = 1 + sizeof...(Rest);
using inner_type = T;
public:
template <typename InT, std::size_t InFirst, std::size_t... InRest>
class view {
BIN
View File
Binary file not shown.