refactor: remove old tensor class

This commit is contained in:
2026-11-02 03:06:31 +01:00
parent d97b65678a
commit 1e76b92c2a
3 changed files with 1 additions and 1017 deletions
+1 -529
View File
@@ -1,9 +1,7 @@
#ifndef CENET_LAYER_HPP
#define CENET_LAYER_HPP
#include "mat.hpp"
#include "math/tensor.hpp"
#include "tensor.hpp"
#include <array>
#include <cstddef>
@@ -18,24 +16,6 @@ namespace cenet {
namespace detail {
template <typename T>
struct is_dense : std::false_type {};
template <std::size_t N, typename T>
struct is_dense<mat<1, N, T>> : std::true_type {};
template <typename T>
static constexpr auto is_dense_v = is_dense<T>::value;
template <typename T>
struct is_tensor : std::false_type {};
template <typename T, std::size_t... Dims>
struct is_tensor<tensor<T, Dims...>> : std::true_type {};
template <typename T>
static constexpr auto is_tensor_v = is_tensor<T>::value;
template <typename T>
struct is_tokens : std::false_type {};
@@ -66,516 +46,8 @@ protected:
using input_inner_t = typename T::inner;
};
template <std::size_t Features, typename T = float>
class dense_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = mat<1, Features, T>;
static constexpr std::size_t INPUT_FEATURES = input_type::COLS;
static constexpr std::size_t OUTPUT_FEATURES = Features;
using weights_type = mat<INPUT_FEATURES, OUTPUT_FEATURES, T>;
using biases_type = mat<1, OUTPUT_FEATURES, T>;
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 = weights_type{};
biases = biases_type{};
}
};
weights_type weights;
biases_type biases;
input_type input;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
T scale = std::sqrt(2.0 / static_cast<T>(INPUT_FEATURES));
weights = decltype(weights)::random(dist) * scale;
biases = decltype(biases){};
}
auto feed(input_type&& input) {
this->input = std::move(input);
return (this->input * weights) + biases;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
grad.weights += input.transpose() * prevErr;
grad.biases += prevErr;
return prevErr * weights.transpose();
}
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 row = 0; row < INPUT_FEATURES; ++row) {
for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) {
auto avgGrad = grad.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);
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));
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
}
for (std::size_t col = 0; col < OUTPUT_FEATURES; ++col) {
double avgGrad = grad.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);
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));
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
}
}
};
};
class sigmoid_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_dense_v<input_type>);
using output_type = input_type;
output_type output;
struct gradient {
void reset() {}
};
static float sigmoid(float in) { return 1 / (1 + std::exp(-in)); }
static double sigmoid(double in) { return 1 / (1 + std::exp(-in)); }
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.apply(std::move(input), [](auto unusd, auto in) { return sigmoid(in); });
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) const {
return prevErr.hadamard(output.hadamard(static_cast<typename output_type::inner_type>(1) - output));
}
void apply_grad(gradient&, double, double) {}
};
};
class relu_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
using output_type = input_type;
input_type input;
struct gradient {
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;
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(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) {}
};
};
template <std::size_t OutChannels,
std::size_t KernelSize,
std::size_t Stride = 1,
std::size_t Padding = 0,
typename T = float>
class conv2d_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(input_type::RANK == 3);
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<2>();
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 = tensor<T, OUT_CHANS, OUT_HEIGHT, OUT_WIDTH>;
using weights_type = tensor<T, OUT_CHANS, IN_CHANS, KernelSize, KernelSize>;
using biases_type = tensor<T, 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 = weights_type{};
biases = biases_type{};
}
};
weights_type weights;
biases_type biases;
input_type input;
void dump(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(T) * weights.size());
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(T) * biases.size());
}
void load(std::istream& is) {
is.read(reinterpret_cast<char*>(weights.data()), sizeof(T) * weights.size());
is.read(reinterpret_cast<char*>(biases.data()), sizeof(T) * biases.size());
}
template <typename Dist>
void fill_random(const Dist& dist) {
constexpr T fanIn = static_cast<T>(IN_CHANS * KernelSize * KernelSize);
const T scale = std::sqrt(2.0 / fanIn);
weights = decltype(weights)::random(dist);
weights *= scale;
biases = decltype(biases){};
}
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) {
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 += input[ic][iy][ix] * weights[oc][ic][ky][kx];
}
}
}
}
output[oc][oy][ox] = value;
}
}
}
this->input = std::move(input);
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
input_type backpropErr;
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[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] += input[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, typename T = float>
class maxpool_layer : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static_assert(std::is_same_v<typename input_type::inner_type, T>);
static_assert(input_type::RANK == 3);
static constexpr std::size_t IN_CHANS = input_type::template dimension<0>();
static constexpr std::size_t IN_HEIGHT = input_type::template dimension<1>();
static constexpr std::size_t IN_WIDTH = input_type::template dimension<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 = tensor<T, 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;
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[ch][oy][ox];
}
}
}
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
class flatten_layer : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
template <class NN, std::size_t I>
struct inner final {
using input_type = typename input_type_s<NN, I>::type;
static_assert(detail::is_tensor_v<input_type>);
static constexpr std::size_t FEATURES = input_type::SIZE;
using output_type = mat<1, FEATURES, typename input_type::inner_type>;
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;
std::copy(input.begin(), input.end(), output.data());
return output;
}
template <typename Error>
auto backward(gradient& grad, Error prevErr) {
input_type backpropErr;
std::copy(prevErr.begin(), prevErr.end(), backpropErr.begin());
return backpropErr;
}
void apply_grad(gradient& grad, double divisor, double rate) {}
};
};
template <std::size_t VocabSize, std::size_t EmbedDims>
class tok2vec_layer : public layer_info {
class tok2vec_layer final : public layer_info {
template <typename Input, typename... Layers>
friend class network;
private:
-300
View File
@@ -1,300 +0,0 @@
#ifndef CENET_MAT_HPP
#define CENET_MAT_HPP
#include <cstddef>
#include <cstring>
#include <random>
#include <type_traits>
namespace cenet {
template <std::size_t N, typename T = double, typename = std::enable_if_t<(N >= 1)>>
class mat_col {
template <std::size_t M, std::size_t N2, typename T2, typename>
friend class mat;
private:
mat_col(T* data)
: m_data(data) {}
public:
T& operator[](std::size_t idx) { return m_data[idx]; }
const T& operator[](std::size_t idx) const { return m_data[idx]; }
private:
T* m_data;
};
template <std::size_t M, std::size_t N, typename T = double, typename = std::enable_if_t<(M >= 1 && N >= 1)>>
class mat {
public:
static constexpr std::size_t ROWS = M;
static constexpr std::size_t COLS = N;
using col_type = mat_col<N, T>;
using inner_type = T;
public:
mat() { std::memset(m_items, 0, sizeof(m_items)); }
mat(T init) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] = init;
}
}
}
mat(col_type col) {
static_assert((M == 1), "Invalid");
std::memcpy(m_items, col.m_data, sizeof(m_items));
}
~mat() = default;
mat(mat&& other) noexcept { std::memcpy(m_items, other.m_items, sizeof(m_items)); }
mat& operator=(mat&& other) noexcept {
if (this == &other) return *this;
std::memcpy(m_items, other.m_items, sizeof(m_items));
return *this;
}
mat(const mat& other) { std::memcpy(m_items, other.m_items, sizeof(m_items)); }
mat& operator=(const mat& other) {
if (this == &other) return *this;
std::memcpy(m_items, other.m_items, sizeof(m_items));
return *this;
}
public:
template <typename Dist>
static mat<M, N, T> random(Dist dist) {
static std::random_device s_rd;
static std::mt19937 s_mt(s_rd());
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = dist(s_mt);
}
}
return res;
}
public:
mat_col<N, T> operator[](std::size_t col) { return { m_items + (col * N) }; }
mat_col<N, const T> operator[](std::size_t col) const { return { m_items + (col * N) }; }
public:
mat operator+(const mat& rhs) const {
mat res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = (*this)[i][j] + rhs[i][j];
}
}
return res;
}
mat& operator+=(const mat& rhs) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] += rhs[i][j];
}
}
return *this;
}
mat operator-(const mat& rhs) const {
mat res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = (*this)[i][j] - rhs[i][j];
}
}
return res;
}
mat& operator-=(const mat& rhs) {
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
(*this)[i][j] -= rhs[i][j];
}
}
return *this;
}
public:
mat hadamard(const mat& rhs) const {
mat res = *this;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] *= rhs[i][j];
}
}
return res;
}
public:
mat<N, M, T> transpose() const {
mat<N, M, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[j][i] = (*this)[i][j];
}
}
return res;
}
public:
template <typename Func>
mat& apply(Func&& func) {
for (auto& el : *this)
el = func(el);
return *this;
}
template <typename Func>
mat& apply(const mat& rhs, Func&& func) {
for (auto it = begin(), itR = rhs.begin(); it != end(); ++it, ++itR)
*it = func(*it, *itR);
return *this;
}
public:
T* data() { return m_items; }
const T* data() const { return m_items; }
T* begin() { return m_items; }
T* end() { return m_items + size(); }
const T* begin() const { return m_items; }
const T* end() const { return m_items + size(); }
const T* cbegin() const { return begin(); }
const T* cend() const { return end(); }
constexpr std::size_t size() const { return M * N; }
public:
bool operator==(const mat& rhs) const { return std::memcmp(m_items, rhs.m_items, sizeof(m_items)) == 0; }
bool operator!=(const mat& rhs) const { return std::memcmp(m_items, rhs.m_items, sizeof(m_items)) != 0; }
private:
T m_items[M * N];
};
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator+(T scalar, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = scalar + rhs[i][j];
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator-(T scalar, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = scalar - rhs[i][j];
}
}
return res;
}
template <std::size_t N, typename T>
mat<1, N, T> operator+(T scalar, const mat_col<N, T>& rhs) {
mat<1, N, T> res;
for (std::size_t j = 0; j < N; ++j) {
res[0][j] = scalar + rhs[j];
}
return res;
}
template <std::size_t N, typename T>
mat<1, N, T> operator-(T scalar, const mat_col<N, T>& rhs) {
mat<1, N, T> res;
for (std::size_t j = 0; j < N; ++j) {
res[0][j] = scalar - rhs[j];
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator*(const mat<M, N, T>& lhs, T rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs[i][j] * rhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator*(T lhs, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = rhs[i][j] * lhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, std::size_t P, typename T>
mat<M, P, T> operator*(const mat<M, N, T>& lhs, const mat<N, P, T>& rhs) {
mat<M, P, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < P; ++j) {
for (std::size_t k = 0; k < N; ++k) {
res[i][j] += lhs[i][k] * rhs[k][j];
}
}
}
return res;
}
template <std::size_t M, std::size_t P, typename T>
mat<M, P, T> operator*(const mat<M, 1, T>& lhs, const mat_col<P, T>& rhs) {
mat<M, P, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < P; ++j) {
res[i][j] += lhs[i][0] * rhs[j];
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator/(const mat<M, N, T>& lhs, T rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs[i][j] / rhs;
}
}
return res;
}
template <std::size_t M, std::size_t N, typename T>
mat<M, N, T> operator/(T lhs, const mat<M, N, T>& rhs) {
mat<M, N, T> res;
for (std::size_t i = 0; i < M; ++i) {
for (std::size_t j = 0; j < N; ++j) {
res[i][j] = lhs / rhs[i][j];
}
}
return res;
}
} // namespace cenet
#endif // CENET_MAT_HPP
-188
View File
@@ -1,188 +0,0 @@
#ifndef CENET_TENSOR_HPP
#define CENET_TENSOR_HPP
#include <cstddef>
#include <cstring>
#include <random>
#include <tuple>
#include <type_traits>
#include <utility>
namespace cenet {
template <typename T, std::size_t First, std::size_t... Rest>
class tensor {
public:
static constexpr auto DIMENSIONS = std::make_tuple(First, Rest...);
template <std::size_t I>
static constexpr std::size_t dimension() {
return std::get<I>(DIMENSIONS);
}
static constexpr std::size_t RANK = 1 + sizeof...(Rest);
using inner_type = T;
public:
template <typename InT, std::size_t InFirst, std::size_t... InRest>
class view {
friend class tensor;
private:
view(InT* data)
: m_data(data) {}
public:
static constexpr auto DIMENSIONS = std::make_tuple(InFirst, InRest...);
public:
decltype(auto) operator[](std::size_t idx) {
if constexpr (sizeof...(InRest) == 0) {
InT& ref = m_data[idx];
return (ref); // NOLINT
} else {
return view<InT, InRest...>{ m_data + (idx * (InRest * ...)) };
}
}
decltype(auto) operator[](std::size_t idx) const {
if constexpr (sizeof...(InRest) == 0) {
const InT& ref = m_data[idx];
return (ref); // NOLINT
} else {
return view<InT, InRest...>{ m_data + (idx * (InRest * ...)) };
}
}
public:
constexpr std::size_t size() const { return InFirst * (InRest * ...); }
InT* data() { return m_data; }
const InT* data() const { return m_data; }
private:
InT* m_data;
};
public:
using view_type = view<T, First, Rest...>;
using const_view_type = view<const T, First, Rest...>;
public:
tensor() { std::memset(m_items, 0, sizeof(m_items)); }
~tensor() = default;
tensor(tensor&& rhs) noexcept { std::memcpy(m_items, rhs.m_items, sizeof(m_items)); }
tensor& operator=(tensor&& rhs) noexcept {
if (this == &rhs) return *this;
std::memcpy(m_items, rhs.m_items, sizeof(m_items));
return *this;
}
tensor(const tensor& rhs) noexcept { std::memcpy(m_items, rhs.m_items, sizeof(m_items)); }
tensor& operator=(const tensor& rhs) noexcept {
if (this == &rhs) return *this;
std::memcpy(m_items, rhs.m_items, sizeof(m_items));
return *this;
}
public:
tensor(const view_type& view) { std::memcpy(m_items, view.data(), sizeof(m_items)); }
operator view_type() { return m_items; }
template <typename Dist>
static tensor random(Dist dist) {
static std::random_device s_rd;
static std::mt19937 s_mt(s_rd());
tensor result;
for (auto& var : result)
var = dist(s_mt);
return result;
}
public:
template <std::size_t... InDims, typename... Offs>
view<T, InDims...> slice(Offs... offs) {
static_assert(sizeof...(InDims) <= sizeof...(Rest) + 1);
static_assert((sizeof...(Offs) == sizeof...(Rest) + 1) && (std::is_same_v<Offs, std::size_t> && ...));
return { slice(std::make_index_sequence<sizeof...(Rest) + 1>{}, offs...) };
}
private:
template <std::size_t I>
constexpr std::size_t stride() {
if constexpr (I == sizeof...(Rest))
return 1;
else
return stride<I + 1>() * std::get<I + 1>(DIMENSIONS);
}
template <std::size_t... I, typename... Offs>
T* slice(std::index_sequence<I...>, Offs... offs) {
return m_items + ((offs * stride<I>()) + ...);
}
public:
decltype(auto) operator[](std::size_t idx) {
if constexpr (sizeof...(Rest) == 0) {
T& ref = m_items[idx];
return (ref); // NOLINT
} else {
return view<T, Rest...>{ m_items + (idx * (Rest * ...)) };
}
}
decltype(auto) operator[](std::size_t idx) const {
if constexpr (sizeof...(Rest) == 0) {
const T& ref = m_items[idx];
return (ref); // NOLINT
} else {
return view<const T, Rest...>{ m_items + (idx * (Rest * ...)) };
}
}
public:
template <typename Func>
auto& apply(Func&& func) {
for (auto& var : *this) {
var = func(var);
}
return *this;
}
template <typename Func>
auto& apply(const tensor& rhs, Func&& func) {
for (auto it1 = begin(), it2 = rhs.begin(), endIt = end(); it1 != endIt; ++it1, ++it2) {
*it1 = func(*it1, *it2);
}
return *this;
}
public:
auto& operator+=(const tensor& rhs) {
return apply(rhs, [](T lhs, T rhs) { return lhs + rhs; });
}
auto& operator-=(const tensor& rhs) {
return apply(rhs, [](T lhs, T rhs) { return lhs - rhs; });
}
auto& operator*=(T scalar) {
return apply([scalar](T lhs) { return lhs * scalar; });
}
auto& operator/=(T scalar) {
return apply([scalar](T lhs) { return lhs / scalar; });
}
public:
static constexpr std::size_t SIZE = First * (Rest * ... * 1);
std::size_t size() const { return SIZE; }
T* data() { return m_items; }
const T* data() const { return m_items; }
T* begin() { return m_items; }
T* end() { return m_items + SIZE; }
const T* begin() const { return m_items; }
const T* end() const { return m_items + SIZE; }
const T* cbegin() const { return m_items; }
const T* cend() const { return m_items + SIZE; }
private:
T m_items[SIZE];
};
} // namespace cenet
#endif // CENET_TENSOR_HPP