refactor: finish refactor

Now it compiles AND generates (with CMake)!
This commit is contained in:
2026-11-19 16:28:05 +01:00
parent e19b6b499d
commit a9ba1874f1
5 changed files with 163 additions and 162 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
#include "cenet/layers/token.hpp"
#include "cenet/network.hpp"
#include "tokenizer.hpp"
@@ -7,7 +8,7 @@
static constexpr std::size_t VOCAB_SIZE = 2256;
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::tok2vec_layer<2256, 512>>;
using network_type = cenet::network<std::vector<std::uint32_t>, cenet::layers::tok2vec<2256, 512>>;
int main(void) {
tokenizer<VOCAB_SIZE> bpe;
+3 -1
View File
@@ -1,7 +1,9 @@
// The most useless header
// I am keeping it for the memes
#ifndef CENET_HPP
#define CENET_HPP
#include "layer.hpp" // IWYU pragma: export
#include "network.hpp" // IWYU pragma: export
#endif // CENET_HPP
-159
View File
@@ -1,159 +0,0 @@
#ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP
#include "math/tensor.hpp"
#include <array>
#include <cstddef>
#include <istream>
#include <ostream>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <vector>
namespace cenet {
namespace detail {
template <typename T>
struct is_tokens : std::false_type {};
template <std::size_t I>
struct is_tokens<std::array<std::uint32_t, I>> : std::true_type {};
template <>
struct is_tokens<std::vector<std::uint32_t>> : std::true_type {};
template <typename T>
static constexpr auto is_tokens_v = is_tokens<T>::value;
} // namespace detail
struct layer_info {
protected:
template <class NN, std::size_t I>
struct input_type_s {
using type = typename std::template tuple_element_t<I - 1, typename NN::layer_types>::output_type;
};
template <class NN>
struct input_type_s<NN, 0> {
using type = typename NN::input_type;
};
template <typename T>
using input_inner_t = typename T::inner;
};
template <std::size_t VocabSize, std::size_t EmbedDims>
class tok2vec_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tokens_v<input_type>);
static_assert(VocabSize > 0);
static_assert(EmbedDims > 0);
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
input_type input;
embedding_type embedding;
struct gradient final {
void reset() { embedding.view().fill(0); }
embedding_type embedding;
embedding_type momentum;
embedding_type variance;
std::size_t time = 0;
};
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(embedding.data()), sizeof(float) * embedding.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(embedding.data()), sizeof(float) * embedding.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
static std::random_device s_rd;
static std::mt19937 s_rng(s_rd());
auto distribution = dist;
const float scale = 1.0F / std::sqrt(static_cast<float>(EmbedDims));
for (std::size_t i = 0; i < embedding.size(); ++i) {
embedding.data()[i] = static_cast<float>(distribution(s_rng)) * scale;
}
}
auto feed(input_type&& input) {
output_type output;
output.set_dimensions(input.size(), EmbedDims);
for (std::size_t i = 0; i < input.size(); ++i) {
if (input[i] >= VocabSize) throw std::out_of_range("invalid token!");
output.view()[i].fill(embedding.view()[input[i]]);
}
this->input = std::move(input);
return output;
}
template <typename Error>
void backward(gradient& grad, Error prevErr) {
const auto errorShape = prevErr.shape();
if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) {
throw std::invalid_argument("unexpected embedding gradient shape");
}
for (std::size_t i = 0; i < input.size(); ++i) {
grad.embedding.view()[input[i]] += prevErr.view()[i];
}
}
void apply_grad(gradient& grad, double divisor, double rate) {
if (divisor <= 0.0) return;
++grad.time;
constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999;
constexpr double epsilon = 1e-8;
const double correction1 = 1.0 - std::pow(beta1, grad.time);
const double correction2 = 1.0 - std::pow(beta2, grad.time);
float* weights = embedding.data();
float* momentum = grad.momentum.data();
float* variance = grad.variance.data();
for (std::size_t i = 0; i < embedding.size(); ++i) {
const double avgGrad = static_cast<double>(grad.embedding.coeff(i)) / divisor;
grad.momentum.coeff(i) = static_cast<float>(beta1 * grad.momentum.coeff(i) + (1.0 - beta1) * avgGrad);
grad.variance.coeff(i) =
static_cast<float>(beta2 * grad.variance.coeff(i) + (1.0 - beta2) * avgGrad * avgGrad);
const double momentumCorrected = grad.momentum.coeff(i) / correction1;
const double varianceCorrected = grad.variance.coeff(i) / correction2;
embedding.coeff(i) -=
static_cast<float>(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon));
}
}
};
};
} // namespace cenet
#endif // CENET_LAYER_HPP
+1 -1
View File
@@ -5,6 +5,7 @@
#ifndef CENET_LAYERS_DENSE_HPP
#define CENET_LAYERS_DENSE_HPP
#include "../math/tensor.hpp"
#include "../math/tensor_fwd.hpp"
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
@@ -16,7 +17,6 @@
namespace cenet {
namespace layers {
// TODO: redesign the layer interface after porting the old layers
template <std::size_t Features>
struct dense final : public layer_tag {
static constexpr auto retain = retain::Input;
+157
View File
@@ -0,0 +1,157 @@
#ifndef CENET_LAYERS_TOKEN_HPP
#define CENET_LAYERS_TOKEN_HPP
#include "../math/tensor.hpp"
#include "../math/tensor_fwd.hpp"
#include "./layer_fwd.hpp"
#include "./layer_traits.hpp"
#include "./retained.hpp"
#include <array>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <random>
#include <vector>
namespace cenet {
namespace layers {
namespace detail {
template <typename T>
struct is_tokens : std::false_type {};
template <std::size_t I>
struct is_tokens<std::array<std::uint32_t, I>> : std::true_type {};
template <>
struct is_tokens<std::vector<std::uint32_t>> : std::true_type {};
template <typename T>
static constexpr auto is_tokens_v = is_tokens<T>::value;
} // namespace detail
template <std::size_t VocabSize, std::size_t EmbedDims>
struct tok2vec final : public layer_tag {
static constexpr auto retain = retain::Input;
template <class N, std::size_t I>
struct data final {
using traits = typename detail::layer_traits<network_layer<tok2vec, N, I>>;
using input_type = typename traits::input_type;
static_assert(detail::is_tokens_v<input_type>);
static_assert(VocabSize > 0);
static_assert(EmbedDims > 0);
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
embedding_type embedding;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(embedding.data()), sizeof(float) * embedding.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(embedding.data()), sizeof(float) * embedding.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
static std::random_device s_rd;
static std::mt19937 s_rng(s_rd());
auto distribution = dist;
const float scale = 1.0F / std::sqrt(static_cast<float>(EmbedDims));
for (std::size_t i = 0; i < embedding.size(); ++i) {
embedding.data()[i] = static_cast<float>(distribution(s_rng)) * scale;
}
}
auto feed(const input_type& input) {
output_type output;
output.set_dimensions(input.size(), EmbedDims);
for (std::size_t i = 0; i < input.size(); ++i) {
if (input[i] >= VocabSize) throw std::out_of_range("invalid token!");
output.view()[i].fill(embedding.view()[input[i]]);
}
return output;
}
};
template <class N, std::size_t I>
struct grad final {
using traits = typename detail::layer_traits<network_layer<tok2vec, N, I>>;
using input_type = typename traits::input_type;
static_assert(detail::is_tokens_v<input_type>);
static_assert(VocabSize > 0);
static_assert(EmbedDims > 0);
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
embedding_type embedding;
embedding_type momentum;
embedding_type variance;
std::size_t time = 0;
void reset() { embedding.view().fill(0); }
template <typename Error>
void backward(const data<N, I>& data, const input_type& retained, Error prevErr) {
const auto errorShape = prevErr.shape();
if (errorShape.template get<0>() != retained.size() || errorShape.template get<1>() != EmbedDims) {
throw std::invalid_argument("unexpected embedding gradient shape");
}
for (std::size_t i = 0; i < retained.size(); ++i) {
embedding.view()[retained[i]] += prevErr.view()[i];
}
}
void apply(data<N, I>& data, double divisor, double rate) {
if (divisor <= 0.0) return;
++time;
constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999;
constexpr double epsilon = 1e-8;
const double correction1 = 1.0 - std::pow(beta1, time);
const double correction2 = 1.0 - std::pow(beta2, time);
float* weightsP = data.embedding.data();
float* momentumM = momentum.data();
float* varianceP = variance.data();
for (std::size_t i = 0; i < embedding.size(); ++i) {
const double avgGrad = static_cast<double>(embedding.coeff(i)) / divisor;
momentum.coeff(i) = static_cast<float>((beta1 * momentum.coeff(i)) + ((1.0 - beta1) * avgGrad));
variance.coeff(i) =
static_cast<float>((beta2 * variance.coeff(i)) + ((1.0 - beta2) * avgGrad * avgGrad));
const double momentumCorrected = momentum.coeff(i) / correction1;
const double varianceCorrected = variance.coeff(i) / correction2;
data.embedding.coeff(i) -=
static_cast<float>(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon));
}
}
};
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_TOKEN_HPP