diff --git a/CMakeLists.txt b/CMakeLists.txt index e73db2d..5055205 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,12 +5,8 @@ project(cenet CXX) 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/layer.hpp - include/cenet/network.hpp - include/cenet/cenet.hpp) +file(GLOB_RECURSE CENET_HEADERS "include/*.hpp") +add_library(cenet INTERFACE ${CENET_HEADERS}) target_include_directories(cenet INTERFACE include/) add_executable(xor example/xor.cpp) diff --git a/example/xor.cpp b/example/xor.cpp index a5bf5ee..be5ab53 100644 --- a/example/xor.cpp +++ b/example/xor.cpp @@ -11,12 +11,13 @@ static std::uniform_real_distribution<> dist(-1, 1); int main(void) { - static constexpr float s_trainData[4] = { - 0, // 0 ^ 0 - 1, // 1 ^ 0 - 1, // 0 ^ 1 - 0, // 1 ^ 1 - }; + static cenet::math::matrix, 1, 1> s_trainData[4] = {}; + for (std::size_t i = 0; i < 4; ++i) { + const bool x0 = (i & 1U) != 0; + const bool x1 = (i & 2U) != 0; + + s_trainData[i].view().fill(x0 != x1 ? 1.0F : 0.0F); + } // network net; using network_type = cenet::network, 1, 2>, @@ -26,6 +27,8 @@ int main(void) { cenet::layers::sigmoid>; network_type xorNet; + network_type::learning_state learningState; + static constexpr const char* NETWORK_PATH = "./xor.nn"; std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary); @@ -38,22 +41,21 @@ int main(void) { std::size_t gen = 0; - network_type::learning_state state; while (gen <= 10'000'000) { - state.reset(); + learningState.reset(); for (std::size_t i = 0; i < 4; ++i) { cenet::math::matrix, 1, 2> xs; xs.coeff(0) = static_cast(i & 1); xs.coeff(1) = static_cast(i > 1); - auto output = std::move(xorNet.feed(xs)); + auto output = xorNet.feed(xs, learningState); auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output); - xorNet.backward(loss, state); + learningState.backward(xorNet, loss); } - xorNet.apply(state, learning_late); + xorNet.apply(learningState, learning_late); double acc = 0.0; @@ -63,7 +65,7 @@ int main(void) { xs.coeff(1) = static_cast(i > 1); float yHat = xorNet.feed(xs).coeff(0); - float error = yHat - s_trainData[i]; + float error = yHat - s_trainData[i].coeff(0); if ((gen % 1000) == 0) { std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n"; diff --git a/include/cenet/layers/dense.hpp b/include/cenet/layers/dense.hpp index 77ce3e8..0dbd6e6 100644 --- a/include/cenet/layers/dense.hpp +++ b/include/cenet/layers/dense.hpp @@ -6,23 +6,23 @@ #define CENET_LAYERS_DENSE_HPP #include "../math/tensor_fwd.hpp" -#include "../network.hpp" #include "./layer_fwd.hpp" #include "./layer_traits.hpp" +#include "./retained.hpp" #include +#include namespace cenet { namespace layers { // TODO: redesign the layer interface after porting the old layers template -class dense final : public layer_tag { - template - friend class ::cenet::network; -private: +struct dense final : public layer_tag { + static constexpr auto retain = retain::Input; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; @@ -34,31 +34,9 @@ private: using weights_type = math::matrix, input_cols, Features>; using biases_type = math::matrix, 1, Features>; - struct gradient final { - using parent_type = inner; - - weights_type weights; - biases_type biases; - - // TODO: move Adam into optimizer state - weights_type momentumWeights; - biases_type momentumBiases; - weights_type varianceWeights; - biases_type varianceBiases; - - std::size_t time = 0; - - void reset() { - weights.view().fill(); - biases.view().fill(); - } - }; - weights_type weights; biases_type biases; - typename input_type::template with_storage retained; - void dump(std::ostream& os) const { os.write(reinterpret_cast(weights.data()), sizeof(value_type) * weights.size()); os.write(reinterpret_cast(biases.data()), sizeof(value_type) * biases.size()); @@ -79,20 +57,49 @@ private: template auto feed(Fwd&& fwd) { - retained = std::forward(fwd); - return retained.matmul(weights) + biases; + return std::forward(fwd).matmul(weights) + biases; + } + }; + + template + struct grad final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + using value_type = typename input_type::value_type; + using output_type = math::matrix; + + static constexpr auto input_cols = input_type::shape_type::template sget<1>(); + + using weights_type = math::matrix, input_cols, Features>; + using biases_type = math::matrix, 1, Features>; + + weights_type weights; + biases_type biases; + + // TODO: move Adam into optimizer state + weights_type momentumWeights; + biases_type momentumBiases; + weights_type varianceWeights; + biases_type varianceBiases; + + std::size_t time = 0; + + void reset() { + weights.view().fill(); + biases.view().fill(); } template - auto backward(gradient& grad, Error&& prevErr) { - grad.weights += retained.transpose().matmul(prevErr); - grad.biases += prevErr; + auto backward(const data& data, const input_type& retained, Error&& prevErr) { + weights += retained.transpose().matmul(prevErr); + biases += prevErr; - return std::forward(prevErr).matmul(weights.transpose()); + return std::forward(prevErr).matmul(data.weights.transpose()); } - void apply_grad(gradient& grad, double divisor, double rate) { - ++grad.time; + void apply(data& data, double divisor, double rate) { + ++time; constexpr double beta1 = 0.9; constexpr double beta2 = 0.999; @@ -100,53 +107,44 @@ private: for (std::size_t row = 0; row < input_cols; ++row) { for (std::size_t col = 0; col < Features; ++col) { - auto avgGrad = grad.weights[row][col] / divisor; + auto avgGrad = 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)); + momentumWeights[row][col] = (beta1 * momentumWeights[row][col]) + ((1.0 - beta1) * avgGrad); + varianceWeights[row][col] = + (beta2 * varianceWeights[row][col]) + ((1.0 - beta2) * (avgGrad * avgGrad)); - 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)); + auto momentumCorrected = momentumWeights[row][col] / (1.0 - std::pow(beta1, time)); + auto varianceCorrected = varianceWeights[row][col] / (1.0 - std::pow(beta2, time)); - weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); + data.weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); } } for (std::size_t col = 0; col < Features; ++col) { - double avgGrad = grad.biases[0][col] / divisor; + double avgGrad = biases[0][col] / divisor; - 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)); + momentumBiases[0][col] = (beta1 * momentumBiases[0][col]) + ((1.0 - beta1) * avgGrad); + varianceBiases[0][col] = (beta2 * varianceBiases[0][col]) + ((1.0 - beta2) * (avgGrad * avgGrad)); - 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)); + auto momentumCorrected = momentumBiases[0][col] / (1.0 - std::pow(beta1, time)); + auto varianceCorrected = varianceBiases[0][col] / (1.0 - std::pow(beta2, time)); - biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); + data.biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); } } }; }; -class sigmoid final : public layer_tag { - template - friend class ::cenet::network; -private: +struct sigmoid final : public layer_tag { + static constexpr auto retain = retain::Output; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; using output_type = input_type; - typename output_type::template with_storage retained; - - struct gradient { - void reset() {} - }; - void dump(std::ostream& os) const {} void load(std::istream& is) {} @@ -156,36 +154,39 @@ private: template auto feed(Fwd&& fwd) { - return retained = std::forward(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); }); + return std::forward(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); }); } + }; + + template + struct grad final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + using output_type = input_type; + + void reset() {} template - auto backward(gradient& grad, Error&& prevErr) const { + auto backward(const data&, const output_type& retained, Error&& prevErr) const { return std::forward(prevErr) * retained * (static_cast(1) - retained); } - void apply_grad(gradient&, double, double) {} + void apply(data&, double, double) {} }; }; -class relu final : public layer_tag { - template - friend class ::cenet::network; -private: +struct relu final : public layer_tag { + static constexpr auto retain = retain::Input; + template - struct inner final { + struct data final { using traits = typename detail::layer_traits>; using input_type = typename traits::input_type; using output_type = input_type; - typename input_type::template with_storage retained; - - struct gradient { - void reset() {} - }; - void dump(std::ostream& os) const {} void load(std::istream& is) {} @@ -195,17 +196,25 @@ private: template auto feed(Fwd&& fwd) { - retained = std::forward(fwd); - return retained.apply([](auto in) { return in > 0.0 ? in : 0.0; }); + return std::forward(fwd).apply([](auto in) { return in > 0.0 ? in : 0.0; }); } + }; + + template + struct grad final { + using traits = typename detail::layer_traits>; + + using input_type = typename traits::input_type; + + void reset() {} template - auto backward(gradient& grad, Error&& prevErr) const { + auto backward(const data&, const input_type& retained, Error&& prevErr) const { return std::forward(prevErr).apply(retained, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); } - void apply_grad(gradient&, double, double) {} + void apply(data&, double, double) {} }; }; diff --git a/include/cenet/layers/layer_traits.hpp b/include/cenet/layers/layer_traits.hpp index 3db5862..bc9fa80 100644 --- a/include/cenet/layers/layer_traits.hpp +++ b/include/cenet/layers/layer_traits.hpp @@ -1,7 +1,9 @@ #ifndef CENET_LAYERS_LAYER_TRAITS_HPP #define CENET_LAYERS_LAYER_TRAITS_HPP -#include "layer_fwd.hpp" +#include "../network_fwd.hpp" +#include "./layer_fwd.hpp" +#include "cenet/network_traits.hpp" #include #include @@ -20,13 +22,17 @@ template static constexpr auto is_layer_v = is_layer::value; template -struct layer_input { - using type = typename N::template layer::output_type; +struct layer_input {}; + +template +struct layer_input, I> { + using type = typename ::cenet::detail:: + layer_for_t<::cenet::detail::layer_at_t>, network, I - 1>::output_type; }; -template -struct layer_input { - using type = typename N::input_type; +template +struct layer_input, 0> { + using type = In; }; template diff --git a/include/cenet/layers/retained.hpp b/include/cenet/layers/retained.hpp new file mode 100644 index 0000000..fb32261 --- /dev/null +++ b/include/cenet/layers/retained.hpp @@ -0,0 +1,16 @@ +#ifndef CENET_LAYERS_RETAINED_HPP +#define CENET_LAYERS_RETAINED_HPP + +namespace cenet { +namespace layers { + +enum class retain { + None, + Input, + Output, +}; + +} // namespace layers +} // namespace cenet + +#endif // CENET_LAYERS_RETAINED_HPP diff --git a/include/cenet/math/expr.hpp b/include/cenet/math/expr.hpp index 06591a1..a14abbf 100644 --- a/include/cenet/math/expr.hpp +++ b/include/cenet/math/expr.hpp @@ -1,6 +1,7 @@ #ifndef CENET_MATH_EXPR_HPP #define CENET_MATH_EXPR_HPP +#include "cenet/math/tensor_traits.hpp" #include "ops.hpp" #include "type_traits.hpp" @@ -28,31 +29,63 @@ struct ops_provider { return { self(), std::forward(rhs) }; } + template + binary_expression matmul(R&& rhs) const { + if (!ops::matmul::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch"); + return { self(), std::forward(rhs) }; + } + template unary_expression> apply(Func&& func) { if (!ops::apply::compatible(self())) throw std::runtime_error("tensor shape mismatch"); return { self(), std::forward(func) }; } + template + unary_expression> apply(Func&& func) const { + if (!ops::apply::compatible(self())) throw std::runtime_error("tensor shape mismatch"); + return { self(), std::forward(func) }; + } + template binary_expression> apply(R&& rhs, Func&& func) { if (!ops::apply::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch"); return { self(), std::forward(rhs), std::forward(func) }; } + template + binary_expression> apply(R&& rhs, Func&& func) const { + if (!ops::apply::compatible(self(), rhs)) throw std::runtime_error("tensor shape mismatch"); + return { self(), std::forward(rhs), std::forward(func) }; + } + unary_expression transpose() { if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch"); return { self() }; } + unary_expression transpose() const { + if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch"); + return { self() }; + } + template unary_expression> reshape() { if (!ops::reshape::compatible(self())) throw std::runtime_error("tensor shape mismatch"); return { self() }; } + + template + unary_expression> reshape() const { + if (!ops::reshape::compatible(self())) throw std::runtime_error("tensor shape mismatch"); + return { self() }; + } private: decltype(auto) self() & { return reinterpret_cast(*this); } decltype(auto) self() && { return reinterpret_cast(*this); } + + decltype(auto) self() const& { return reinterpret_cast(*this); } + decltype(auto) self() const&& { return reinterpret_cast(*this); } }; namespace detail { @@ -152,6 +185,17 @@ binary_expression operator/(L&& lhs, R&& rhs) { return { std::forward(lhs), std::forward(rhs) }; } +template +constexpr decltype(auto) eval(T&& fwd) { + if constexpr (detail::is_expression_v) { + auto tensor = tensor_from_shape()))>(fwd.shape()); + tensor = std::forward(fwd); + return tensor; + } else { + return std::forward(fwd); + } +} + } // namespace math } // namespace cenet diff --git a/include/cenet/math/tensor.hpp b/include/cenet/math/tensor.hpp index 0f40b52..a6417e2 100644 --- a/include/cenet/math/tensor.hpp +++ b/include/cenet/math/tensor.hpp @@ -111,11 +111,9 @@ public: tensor& operator=(E&& exprFwd) { if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch"); - if constexpr (!traits::inline_storage) { - if constexpr (traits::dynamic) { + if constexpr (traits::dynamic) { + if (m_shape != exprFwd.shape()) { set_dimensions(exprFwd.shape()); - } else { - m_items = new value_type[traits::size]; } } diff --git a/include/cenet/math/tensor_traits.hpp b/include/cenet/math/tensor_traits.hpp index 88335f1..0cabb75 100644 --- a/include/cenet/math/tensor_traits.hpp +++ b/include/cenet/math/tensor_traits.hpp @@ -1,6 +1,8 @@ #ifndef CENET_MATH_TENSOR_TRAITS_HPP #define CENET_MATH_TENSOR_TRAITS_HPP +#include "cenet/math/tensor_shape.hpp" +#include "cenet/math/type_traits.hpp" #include "tensor_fwd.hpp" #include @@ -90,6 +92,19 @@ struct tensor_with_storage { using type = tensor>, Dims...>; }; +template +struct tensor_from_shape {}; + +template +struct tensor_from_shape> { + using type = tensor; +}; + +template +struct tensor_from_shape> { + using type = tensor; +}; + } // namespace detail template @@ -115,6 +130,15 @@ struct tensor_traits> { using with_storage_t = typename detail::tensor_with_storage::template type; }; +template +constexpr decltype(auto) tensor_from_shape(const Shape& shape) { + typename detail::tensor_from_shape>::type tensor; + if constexpr (!detail::is_static_shape_v) { + tensor.set_dimensions(shape); + } + return tensor; +} + } // namespace math } // namespace cenet diff --git a/include/cenet/network.hpp b/include/cenet/network.hpp index c16a794..5b4e04f 100644 --- a/include/cenet/network.hpp +++ b/include/cenet/network.hpp @@ -1,6 +1,10 @@ #ifndef CENET_NETWORK_HPP #define CENET_NETWORK_HPP +#include "./network_traits.hpp" +#include "cenet/layers/retained.hpp" +#include "cenet/math/expr.hpp" + #include #include #include @@ -12,36 +16,11 @@ namespace cenet { template class network { friend class layer_info; -private: - template - struct layer_types_gen {}; - - template - struct layer_types_gen> { - using type = std::tuple...>; - }; - - using layer_types = typename layer_types_gen>::type; - using output_layer_type = std::tuple_element_t; - - template - using layer_input_t = typename std::tuple_element_t::input_type; -private: - template - auto& get_layer() { - return std::get(m_layers); - } - - template - const auto& get_layer() const { - return std::get(m_layers); - } public: - template - using layer = std::tuple_element_t; -public: - using input_type = Input; - using output_type = typename output_layer_type::output_type; + using traits = network_traits; + + using input_type = typename traits::input_type; + using output_type = typename traits::output_type; public: const output_type& get_output() const { return m_output; } public: @@ -53,14 +32,14 @@ public: private: template void dump_network(std::ostream& os, std::index_sequence) const { - (get_layer().dump(os), ...); + (at().dump(os), ...); } public: void load_network(std::istream& is) { load_network(is, std::make_index_sequence{}); } private: template void load_network(std::istream& is, std::index_sequence) { - (get_layer().load(is), ...); + (at().load(is), ...); } public: template @@ -70,7 +49,7 @@ public: private: template void fill_random(const Dist& dist, std::index_sequence) { - (get_layer().fill_random(dist), ...); + (at().fill_random(dist), ...); } public: output_type feed(input_type input) { return feed_impl<0>(std::move(input)); } @@ -80,76 +59,151 @@ private: if constexpr (I == sizeof...(Layers)) { return std::forward(current); } else { - return feed_impl(get_layer().feed(std::forward(current))); + return feed_impl(at().feed(std::forward(current))); } } +private: + // TODO: pass in the optimizer + struct layers_grad_gen { + template + struct impl { + using type = decltype(std::tuple_cat(std::tuple>{}, + std::declval::type>())); + }; + + template + struct impl { + using type = std::tuple>; + }; + + using type = typename impl<0, Layers...>::type; + }; public: struct learning_state final { + friend class network; + void reset() { m_count = 0; reset(std::make_index_sequence{}); } - template > - decltype(auto) get() { + template + decltype(auto) at() { return std::get(m_layers); } - void increment() { ++m_count; } - auto count() const { return m_count; } + + template + void backward(const network& network, const Loss& loss) { + at<0>().backward(network.template at<0>(), + retained_for<0>(), + backward_chain(network, loss.gradient)); + ++m_count; + } private: template void reset(std::index_sequence) { (std::get(m_layers).reset(), ...); } private: - template - struct gen {}; + template + auto backward_chain(const network& network, Error&& error) { + if constexpr (I != 0) { + return backward_chain(network, + at().backward(network.template at(), retained_for(), std::forward(error))); + } else { + return std::forward(error); + } + } - template - struct gen> { - using type = std::tuple::gradient...>; - }; + struct empty {}; + + template + decltype(auto) retained_for() const { + if constexpr (detail::layer_retains_v) { + return std::get(m_retained); + } else if constexpr (detail::layer_retains_v) { + return std::get(m_retained); + } else { + return empty{}; + } + } private: std::size_t m_count = 0; - typename gen>::type m_layers; + detail::network_retained_t m_retained; // TODO: move retained state to its own struct + typename layers_grad_gen::type m_layers; }; public: - template - void backward(const Loss& loss, LState& state) { - get_layer<0>().backward(state.template get<0>(), backward_chain(state, loss.gradient)); - state.increment(); - } + output_type feed(input_type input, learning_state& state) { return feed_impl<0>(std::move(input), state); } private: - template - auto backward_chain(LState& state, ErrorType error) { - if constexpr (I != 0) { - auto next = get_layer().backward(state.template get(), error); - return backward_chain(state, next); + template + auto feed_impl(Current&& current, learning_state& state) { + if constexpr (I == sizeof...(Layers)) { + return std::forward(current); } else { - return error; + if constexpr (detail::layer_retains_v) { + std::get(state.m_retained) = current; + } + + auto next = at().feed(std::forward(current)); + + if constexpr (detail::layer_retains_v) { + std::get(state.m_retained) = next; + } + + return feed_impl(std::move(next), state); } } public: - void apply(learning_state& state, double rate) { - apply(state, rate, std::make_index_sequence{}); + void apply(learning_state& state, double learningRate) { + apply(state, learningRate, std::make_index_sequence{}); } private: template void apply(learning_state& state, double rate, std::index_sequence) { - (std::get(m_layers).apply_grad(state.template get(), state.count(), rate), ...); + (std::get(state.m_layers).apply(at(), state.count(), rate), ...); } public: - void train(const input_type& input, const output_type& expected, double learningRate) { - learning_state state; - backward(input, expected, state); - apply(state, learningRate); + template + decltype(auto) at() { + return std::get(m_layers); + } + + template + decltype(auto) at() const { + return std::get(m_layers); } private: - layer_types m_layers; - output_type m_output; + struct layers_data_gen { + template + struct impl { + using type = decltype(std::tuple_cat(std::tuple>{}, + std::declval::type>())); + }; + + template + struct impl { + using type = std::tuple>; + }; + + template + struct at : at {}; + + template + struct at<0, J, LF, LR...> { + using type = typename LF::template data; + }; + + using type = typename impl<0, Layers...>::type; + }; +public: + template + using layer = typename layers_data_gen::template at::type; +private: + typename layers_data_gen::type m_layers; + output_type m_output; }; } // namespace cenet diff --git a/include/cenet/network_fwd.hpp b/include/cenet/network_fwd.hpp new file mode 100644 index 0000000..d1e98ae --- /dev/null +++ b/include/cenet/network_fwd.hpp @@ -0,0 +1,11 @@ +#ifndef CENET_NETWORK_FWD_HPP +#define CENET_NETWORK_FWD_HPP + +namespace cenet { + +template +class network; + +} + +#endif // CENET_NETWORK_FWD_HPP diff --git a/include/cenet/network_traits.hpp b/include/cenet/network_traits.hpp new file mode 100644 index 0000000..8468f2e --- /dev/null +++ b/include/cenet/network_traits.hpp @@ -0,0 +1,102 @@ +#ifndef CENET_NETWORK_TRAITS_HPP +#define CENET_NETWORK_TRAITS_HPP + +#include "./layers/retained.hpp" +#include "./network_fwd.hpp" + +#include +#include +#include +#include + +namespace cenet { + +namespace detail { + +template +struct layer_at {}; + +template +struct layer_at> { + static_assert(At <= sizeof...(LR)); + using type = typename layer_at>::type; +}; + +template +struct layer_at<0, network> { + using type = LF; +}; + +template +using layer_at_t = typename layer_at::type; + +template +using layer_for_t = typename L::template data; + +template +struct layer_retains : std::conditional_t::retain == Retain, std::true_type, std::false_type> {}; + +template +inline constexpr auto layer_retains_v = layer_retains::value; + +template +struct network_retained {}; + +template +struct network_retained> { +private: + using network_type = network; + + struct empty {}; + + template + static constexpr auto generate(std::index_sequence) { + if constexpr (layer_retains_v) { + return std::tuple_cat(std::tuple{}, generate_layer()...); + } else { + return std::tuple_cat(std::tuple{}, generate_layer()...); + } + } + + template + static constexpr auto generate_layer() { + if constexpr (I + 1 >= sizeof...(Ls)) { // Last layer + if constexpr (layer_retains_v) { + return std::tuple, network_type, I>::output_type>{}; + } else { + return std::tuple{}; + } + } else { + if constexpr (layer_retains_v || + layer_retains_v) { + return std::tuple, network_type, I>::output_type>{}; + } else { + return std::tuple{}; + } + } + } +public: + using type = decltype(generate(std::make_index_sequence{})); +}; + +template +using network_retained_t = typename network_retained::type; + +} // namespace detail + +template +struct network_traits {}; + +template +struct network_traits> { + using network_type = network; + + using input_type = I; + using output_layer = detail::layer_at_t; + using output_type = + typename detail::layer_for_t, sizeof...(Layers) - 1>::output_type; +}; + +} // namespace cenet + +#endif // CENET_NETWORK_TRAITS_HPP diff --git a/mnist-conv.nn b/mnist-conv.nn index b76347f..dc1bbf0 100644 Binary files a/mnist-conv.nn and b/mnist-conv.nn differ diff --git a/test/tensor.cpp b/test/tensor.cpp new file mode 100644 index 0000000..a8b4af8 --- /dev/null +++ b/test/tensor.cpp @@ -0,0 +1,126 @@ +// TODO: write actual tests + +#include +#include +#include +#include +#include +#include + +using cenet::math::dynamic_extent; + +// Whatever +TEST(Tensor, View) { + cenet::math::tensor tensor; + + auto view = tensor.view()[1][1]; +} + +TEST(Tensor, Ops) { + constexpr float lhsArray[2 * 3] = { 1, 2, 3, 4, 5, 6 }; + cenet::math::tensor lhs; + lhs.set_dimensions(2, 3); + lhs.view().fill(lhsArray); + + constexpr float rhsArray[2 * 3] = { 6, 5, 4, 3, 2, 1 }; + cenet::math::tensor, 2, 3> rhs; + rhs.view().fill(rhsArray); + + constexpr float resultArray[2 * 3] = { 6 * 1, 6 * 2, 6 * 3, 6 * 4, 6 * 5, 6 * 6 }; + cenet::math::tensor, 2, 3> result = lhs + rhs - 1; + result *= lhs; + + for (std::size_t i = 0; i < result.size(); ++i) { + EXPECT_EQ(result.coeff(i), resultArray[i]); + } +} + +TEST(Tensor, MatMul) { + constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 }; + constexpr float rhsArray[2 * 2] = { 5, 6, 7, 8 }; + + cenet::math::tensor, 2, 2> lhs; + cenet::math::tensor, 2, 2> rhs; + + lhs.view().fill(lhsArray); + rhs.view().fill(rhsArray); + + constexpr float expArray[2 * 2] = { (1 * 5) + (2 * 7), (1 * 6) + (2 * 8), (3 * 5) + (4 * 7), (3 * 6) + (4 * 8) }; + + cenet::math::tensor, 2, 2> result = lhs.matmul(rhs); + for (std::size_t i = 0; i < result.size(); ++i) { + EXPECT_EQ(result.coeff(i), expArray[i]); + } +} + +// MatMul was so good they made a sequel +TEST(Tensor, MatMul2) { + constexpr float lhsArray[3 * 2] = { 1, 2, 5, 6, 7, 8 }; + constexpr float rhsArray[2 * 1] = { 3, 4 }; + + cenet::math::tensor, 3, 2> lhs; + cenet::math::tensor, 2, 1> rhs; + + lhs.view().fill(lhsArray); + rhs.view().fill(rhsArray); + + constexpr float expArray[3 * 1] = { 11, 39, 53 }; + + cenet::math::tensor, 3, 1> result = lhs.matmul(rhs); + for (std::size_t i = 0; i < result.size(); ++i) { + EXPECT_EQ(result.coeff(i), expArray[i]); + } +} + +TEST(Tensor, Apply) { + constexpr float values[2 * 2] = { 1, 2, 3, 4 }; + cenet::math::tensor, 2, 2> tensor; + tensor.view().fill(values); + + constexpr float expected[2 * 2] = { 1, 4, 9, 16 }; + + tensor = tensor.apply([](auto val) { return val * val; }); + for (std::size_t i = 0; i < tensor.size(); ++i) { + EXPECT_EQ(tensor.coeff(i), expected[i]); + } +} + +TEST(Tensor, Apply2) { + constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 }; + constexpr float rhsArray[2 * 2] = { 4, 3, 2, 1 }; + + cenet::math::tensor, 2, 2> lhs; + cenet::math::tensor, 2, 2> rhs; + + lhs.view().fill(lhsArray); + rhs.view().fill(rhsArray); + + constexpr float expArray[2 * 2] = { 4, 3, 3, 4 }; + + cenet::math::tensor, 2, 2> result = + lhs.apply(rhs, [](auto x1, auto x2) { return std::max(x1, x2); }); + for (std::size_t i = 0; i < result.size(); ++i) { + EXPECT_EQ(result.coeff(i), expArray[i]); + } +} + +TEST(Tensor, Offsets) { + cenet::math::tensor tensor; + + for (std::size_t i = 0; i < tensor.size(); ++i) + tensor.coeff(i) = static_cast(i); + + EXPECT_EQ(tensor[1][0][0], 12); + EXPECT_EQ(tensor[1][2][0], 20); + EXPECT_EQ(tensor[1][2][3], 23); +} + +TEST(Tensor, Offsets2) { + using shape_type = cenet::math::static_shape<2, 3, 4>; + + shape_type shape; + + EXPECT_EQ(shape.calculate_offset(std::make_tuple(1)), 12); + EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2)), 20); + EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2, 3)), 23); +}