Compare commits

...
2 Commits
8 changed files with 173 additions and 97 deletions
+7 -2
View File
@@ -1,3 +1,5 @@
#include "cenet/loss/mse.hpp"
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cenet/cenet.hpp> #include <cenet/cenet.hpp>
@@ -140,8 +142,11 @@ int main(void) {
for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) { for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) {
if (i > 0) state->reset(); if (i > 0) state->reset();
for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) 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); 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); mnistNet->apply(*state, learningRate);
} }
+8 -1
View File
@@ -1,3 +1,5 @@
#include "cenet/loss/mse.hpp"
#include <cenet/cenet.hpp> #include <cenet/cenet.hpp>
#include <cstddef> #include <cstddef>
#include <fstream> #include <fstream>
@@ -40,7 +42,12 @@ int main(void) {
xs[0][0] = static_cast<float>(i & 1); xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1); xs[0][1] = static_cast<float>(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; double acc = 0.0;
+34 -26
View File
@@ -105,7 +105,7 @@ private:
weights_type weights; weights_type weights;
biases_type biases; biases_type biases;
output_type output; input_type input;
void dump(std::ostream& os) const { void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size()); os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
@@ -124,10 +124,13 @@ private:
biases = decltype(biases){}; 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 <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
grad.weights += input.transpose() * prevErr; grad.weights += input.transpose() * prevErr;
grad.biases += prevErr; grad.biases += prevErr;
@@ -197,13 +200,13 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type&& input) {
output.apply(input, [](auto unusd, auto in) { return sigmoid(in); }); output.apply(std::move(input), [](auto unusd, auto in) { return sigmoid(in); });
return output; return output;
} }
template <typename Error> template <typename Error>
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<typename output_type::inner_type>(1) - output)); return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
} }
@@ -220,8 +223,7 @@ private:
using input_type = typename input_type_s<NN, I>::type; using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type; using output_type = input_type;
input_type savedInput; input_type input;
output_type output;
struct gradient { struct gradient {
void reset() {} void reset() {}
@@ -234,15 +236,16 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} void fill_random(const Dist& dist) {}
auto& forward(const input_type& input) { auto feed(input_type&& input) {
savedInput = input; output_type output;
output.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; });
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) const { auto backward(gradient& grad, Error prevErr) const {
return prevErr.apply(savedInput, [](auto in, auto check) { return check > 0.0 ? in : 0.0; }); return prevErr.apply(input, [](auto in, auto check) { return check > 0.0 ? in : 0.0; });
} }
void apply_grad(gradient&, double, double) {} void apply_grad(gradient&, double, double) {}
@@ -303,7 +306,7 @@ private:
weights_type weights; weights_type weights;
biases_type biases; biases_type biases;
output_type output; input_type input;
void dump(std::ostream& os) const { void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size()); os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
@@ -326,7 +329,8 @@ private:
biases = decltype(biases){}; 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 oc = 0; oc < OUT_CHANS; ++oc) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
@@ -351,11 +355,12 @@ private:
} }
} }
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
input_type backpropErr; input_type backpropErr;
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) { 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; static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>; using output_type = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output;
input_type input;
struct gradient final { struct gradient final {
void reset() {} void reset() {}
@@ -468,7 +474,8 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} 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 ch = 0; ch < OUT_CHANS; ++ch) {
for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) { for (std::size_t oy = 0; oy < OUT_HEIGHT; ++oy) {
for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) { for (std::size_t ox = 0; ox < OUT_WIDTH; ++ox) {
@@ -484,12 +491,13 @@ private:
} }
} }
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
input_type backpropErr; input_type backpropErr;
for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) { for (std::size_t ch = 0; ch < OUT_CHANS; ++ch) {
@@ -537,7 +545,6 @@ private:
static constexpr std::size_t FEATURES = input_type::SIZE; static constexpr std::size_t FEATURES = input_type::SIZE;
using output_type = mat<1, FEATURES, typename input_type::inner_type>; using output_type = mat<1, FEATURES, typename input_type::inner_type>;
output_type output;
struct gradient final { struct gradient final {
void reset() {} void reset() {}
@@ -550,17 +557,16 @@ private:
template <typename Dist> template <typename Dist>
void fill_random(const Dist& dist) {} 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()); std::copy(input.begin(), input.end(), output.data());
return output; return output;
} }
template <typename Error> template <typename Error>
auto backward(const input_type& input, gradient& grad, Error prevErr) { auto backward(gradient& grad, Error prevErr) {
input_type backpropErr; input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin()); std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
return backpropErr; return backpropErr;
} }
@@ -584,7 +590,7 @@ private:
using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>; using output_type = math::matrix<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>; using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
output_type output; input_type input;
embedding_type embedding; 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); output.set_dimensions(input.size(), EmbedDims);
for (std::size_t i = 0; i < input.size(); ++i) { for (std::size_t i = 0; i < input.size(); ++i) {
if (input[i] >= VocabSize) throw std::out_of_range("invalid token!"); if (input[i] >= VocabSize) throw std::out_of_range("invalid token!");
output.view()[i].fill(embedding.view()[input[i]]); output.view()[i].fill(embedding.view()[input[i]]);
} }
this->input = std::move(input);
return output; return output;
} }
template <typename Error> template <typename Error>
void backward(const input_type& input, gradient& grad, Error prevErr) { void backward(gradient& grad, Error prevErr) {
const auto errorShape = prevErr.shape(); const auto errorShape = prevErr.shape();
if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) { if (errorShape.template get<0>() != input.size() || errorShape.template get<1>() != EmbedDims) {
throw std::invalid_argument("unexpected embedding gradient shape"); throw std::invalid_argument("unexpected embedding gradient shape");
+24
View File
@@ -0,0 +1,24 @@
#ifndef CENET_LOSS_MSE_HPP
#define CENET_LOSS_MSE_HPP
#include <utility>
namespace cenet {
namespace loss {
struct mean_squared_error {
template <typename L, typename R>
struct result {
decltype(std::declval<R>() - std::declval<L>()) gradient;
};
template <typename L, typename R>
static result<L, R> calculate(L&& result, R&& expected) {
return { std::forward<R>(expected) - std::forward<L>(result) };
}
};
} // namespace loss
} // namespace cenet
#endif // CENET_LOSS_MSE_HPP
+1 -1
View File
@@ -63,7 +63,7 @@ template <typename T>
using operand_t = typename operand<T>::type; using operand_t = typename operand<T>::type;
template <typename T> template <typename T>
static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, std::remove_cv_t<T>>; static constexpr bool is_expression_v = std::is_base_of_v<expression_tag, remove_cvref_t<T>>;
template <typename E> template <typename E>
struct expression_result { struct expression_result {
+70 -44
View File
@@ -17,7 +17,7 @@ namespace cenet {
namespace math { namespace math {
template <typename T, std::size_t... Dims> template <typename T, std::size_t... Dims>
class tensor { class tensor : public expression_tag {
public: public:
using traits = tensor_traits<tensor>; using traits = tensor_traits<tensor>;
using value_type = typename traits::value_type; using value_type = typename traits::value_type;
@@ -84,71 +84,97 @@ public:
return *this; return *this;
} }
public: public:
template <typename E, template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && tensor(E&& exprFwd) { // NOLINT
shape_type::template compatible<typename detail::expression_result<E>::type>()>> // If static shape check failed, check dynamically (requried for static = dynamic op dynamic).
tensor(E&& expr) { // NOLINT if constexpr (!shape_type::template compatible<typename detail::expression_result<E>::type>()) {
// TODO: introduce better exceptions
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
}
if constexpr (!traits::inline_storage) { if constexpr (!traits::inline_storage) {
if constexpr (traits::dynamic) { if constexpr (traits::dynamic) {
set_dimensions(expr.shape()); set_dimensions(exprFwd.shape());
} else { } else {
m_items = new value_type[traits::size]; m_items = new value_type[traits::size];
} }
} }
for (std::size_t i = 0; i < view().size(); ++i) { E expr = std::forward<E>(exprFwd);
m_items[i] = std::forward<E>(expr).coeff(i); for (std::size_t i = 0; i < size(); ++i) {
m_items[i] = expr.coeff(i);
} }
} }
template <typename E, template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && tensor& operator=(E&& exprFwd) {
std::is_same_v<tensor, typename detail::expression_result<E>::type>>> // If static shape check failed, check dynamically (requried for static = dynamic op dynamic).
tensor& operator=(E&& expr) { if constexpr (!shape_type::template compatible<typename detail::expression_result<E>::type>()) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape"); if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
for (std::size_t i = 0; i < view().size(); ++i) { }
m_items[i] = std::forward<E>(expr);
if constexpr (!traits::inline_storage) {
if constexpr (traits::dynamic) {
set_dimensions(exprFwd.shape());
} else {
m_items = new value_type[traits::size];
} }
} }
template <typename E, E expr = std::forward<E>(exprFwd);
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator+=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] += std::forward<E>(expr); m_items[i] = expr.coeff(i);
}
} }
template <typename E, return *this;
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator-=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] -= std::forward<E>(expr);
}
} }
template <typename E, template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> && tensor& operator+=(E&& exprFwd) {
std::is_same_v<tensor, typename detail::expression_result<E>::type>>> if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
tensor& operator*=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape"); E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) { for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] *= std::forward<E>(expr); m_items[i] += expr.coeff(i);
}
} }
template <typename E, return *this;
typename = std::enable_if_t<detail::is_expression_v<E> && !is_tensor_v<E> &&
std::is_same_v<tensor, typename detail::expression_result<E>::type>>>
tensor& operator/=(E&& expr) {
if (!expr.valid_for(m_shape)) throw std::runtime_error("unexpected tensor shape");
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] /= std::forward<E>(expr);
} }
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator-=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] -= expr.coeff(i);
}
return *this;
}
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator*=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] *= expr.coeff(i);
}
return *this;
}
template <typename E, typename = std::enable_if_t<detail::is_expression_v<E>>>
tensor& operator/=(E&& exprFwd) {
if (m_shape != exprFwd.shape()) throw std::runtime_error("tensor shape mismatch");
E expr = std::forward<E>(exprFwd);
for (std::size_t i = 0; i < view().size(); ++i) {
m_items[i] /= expr;
}
return *this;
} }
public: public:
view_type view() { return { m_items, m_shape }; } view_type view() { return { m_items, m_shape }; }
+3 -3
View File
@@ -15,7 +15,7 @@ namespace cenet {
namespace math { namespace math {
template <typename T, std::size_t... Dims> template <typename T, std::size_t... Dims>
class tensor_view { class tensor_view : public expression_tag {
static_assert(std::is_arithmetic_v<T>); static_assert(std::is_arithmetic_v<T>);
template <typename, std::size_t...> template <typename, std::size_t...>
@@ -91,10 +91,10 @@ public:
void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) { void fill(const value_type* source, std::size_t offset = 0, std::size_t length = dynamic_extent) {
offset = std::min(offset, size()); offset = std::min(offset, size());
std::memcpy(m_view + offset, source, std::min(length, size() - offset)); std::memcpy(m_view + offset, source, std::min(length, size() - offset) * sizeof(*m_view));
} }
void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size()); } void fill(const tensor_view& view) { std::memcpy(m_view, view.m_view, size() * sizeof(*m_view)); }
public: public:
value_type& coeff(std::size_t index) { return m_view[index]; } value_type& coeff(std::size_t index) { return m_view[index]; }
const value_type& coeff(std::size_t index) const { return m_view[index]; } const value_type& coeff(std::size_t index) const { return m_view[index]; }
+31 -25
View File
@@ -40,7 +40,11 @@ public:
using input_type = Input; using input_type = Input;
using output_type = typename output_layer_type::output_type; using output_type = typename output_layer_type::output_type;
public: public:
const output_type& get_output() const { return get_layer<sizeof...(Layers) - 1>().output; } const output_type& get_output() const { return m_output; }
public:
struct loss {
double value;
};
public: public:
void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence<sizeof...(Layers)>{}); } void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence<sizeof...(Layers)>{}); }
private: private:
@@ -66,27 +70,31 @@ private:
(get_layer<I>().fill_random(dist), ...); (get_layer<I>().fill_random(dist), ...);
} }
public: public:
const output_type& feed(const input_type& input) { output_type feed(input_type input) { return feed_impl<0>(std::move(input)); }
feed<sizeof...(Layers) - 1>(input);
return get_layer<sizeof...(Layers) - 1>().output;
}
private: private:
template <std::size_t I> template <std::size_t I, typename Current>
auto feed(const input_type& input) { auto feed_impl(Current&& current) {
if constexpr (I == 0) { if constexpr (I == sizeof...(Layers)) {
return get_layer<I>().forward(input); return std::forward<Current>(current);
} else { } else {
return get_layer<I>().forward(feed<I - 1>(input)); return feed_impl<I + 1>(get_layer<I>().feed(std::forward<Current>(current)));
} }
} }
public: public:
struct learning_state final { struct learning_state final {
friend class network;
void reset() { void reset() {
m_count = 0; m_count = 0;
reset(std::make_index_sequence<sizeof...(Layers)>{}); reset(std::make_index_sequence<sizeof...(Layers)>{});
} }
template <std::size_t I, typename = std::enable_if_t<(I < sizeof...(Layers))>>
decltype(auto) get() {
return std::get<I>(m_layers);
}
void increment() { ++m_count; }
auto count() const { return m_count; }
private: private:
template <std::size_t... I> template <std::size_t... I>
void reset(std::index_sequence<I...>) { void reset(std::index_sequence<I...>) {
@@ -106,20 +114,17 @@ public:
typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers; typename gen<std::make_index_sequence<sizeof...(Layers)>>::type m_layers;
}; };
public: public:
void backprop(const input_type& input, const output_type& expected, learning_state& state) { template <typename Loss, typename LState>
feed(input); void backward(const Loss& loss, LState& state) {
auto outputErr = get_output() - expected; get_layer<0>().backward(state.template get<0>(), backward_chain<sizeof...(Layers) - 1>(state, loss.gradient));
get_layer<0>().backward(input, state.increment();
std::get<0>(state.m_layers),
backprop_chain<sizeof...(Layers) - 1>(state, outputErr));
state.m_count += 1;
} }
private: private:
template <std::size_t I, typename ErrorType> template <std::size_t I, typename LState, typename ErrorType>
auto backprop_chain(learning_state& state, ErrorType error) { auto backward_chain(LState& state, ErrorType error) {
if constexpr (I != 0) { if constexpr (I != 0) {
auto next = get_layer<I>().backward(get_layer<I - 1>().output, std::get<I>(state.m_layers), error); auto next = get_layer<I>().backward(state.template get<I>(), error);
return backprop_chain<I - 1>(state, next); return backward_chain<I - 1>(state, next);
} else { } else {
return error; return error;
} }
@@ -131,16 +136,17 @@ public:
private: private:
template <std::size_t... I> template <std::size_t... I>
void apply(learning_state& state, double rate, std::index_sequence<I...>) { void apply(learning_state& state, double rate, std::index_sequence<I...>) {
(std::get<I>(m_layers).apply_grad(std::get<I>(state.m_layers), state.m_count, rate), ...); (std::get<I>(m_layers).apply_grad(state.template get<I>(), state.count(), rate), ...);
} }
public: public:
void train(const input_type& input, const output_type& expected, double learningRate) { void train(const input_type& input, const output_type& expected, double learningRate) {
learning_state state; learning_state state;
backprop(input, expected, state); backward(input, expected, state);
apply(state, learningRate); apply(state, learningRate);
} }
private: private:
layer_types m_layers; layer_types m_layers;
output_type m_output;
}; };
} // namespace cenet } // namespace cenet