From a9ba1874f151b59ba7106105fccac07f91e56451 Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Thu, 19 Nov 2026 16:28:05 +0100 Subject: [PATCH] refactor: finish refactor Now it compiles AND generates (with CMake)! --- example/gpt.cpp | 3 +- include/cenet/cenet.hpp | 4 +- include/cenet/layer.hpp | 159 --------------------------------- include/cenet/layers/dense.hpp | 2 +- include/cenet/layers/token.hpp | 157 ++++++++++++++++++++++++++++++++ 5 files changed, 163 insertions(+), 162 deletions(-) delete mode 100644 include/cenet/layer.hpp create mode 100644 include/cenet/layers/token.hpp diff --git a/example/gpt.cpp b/example/gpt.cpp index 9adcbef..dd7d36a 100644 --- a/example/gpt.cpp +++ b/example/gpt.cpp @@ -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, cenet::tok2vec_layer<2256, 512>>; +using network_type = cenet::network, cenet::layers::tok2vec<2256, 512>>; int main(void) { tokenizer bpe; diff --git a/include/cenet/cenet.hpp b/include/cenet/cenet.hpp index 091246d..729528d 100644 --- a/include/cenet/cenet.hpp +++ b/include/cenet/cenet.hpp @@ -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 diff --git a/include/cenet/layer.hpp b/include/cenet/layer.hpp deleted file mode 100644 index d00e510..0000000 --- a/include/cenet/layer.hpp +++ /dev/null @@ -1,159 +0,0 @@ -#ifndef CENET_LAYER_HPP -#define CENET_LAYER_HPP - -#include "math/tensor.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cenet { - -namespace detail { - -template -struct is_tokens : std::false_type {}; - -template -struct is_tokens> : std::true_type {}; - -template <> -struct is_tokens> : std::true_type {}; - -template -static constexpr auto is_tokens_v = is_tokens::value; - -} // namespace detail - -struct layer_info { -protected: - template - struct input_type_s { - using type = typename std::template tuple_element_t::output_type; - }; - - template - struct input_type_s { - using type = typename NN::input_type; - }; - - template - using input_inner_t = typename T::inner; -}; - -template -class tok2vec_layer final : public layer_info { - template - friend class network; -private: - template - struct inner final { - using input_type = typename input_type_s::type; - static_assert(detail::is_tokens_v); - - static_assert(VocabSize > 0); - static_assert(EmbedDims > 0); - - using output_type = math::matrix; - using embedding_type = math::matrix; - - 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(embedding.data()), sizeof(float) * embedding.size()); - } - - void load(std::istream& is) { - is.read(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); - } - - template - 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(EmbedDims)); - - for (std::size_t i = 0; i < embedding.size(); ++i) { - embedding.data()[i] = static_cast(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 - 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(grad.embedding.coeff(i)) / divisor; - - grad.momentum.coeff(i) = static_cast(beta1 * grad.momentum.coeff(i) + (1.0 - beta1) * avgGrad); - grad.variance.coeff(i) = - static_cast(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(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon)); - } - } - }; -}; - -} // namespace cenet - -#endif // CENET_LAYER_HPP diff --git a/include/cenet/layers/dense.hpp b/include/cenet/layers/dense.hpp index 0dbd6e6..41578c1 100644 --- a/include/cenet/layers/dense.hpp +++ b/include/cenet/layers/dense.hpp @@ -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 struct dense final : public layer_tag { static constexpr auto retain = retain::Input; diff --git a/include/cenet/layers/token.hpp b/include/cenet/layers/token.hpp new file mode 100644 index 0000000..2825529 --- /dev/null +++ b/include/cenet/layers/token.hpp @@ -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 +#include +#include +#include +#include +#include + +namespace cenet { +namespace layers { + +namespace detail { + +template +struct is_tokens : std::false_type {}; + +template +struct is_tokens> : std::true_type {}; + +template <> +struct is_tokens> : std::true_type {}; + +template +static constexpr auto is_tokens_v = is_tokens::value; + +} // namespace detail + +template +struct tok2vec final : public layer_tag { + static constexpr auto retain = retain::Input; + + template + struct data final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + static_assert(detail::is_tokens_v); + + static_assert(VocabSize > 0); + static_assert(EmbedDims > 0); + + using output_type = math::matrix; + using embedding_type = math::matrix; + + embedding_type embedding; + + void dump(std::ostream& os) const { + os.write(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); + } + + void load(std::istream& is) { + is.read(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); + } + + template + 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(EmbedDims)); + + for (std::size_t i = 0; i < embedding.size(); ++i) { + embedding.data()[i] = static_cast(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 + struct grad final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + static_assert(detail::is_tokens_v); + + static_assert(VocabSize > 0); + static_assert(EmbedDims > 0); + + using output_type = math::matrix; + using embedding_type = math::matrix; + + embedding_type embedding; + embedding_type momentum; + embedding_type variance; + + std::size_t time = 0; + + void reset() { embedding.view().fill(0); } + + template + void backward(const data& 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& 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(embedding.coeff(i)) / divisor; + + momentum.coeff(i) = static_cast((beta1 * momentum.coeff(i)) + ((1.0 - beta1) * avgGrad)); + variance.coeff(i) = + static_cast((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(rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon)); + } + } + }; +}; + +} // namespace layers +} // namespace cenet + +#endif // CENET_LAYERS_TOKEN_HPP