Compare commits

...
5 Commits
14 changed files with 712 additions and 148 deletions
+3 -1
View File
@@ -7,7 +7,6 @@ set(CMAKE_CXX_STANDARD 20)
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 +17,6 @@ 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)
+3 -3
View File
@@ -11,7 +11,7 @@
#include <random>
#include <vector>
using network_type = cenet::network<cenet::tensor_input<float, 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<>,
@@ -157,11 +157,11 @@ int main(void) {
const auto& output = mnistNet->feed(validationSet[i].xs);
for (std::size_t j = 0; j < 10; ++j) {
float 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 <std::size_t... Is>
void dump(std::ofstream& file, auto 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.insert(lhs | (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(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
+2 -2
View File
@@ -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>,
@@ -50,7 +50,7 @@ int main(void) {
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
float yHat = xorNet.feed(xs).get()[0][0];
float yHat = xorNet.feed(xs)[0][0];
float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) {
+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
-85
View File
@@ -1,85 +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, typename T = float>
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 inner_type = T;
using type = mat<1, FEATURES, T>;
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 <typename T, 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 inner_type = T;
using type = tensor<T, 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
+70 -52
View File
@@ -1,15 +1,39 @@
#ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP
#include "input.hpp"
#include "mat.hpp"
#include "tensor.hpp"
#include <cstddef>
#include <istream>
#include <ostream>
#include <tuple>
#include <type_traits>
namespace cenet {
namespace detail {
template <typename T>
struct is_dense : std::false_type {};
template <std::size_t N, typename T>
struct is_dense<mat<1, N, T>> : std::true_type {};
template <typename T>
static constexpr auto is_dense_v = is_dense<T>::value;
template <typename T>
struct is_tensor : std::false_type {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
} // namespace detail
struct layer_info {
protected:
template <class NN, std::size_t I>
@@ -34,11 +58,11 @@ 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);
static_assert(detail::is_dense_v<input_type>);
using output_type = input_inner_t<dense_input<Features, T>>;
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, T>;
@@ -81,14 +105,14 @@ private:
void fill_random(const Dist& dist) {
T scale = std::sqrt(2.0 / static_cast<T>(INPUT_FEATURES));
weights = decltype(weights)::random(dist) * scale;
biases = decltype(biases)::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();
@@ -138,7 +162,7 @@ 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);
static_assert(detail::is_dense_v<input_type>);
using output_type = input_type;
output_type output;
@@ -158,13 +182,13 @@ private:
void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) {
output.get().apply(input, [](auto unusd, auto 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(static_cast<output_type::inner_type>(1) - output.get()));
return prevErr.hadamard(output.hadamard(static_cast<output_type::inner_type>(1) - output));
}
void apply_grad(gradient&, double, double) {}
@@ -196,7 +220,7 @@ private:
auto& forward(const input_type& input) {
savedInput = input;
output.get().apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; });
return output;
}
@@ -221,14 +245,12 @@ 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);
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_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_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
@@ -239,7 +261,7 @@ private:
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<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<T, OUT_CHANS>;
@@ -268,20 +290,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;
@@ -303,13 +325,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;
}
}
}
@@ -318,7 +340,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 oc = 0; oc < OUT_CHANS; ++oc) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
@@ -339,7 +361,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;
}
@@ -404,21 +426,19 @@ 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);
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(std::is_same_v<typename input_tensor::inner_type, T>);
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<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>>;
using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output;
struct gradient final {
@@ -436,15 +456,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) {
auto 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;
}
}
}
@@ -454,7 +474,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) {
@@ -462,15 +482,15 @@ private:
std::size_t maxY = oy * Stride;
std::size_t maxX = ox * Stride;
auto 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;
}
@@ -496,13 +516,11 @@ 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);
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, typename input_tensor::inner_type>>;
using output_type = mat<1, FEATURES, typename input_type::inner_type>;
output_type output;
struct gradient final {
@@ -517,13 +535,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());
+3
View File
@@ -25,6 +25,9 @@ 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:
+135
View File
@@ -0,0 +1,135 @@
#ifndef CENET_MATH_TENSOR_HPP
#define CENET_MATH_TENSOR_HPP
#include "tensor_fwd.hpp"
#include "tensor_traits.hpp"
#include <cstddef>
#include <cstring>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace cenet {
namespace math {
template <typename T, std::size_t... Dims>
class tensor_view {
template <typename, std::size_t, std::size_t...>
friend class tensor;
public:
using traits = tensor_traits<tensor<T, Dims...>>;
using value_type = traits::value_type;
public:
private:
value_type* m_view;
std::enable_if_t<(sizeof...(Dims) > 0), std::size_t[sizeof...(Dims)]> m_strides;
};
template <typename T, std::size_t... Dims>
class tensor {
public:
using traits = tensor_traits<tensor>;
using value_type = traits::value_type;
public:
tensor() {
if constexpr (traits::dynamic) {
m_items = nullptr;
} else if constexpr (traits::inplace_storage) {
std::memset(m_items, 0, sizeof(m_items));
} else {
m_items = new value_type[traits::size];
}
}
template <typename... RtDims,
typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
explicit tensor(RtDims... dimensions) {
set_dimensions(dimensions...);
}
~tensor() { release(); }
tensor(tensor&& other) noexcept { *this = std::move(other); }
tensor& operator=(tensor&& other) noexcept {
if (this == &other) return *this;
release();
m_items = other.m_items;
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
other.m_items = nullptr;
return *this;
}
tensor(const tensor& other) { *this = other; }
tensor& operator=(const tensor& other) {
if (this == &other) return *this;
release();
std::memcpy(m_dimensions, other.m_dimensions, sizeof(m_dimensions));
std::memcpy(m_strides, other.m_strides, sizeof(m_strides));
dyn_alloc(std::make_index_sequence<sizeof...(Dims)>{});
dyn_copy(std::make_index_sequence<sizeof...(Dims)>{});
return *this;
}
public:
template <typename... RtDims,
typename = std::enable_if_t<(
traits::dynamic && sizeof...(RtDims) == sizeof...(Dims) && (std::is_integral_v<RtDims> && ...))>>
void set_dimensions(RtDims... dimensions) {
if constexpr (!valid_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...))
throw std::runtime_error("invalid dynamic tensor dimensions");
store_dims(std::make_index_sequence<sizeof...(Dims)>{}, dimensions...);
release();
m_items = new value_type[(dimensions * ... * 1)];
std::memset(m_items, 0, sizeof(*m_items) * (dimensions * ... * 1));
}
private:
template <typename... RtDims, std::size_t... Is>
constexpr bool valid_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
return (valid_dim<Is>(dimensions) && ...);
}
template <typename RtDim, std::size_t I>
constexpr bool valid_dim(RtDim dim) const {
return traits::dimensions[I] == dynamic_extent || traits::dimensions[I] == dim;
}
private:
template <typename... RtDims, std::size_t... Is>
constexpr void store_dims(std::index_sequence<Is...>, RtDims... dimensions) const {
return ((m_dimensions[Is] = dimensions) && ...);
}
private:
template <std::size_t... Is>
void dyn_alloc(std::index_sequence<Is...>) {
m_items = new value_type[(m_dimensions[Is] * ...)];
}
template <std::size_t... Is>
void dyn_copy(const value_type* src, std::index_sequence<Is...>) {
std::memcpy(m_items, src, sizeof(*m_items) * (m_dimensions[Is] * ... * 1));
}
void release() {
if constexpr (!traits::inline_storage) {
delete[] m_items;
}
}
private:
traits::storage_type m_items;
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_dimensions;
std::enable_if_t<traits::dynamic, std::size_t[sizeof...(Dims)]> m_strides;
};
template <typename T, std::size_t M, std::size_t N>
using matrix = tensor<T, M, N>;
} // namespace math
} // namespace cenet
#endif // CENET_MATH_TENSOR_HPP
+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
+86
View File
@@ -0,0 +1,86 @@
#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 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 = tensor_storage<tensor_type>::value_type;
using storage_type = 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
+2 -2
View File
@@ -37,7 +37,7 @@ private:
return std::get<I>(m_layers);
}
public:
using input_type = Input::inner;
using input_type = Input;
using output_type = output_layer_type::output_type;
public:
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; }
@@ -108,7 +108,7 @@ public:
public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) {
feed(input);
auto outputErr = get_output().get() - expected;
auto outputErr = get_output() - expected;
get_layer<0>().backward(input,
std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
BIN
View File
Binary file not shown.