refactor(nn): separate loss function from network

Refs: #3
This commit is contained in:
2026-10-30 23:45:54 +01:00
parent 513413515e
commit 8fe56476ed
5 changed files with 104 additions and 54 deletions
+34 -26
View File
@@ -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<const char*>(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 <typename Error>
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 <typename Dist>
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 <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));
}
@@ -220,8 +223,7 @@ private:
using input_type = typename input_type_s<NN, I>::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 <typename Dist>
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 <typename Error>
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<const char*>(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 <typename Error>
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<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
output_type output;
input_type input;
struct gradient final {
void reset() {}
@@ -468,7 +474,8 @@ private:
template <typename 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 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 <typename Error>
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 <typename 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());
return output;
}
template <typename Error>
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<float, math::dynamic_extent, EmbedDims>;
using embedding_type = math::matrix<float, VocabSize, EmbedDims>;
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 <typename Error>
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");
+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
+31 -25
View File
@@ -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<sizeof...(Layers) - 1>().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<sizeof...(Layers)>{}); }
private:
@@ -66,27 +70,31 @@ private:
(get_layer<I>().fill_random(dist), ...);
}
public:
const output_type& feed(const input_type& input) {
feed<sizeof...(Layers) - 1>(input);
return get_layer<sizeof...(Layers) - 1>().output;
}
output_type feed(input_type input) { return feed_impl<0>(std::move(input)); }
private:
template <std::size_t I>
auto feed(const input_type& input) {
if constexpr (I == 0) {
return get_layer<I>().forward(input);
template <std::size_t I, typename Current>
auto feed_impl(Current&& current) {
if constexpr (I == sizeof...(Layers)) {
return std::forward<Current>(current);
} else {
return get_layer<I>().forward(feed<I - 1>(input));
return feed_impl<I + 1>(get_layer<I>().feed(std::forward<Current>(current)));
}
}
public:
struct learning_state final {
friend class network;
void reset() {
m_count = 0;
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:
template <std::size_t... I>
void reset(std::index_sequence<I...>) {
@@ -106,20 +114,17 @@ public:
typename gen<std::make_index_sequence<sizeof...(Layers)>>::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<sizeof...(Layers) - 1>(state, outputErr));
state.m_count += 1;
template <typename Loss, typename LState>
void backward(const Loss& loss, LState& state) {
get_layer<0>().backward(state.template get<0>(), backward_chain<sizeof...(Layers) - 1>(state, loss.gradient));
state.increment();
}
private:
template <std::size_t I, typename ErrorType>
auto backprop_chain(learning_state& state, ErrorType error) {
template <std::size_t I, typename LState, typename ErrorType>
auto backward_chain(LState& state, ErrorType error) {
if constexpr (I != 0) {
auto next = get_layer<I>().backward(get_layer<I - 1>().output, std::get<I>(state.m_layers), error);
return backprop_chain<I - 1>(state, next);
auto next = get_layer<I>().backward(state.template get<I>(), error);
return backward_chain<I - 1>(state, next);
} else {
return error;
}
@@ -131,16 +136,17 @@ public:
private:
template <std::size_t... 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:
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