diff --git a/example/mnist.cpp b/example/mnist.cpp index 0bf9b29..0ec54d6 100644 --- a/example/mnist.cpp +++ b/example/mnist.cpp @@ -1,3 +1,5 @@ +#include "cenet/loss/mse.hpp" + #include #include #include @@ -140,8 +142,11 @@ int main(void) { for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) { if (i > 0) state->reset(); - for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) - mnistNet->backprop(trainSet[i + j].xs, trainSet[i + j].ys, *state); + for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) { + auto output = mnistNet->feed(trainSet[i + j].xs); + auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output); + mnistNet->backward(loss, *state); + } mnistNet->apply(*state, learningRate); } diff --git a/example/xor.cpp b/example/xor.cpp index 4f62182..06ee946 100644 --- a/example/xor.cpp +++ b/example/xor.cpp @@ -1,3 +1,5 @@ +#include "cenet/loss/mse.hpp" + #include #include #include @@ -40,7 +42,12 @@ int main(void) { xs[0][0] = static_cast(i & 1); xs[0][1] = static_cast(i > 1); - xorNet.train(xs, s_trainData[i], EPSILON); + auto output = xorNet.feed(xs); + auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output); + + network_type::learning_state state; + xorNet.backward(loss, state); + xorNet.apply(state, EPSILON); } double acc = 0.0; diff --git a/include/cenet/layer.hpp b/include/cenet/layer.hpp index 26cb855..50e9c6e 100644 --- a/include/cenet/layer.hpp +++ b/include/cenet/layer.hpp @@ -105,7 +105,7 @@ private: weights_type weights; biases_type biases; - output_type output; + input_type input; void dump(std::ostream& os) const { os.write(reinterpret_cast(weights.data()), sizeof(T) * weights.size()); @@ -124,10 +124,13 @@ private: biases = decltype(biases){}; } - auto& forward(const input_type& input) { return output = (input * weights) + biases; } + auto feed(input_type&& input) { + this->input = std::move(input); + return (this->input * weights) + biases; + } template - auto backward(const input_type& input, gradient& grad, Error prevErr) { + auto backward(gradient& grad, Error prevErr) { grad.weights += input.transpose() * prevErr; grad.biases += prevErr; @@ -197,13 +200,13 @@ private: template void fill_random(const Dist& dist) {} - auto& forward(const input_type& input) { - output.apply(input, [](auto unusd, auto in) { return sigmoid(in); }); + auto feed(input_type&& input) { + output.apply(std::move(input), [](auto unusd, auto in) { return sigmoid(in); }); return output; } template - auto backward(const input_type& input, gradient& grad, Error prevErr) const { + auto backward(gradient& grad, Error prevErr) const { return prevErr.hadamard(output.hadamard(static_cast(1) - output)); } @@ -220,8 +223,7 @@ private: using input_type = typename input_type_s::type; using output_type = input_type; - input_type savedInput; - output_type output; + input_type input; struct gradient { void reset() {} @@ -234,15 +236,16 @@ private: template void fill_random(const Dist& dist) {} - auto& forward(const input_type& input) { - savedInput = input; + auto feed(input_type&& input) { + output_type output; output.apply(input, [](auto unusd, auto in) { return in > 0.0 ? in : 0.0; }); + this->input = std::move(input); return output; } template - auto backward(const input_type& input, gradient& grad, Error prevErr) const { - return prevErr.apply(savedInput, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); + auto backward(gradient& grad, Error prevErr) const { + return prevErr.apply(input, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); } void apply_grad(gradient&, double, double) {} @@ -303,7 +306,7 @@ private: weights_type weights; biases_type biases; - output_type output; + input_type input; void dump(std::ostream& os) const { os.write(reinterpret_cast(weights.data()), sizeof(T) * weights.size()); @@ -326,7 +329,8 @@ private: biases = decltype(biases){}; } - auto& forward(const input_type& input) { + auto feed(input_type&& input) { + output_type output; 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) { @@ -351,11 +355,12 @@ private: } } } + this->input = std::move(input); return output; } template - auto backward(const input_type& input, gradient& grad, Error prevErr) { + auto backward(gradient& grad, Error prevErr) { input_type backpropErr; for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) { @@ -455,7 +460,8 @@ private: static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1; using output_type = tensor; - output_type output; + + input_type input; struct gradient final { void reset() {} @@ -468,7 +474,8 @@ private: template void fill_random(const Dist& dist) {} - auto& forward(const input_type& input) { + auto feed(input_type&& input) { + output_type output; 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) { @@ -484,12 +491,13 @@ private: } } } + this->input = std::move(input); return output; } template - auto backward(const input_type& input, gradient& grad, Error prevErr) { + auto backward(gradient& grad, Error prevErr) { input_type backpropErr; for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) { @@ -537,7 +545,6 @@ private: static constexpr std::size_t FEATURES = input_type::SIZE; using output_type = mat<1, FEATURES, typename input_type::inner_type>; - output_type output; struct gradient final { void reset() {} @@ -550,17 +557,16 @@ private: template void fill_random(const Dist& dist) {} - auto& forward(const input_type& input) { + auto feed(input_type input) { + output_type output; std::copy(input.begin(), input.end(), output.data()); return output; } template - auto backward(const input_type& input, gradient& grad, Error prevErr) { + auto backward(gradient& grad, Error prevErr) { input_type backpropErr; - std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin()); - return backpropErr; } @@ -584,7 +590,7 @@ private: using output_type = math::matrix; using embedding_type = math::matrix; - output_type output; + input_type input; embedding_type embedding; @@ -620,17 +626,19 @@ private: } } - auto& forward(const input_type& input) { + 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(const input_type& input, gradient& grad, Error prevErr) { + 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"); diff --git a/include/cenet/loss/mse.hpp b/include/cenet/loss/mse.hpp new file mode 100644 index 0000000..bcfc282 --- /dev/null +++ b/include/cenet/loss/mse.hpp @@ -0,0 +1,24 @@ +#ifndef CENET_LOSS_MSE_HPP +#define CENET_LOSS_MSE_HPP + +#include + +namespace cenet { +namespace loss { + +struct mean_squared_error { + template + struct result { + decltype(std::declval() - std::declval()) gradient; + }; + + template + static result calculate(L&& result, R&& expected) { + return { std::forward(expected) - std::forward(result) }; + } +}; + +} // namespace loss +} // namespace cenet + +#endif // CENET_LOSS_MSE_HPP diff --git a/include/cenet/network.hpp b/include/cenet/network.hpp index d78c593..b1f1d9f 100644 --- a/include/cenet/network.hpp +++ b/include/cenet/network.hpp @@ -40,7 +40,11 @@ public: using input_type = Input; using output_type = typename output_layer_type::output_type; public: - const output_type& get_output() const { return get_layer().output; } + const output_type& get_output() const { return m_output; } +public: + struct loss { + double value; + }; public: void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence{}); } private: @@ -66,27 +70,31 @@ private: (get_layer().fill_random(dist), ...); } public: - const output_type& feed(const input_type& input) { - feed(input); - return get_layer().output; - } + output_type feed(input_type input) { return feed_impl<0>(std::move(input)); } private: - template - auto feed(const input_type& input) { - if constexpr (I == 0) { - return get_layer().forward(input); + template + auto feed_impl(Current&& current) { + if constexpr (I == sizeof...(Layers)) { + return std::forward(current); } else { - return get_layer().forward(feed(input)); + return feed_impl(get_layer().feed(std::forward(current))); } } public: struct learning_state final { - friend class network; - void reset() { m_count = 0; reset(std::make_index_sequence{}); } + + template > + decltype(auto) get() { + return std::get(m_layers); + } + + void increment() { ++m_count; } + + auto count() const { return m_count; } private: template void reset(std::index_sequence) { @@ -106,20 +114,17 @@ public: typename gen>::type m_layers; }; public: - void backprop(const input_type& input, const output_type& expected, learning_state& state) { - feed(input); - auto outputErr = get_output() - expected; - get_layer<0>().backward(input, - std::get<0>(state.m_layers), - backprop_chain(state, outputErr)); - state.m_count += 1; + template + void backward(const Loss& loss, LState& state) { + get_layer<0>().backward(state.template get<0>(), backward_chain(state, loss.gradient)); + state.increment(); } private: - template - auto backprop_chain(learning_state& state, ErrorType error) { + template + auto backward_chain(LState& state, ErrorType error) { if constexpr (I != 0) { - auto next = get_layer().backward(get_layer().output, std::get(state.m_layers), error); - return backprop_chain(state, next); + auto next = get_layer().backward(state.template get(), error); + return backward_chain(state, next); } else { return error; } @@ -131,16 +136,17 @@ public: private: template void apply(learning_state& state, double rate, std::index_sequence) { - (std::get(m_layers).apply_grad(std::get(state.m_layers), state.m_count, rate), ...); + (std::get(m_layers).apply_grad(state.template get(), state.count(), rate), ...); } public: void train(const input_type& input, const output_type& expected, double learningRate) { learning_state state; - backprop(input, expected, state); + backward(input, expected, state); apply(state, learningRate); } private: layer_types m_layers; + output_type m_output; }; } // namespace cenet