Compare commits

..
3 Commits
5 changed files with 400 additions and 28 deletions
+23 -20
View File
@@ -1,3 +1,5 @@
#include "cenet/layers/convolutional.hpp"
#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include <algorithm>
@@ -13,28 +15,28 @@
#include <random>
#include <vector>
using network_type = cenet::network<cenet::tensor<float, 1, 28, 28>,
cenet::conv2d_layer<8, 3, 1, 1>,
cenet::relu_layer,
cenet::maxpool_layer<>,
cenet::conv2d_layer<16, 3, 1, 1>,
cenet::relu_layer,
cenet::maxpool_layer<>,
cenet::flatten_layer,
cenet::dense_layer<10>,
cenet::sigmoid_layer>;
using network_type = cenet::network<cenet::math::tensor<float, 1, 28, 28>,
cenet::layers::conv2d<8, 3, 1, 1>,
cenet::layers::relu,
cenet::layers::maxpool<>,
cenet::layers::conv2d<16, 3, 1, 1>,
cenet::layers::relu,
cenet::layers::maxpool<>,
cenet::layers::flatten,
cenet::layers::dense<10>,
cenet::layers::sigmoid>;
static std::uniform_real_distribution<> dist(-1, 1);
struct data {
cenet::tensor<float, 1, 28, 28> xs;
cenet::mat<1, 10, float> ys;
cenet::math::tensor<float, 1, 28, 28> xs{};
cenet::math::matrix<float, 1, 10> ys{};
};
using dataset = std::vector<data>;
template <std::size_t N, typename T>
static std::size_t col_largest_idx(const cenet::mat_col<N, T>& col) {
static std::size_t col_largest_idx(const cenet::math::tensor_view<T, N>& col) {
std::size_t maxIdx = 0;
std::remove_cv_t<T> max = col[0];
for (std::size_t i = 1; i < N; ++i) {
@@ -89,6 +91,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::uint8_t label = 0;
labels.read(reinterpret_cast<char*>(&label), sizeof(label));
set[i].ys.view().fill();
set[i].ys[0][label] = 1.0;
}
@@ -108,10 +111,10 @@ int main(void) {
static constexpr const char* NETWORK_PATH = "./mnist-conv.nn";
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
if (file.is_open())
mnistNet->load_network(file);
else
mnistNet->fill_random(dist);
// if (file.is_open())
// mnistNet->load_network(file);
// else
mnistNet->fill_random(dist);
dataset trainSet = load_dataset("./mnist/train-labels-idx1-ubyte", "./mnist/train-images-idx3-ubyte");
if (trainSet.empty()) return 1;
@@ -123,7 +126,7 @@ int main(void) {
std::size_t patienceCounter = 0;
static constexpr std::size_t MAX_PATIENCE = 10;
static constexpr std::size_t MAX_EPOCHS = 1000;
static constexpr std::size_t MAX_EPOCHS = 2;
static constexpr std::size_t BATCH_SIZE = 64;
static constexpr std::size_t EPL = 1; // Epochs Per Log
@@ -140,10 +143,10 @@ int main(void) {
auto epochStart = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) {
if (i > 0) state->reset();
state->reset();
for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j) {
auto output = mnistNet->feed(trainSet[i + j].xs);
auto output = std::move(mnistNet->feed(trainSet[i + j].xs));
auto loss = cenet::loss::mean_squared_error::calculate(trainSet[i + j].ys, output);
mnistNet->backward(loss, *state);
}
+3 -2
View File
@@ -34,7 +34,7 @@ int main(void) {
else
xorNet.fill_random(dist);
static constexpr double learning_late = 0.001;
static constexpr double learning_late = 0.5;
std::size_t gen = 0;
@@ -51,9 +51,10 @@ int main(void) {
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
xorNet.backward(loss, state);
xorNet.apply(state, learning_late);
}
xorNet.apply(state, learning_late);
double acc = 0.0;
for (std::size_t i = 0; i < 4; ++i) {
+346
View File
@@ -0,0 +1,346 @@
#ifndef CENET_LAYERS_CONVOLUTIONAL_HPP
#define CENET_LAYERS_CONVOLUTIONAL_HPP
#include "../layer.hpp"
#include "../math/tensor_fwd.hpp"
#include "../math/tensor_shape.hpp"
#include "../math/tensor_traits.hpp"
#include "../network.hpp"
namespace cenet {
namespace layers {
template <std::size_t OutChannels, std::size_t KernelSize, std::size_t Stride = 1, std::size_t Padding = 0>
class conv2d final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
static_assert(input_type::shape_type::rank == 3);
using value_type = typename input_type::value_type;
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
static_assert(!input_type::traits::dynamic, "dynamic input to conv2d is currently unsupported");
static_assert(Stride > 0, "Invalid stride passed to conv2d_layer");
static_assert(KernelSize > 0, "Invalid kernel size passed to conv2d_layer");
static_assert(IN_HEIGHT + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static_assert(IN_WIDTH + (2 * Padding) >= KernelSize, "Invalid network configuration for conv2d_layer");
static constexpr std::size_t OUT_CHANS = OutChannels;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - KernelSize + (2 * Padding)) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - KernelSize + (2 * Padding)) / Stride) + 1;
using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type =
math::tensor<math::inline_storage<value_type>, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS>;
struct gradient final {
using parent_type = inner;
weights_type weights{};
biases_type biases{};
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<math::inline_storage_tag> retained;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(value_type) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(value_type) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(value_type) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr value_type fanIn = static_cast<value_type>(IN_CHANS * KernelSize * KernelSize);
const value_type scale = std::sqrt(6.0 / fanIn);
weights.view().fill_random(dist);
weights = weights.apply([scale](auto val) { return val * scale; });
biases.view().fill();
}
template <typename Fwd>
auto feed(Fwd&& fwd) {
typename output_type::template with_storage<math::heap_storage_tag> 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) {
auto value = biases[oc];
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
std::ptrdiff_t iy = static_cast<std::ptrdiff_t>((oy * Stride) + ky) -
static_cast<std::ptrdiff_t>(Padding);
std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
value += fwd[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output[oc][oy][ox] = value;
}
}
}
retained = std::forward<Fwd>(fwd);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
typename input_type::template with_storage<math::heap_storage_tag> backpropErr;
backpropErr.view().fill();
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) {
const auto err = prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(oc, oy, ox)));
grad.biases[oc] += err;
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
const std::ptrdiff_t iy = static_cast<std::ptrdiff_t>((oy * Stride) + ky) -
static_cast<std::ptrdiff_t>(Padding);
const std::ptrdiff_t ix = static_cast<std::ptrdiff_t>((ox * Stride) + kx) -
static_cast<std::ptrdiff_t>(Padding);
if (iy >= 0 && iy < static_cast<std::ptrdiff_t>(IN_HEIGHT) && ix >= 0 &&
ix < static_cast<std::ptrdiff_t>(IN_WIDTH)) {
grad.weights[oc][ic][ky][kx] += retained[ic][iy][ix] * err;
backpropErr[ic][iy][ix] += weights[oc][ic][ky][kx] * err;
}
}
}
}
}
}
}
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {
++grad.time;
constexpr double beta1 = 0.9;
constexpr double beta2 = 0.999;
constexpr double epsilon = 1e-8;
for (std::size_t oc = 0; oc < OUT_CHANS; ++oc) {
for (std::size_t ic = 0; ic < IN_CHANS; ++ic) {
for (std::size_t ky = 0; ky < KernelSize; ++ky) {
for (std::size_t kx = 0; kx < KernelSize; ++kx) {
double avgGrad = grad.weights[oc][ic][ky][kx] / divisor;
grad.momentumWeights[oc][ic][ky][kx] =
beta1 * grad.momentumWeights[oc][ic][ky][kx] + (1.0 - beta1) * avgGrad;
grad.varianceWeights[oc][ic][ky][kx] =
beta2 * grad.varianceWeights[oc][ic][ky][kx] + (1.0 - beta2) * avgGrad * avgGrad;
auto momentumCorrected =
grad.momentumWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta1, grad.time));
auto varianceCorrected =
grad.varianceWeights[oc][ic][ky][kx] / (1.0 - std::pow(beta2, grad.time));
weights[oc][ic][ky][kx] -=
rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
}
}
}
auto avgGrad = grad.biases[oc] / divisor;
grad.momentumBiases[oc] = beta1 * grad.momentumBiases[oc] + (1.0 - beta1) * avgGrad;
grad.varianceBiases[oc] = beta2 * grad.varianceBiases[oc] + (1.0 - beta2) * avgGrad * avgGrad;
auto momentumCorrected = grad.momentumBiases[oc] / (1.0 - std::pow(beta1, grad.time));
auto varianceCorrected = grad.varianceBiases[oc] / (1.0 - std::pow(beta2, grad.time));
biases[oc] -= rate * momentumCorrected / (std::sqrt(varianceCorrected) + epsilon);
}
}
};
};
template <std::size_t PoolSize = 2, std::size_t Stride = 2>
class maxpool : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
static_assert(input_type::shape_type::rank == 3);
static_assert(!input_type::traits::dynamic, "dynamic input to maxpool is currently unsupported");
using value_type = typename input_type::value_type;
static constexpr std::size_t IN_CHANS = input_type::shape_type::template sget<0>();
static constexpr std::size_t IN_HEIGHT = input_type::shape_type::template sget<1>();
static constexpr std::size_t IN_WIDTH = input_type::shape_type::template sget<2>();
static constexpr std::size_t OUT_CHANS = IN_CHANS;
static constexpr std::size_t OUT_HEIGHT = ((IN_HEIGHT - PoolSize) / Stride) + 1;
static constexpr std::size_t OUT_WIDTH = ((IN_WIDTH - PoolSize) / Stride) + 1;
using output_type = math::tensor<math::inline_storage<value_type>, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
input_type input;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
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) {
auto maxValue = input[ch][oy * Stride][ox * Stride];
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
maxValue = std::max(maxValue, input[ch][(oy * Stride) + ky][(ox * Stride) + kx]);
}
}
output[ch][oy][ox] = maxValue;
}
}
}
this->input = std::move(input);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
input_type backpropErr;
backpropErr.view().fill();
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) {
std::size_t maxY = oy * Stride;
std::size_t maxX = ox * Stride;
auto maxValue = input[ch][maxY][maxX];
for (std::size_t ky = 0; ky < PoolSize; ++ky) {
for (std::size_t kx = 0; kx < PoolSize; ++kx) {
const std::size_t yIdx = (oy * Stride) + ky;
const std::size_t xIdx = (ox * Stride) + kx;
if (input[ch][yIdx][xIdx] > maxValue) {
maxValue = input[ch][yIdx][xIdx];
maxY = yIdx;
maxX = xIdx;
}
}
}
backpropErr[ch][maxY][maxX] +=
prevErr.coeff(prevErr.shape().calculate_offset(std::make_tuple(ch, oy, ox)));
}
}
}
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
class flatten final : public layer_info {
template <typename Input, typename... Layers>
friend class ::cenet::network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(math::is_tensor_v<input_type>);
static_assert(!input_type::traits::dynamic, "dynamic input to flatten is currently unsupported");
using value_type = typename input_type::value_type;
static constexpr auto FEATURES = input_type::shape_type::size;
using output_type = math::matrix<value_type, 1, FEATURES>;
struct gradient final {
void reset() {}
};
void dump(std::ostream& os) const {}
void load(std::istream& is) {}
template <typename Dist>
void fill_random(const Dist& dist) {}
template <typename Fwd>
auto feed(Fwd&& fwd) {
return std::forward<Fwd>(fwd).template reshape<math::shape_of<1, FEATURES>>();
}
template <typename Error>
auto backward(gradient& grad, Error&& prevErr) {
return std::forward<Error>(prevErr).template reshape<typename input_type::shape_type>();
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
} // namespace layers
} // namespace cenet
#endif // CENET_LAYERS_CONVOLUTIONAL_HPP
+28 -6
View File
@@ -76,10 +76,12 @@ public:
template <std::size_t Start = 0, typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
static_assert(sizeof...(Offs) > 0);
static_assert(sizeof...(Offs) <= sizeof...(Dims));
constexpr std::size_t off_count = sizeof...(Offs);
return calculate_offset_impl<Start, sizeof...(Dims) - sizeof...(Offs)>(offs);
static_assert(off_count > 0);
static_assert(Start + off_count <= sizeof...(Dims));
return calculate_offset_impl<off_count - 1, Start>(offs) * trailing_product<Start + off_count>();
}
private:
template <std::size_t I, std::size_t Start, typename... Offs>
@@ -90,6 +92,15 @@ private:
return (calculate_offset_impl<I - 1, Start>(offs) * get<Start + I>()) + std::get<I>(offs);
}
}
template <std::size_t I>
std::size_t trailing_product() const {
if constexpr (I == sizeof...(Dims)) {
return 1;
} else {
return get<I>() * trailing_product<I + 1>();
}
}
};
template <std::size_t... Dims>
@@ -171,10 +182,12 @@ public:
template <std::size_t Start = 0, typename... Offs>
std::size_t calculate_offset(const std::tuple<Offs...>& offs) const {
static_assert(sizeof...(Offs) > 0);
static_assert(sizeof...(Offs) <= sizeof...(Dims));
constexpr std::size_t off_count = sizeof...(Offs);
return calculate_offset_impl<Start, sizeof...(Dims) - sizeof...(Offs)>(offs);
static_assert(off_count > 0);
static_assert(Start + off_count <= sizeof...(Dims));
return calculate_offset_impl<off_count - 1, Start>(offs) * trailing_product<Start + off_count>();
}
private:
template <std::size_t I, std::size_t Start, typename... Offs>
@@ -185,6 +198,15 @@ private:
return (calculate_offset_impl<I - 1, Start>(offs) * get<Start + I>()) + std::get<I>(offs);
}
}
template <std::size_t I>
std::size_t trailing_product() const {
if constexpr (I == sizeof...(Dims)) {
return 1;
} else {
return get<I>() * trailing_product<I + 1>();
}
}
};
namespace detail {
BIN
View File
Binary file not shown.