vendor/fastText/src/densematrix.cc in fasttext-0.1.2 vs vendor/fastText/src/densematrix.cc in fasttext-0.1.3

- old
+ new

@@ -6,15 +6,14 @@ * LICENSE file in the root directory of this source tree. */ #include "densematrix.h" -#include <exception> #include <random> #include <stdexcept> +#include <thread> #include <utility> - #include "utils.h" #include "vector.h" namespace fasttext { @@ -23,22 +22,43 @@ DenseMatrix::DenseMatrix(int64_t m, int64_t n) : Matrix(m, n), data_(m * n) {} DenseMatrix::DenseMatrix(DenseMatrix&& other) noexcept : Matrix(other.m_, other.n_), data_(std::move(other.data_)) {} +DenseMatrix::DenseMatrix(int64_t m, int64_t n, real* dataPtr) + : Matrix(m, n), data_(dataPtr, dataPtr + (m * n)) {} + void DenseMatrix::zero() { std::fill(data_.begin(), data_.end(), 0.0); } -void DenseMatrix::uniform(real a) { - std::minstd_rand rng(1); +void DenseMatrix::uniformThread(real a, int block, int32_t seed) { + std::minstd_rand rng(block + seed); std::uniform_real_distribution<> uniform(-a, a); - for (int64_t i = 0; i < (m_ * n_); i++) { + int64_t blockSize = (m_ * n_) / 10; + for (int64_t i = blockSize * block; + i < (m_ * n_) && i < blockSize * (block + 1); + i++) { data_[i] = uniform(rng); } } +void DenseMatrix::uniform(real a, unsigned int thread, int32_t seed) { + if (thread > 1) { + std::vector<std::thread> threads; + for (int i = 0; i < thread; i++) { + threads.push_back(std::thread([=]() { uniformThread(a, i, seed); })); + } + for (int32_t i = 0; i < threads.size(); i++) { + threads[i].join(); + } + } else { + // webassembly can't instantiate `std::thread` + uniformThread(a, 0, seed); + } +} + void DenseMatrix::multiplyRow(const Vector& nums, int64_t ib, int64_t ie) { if (ie == -1) { ie = m_; } assert(ie <= nums.size()); @@ -71,11 +91,11 @@ auto norm = 0.0; for (auto j = 0; j < n_; j++) { norm += at(i, j) * at(i, j); } if (std::isnan(norm)) { - throw std::runtime_error("Encountered NaN."); + throw EncounteredNaNError(); } return std::sqrt(norm); } void DenseMatrix::l2NormRow(Vector& norms) const { @@ -92,10 +112,10 @@ real d = 0.0; for (int64_t j = 0; j < n_; j++) { d += at(i, j) * vec[j]; } if (std::isnan(d)) { - throw std::runtime_error("Encountered NaN."); + throw EncounteredNaNError(); } return d; } void DenseMatrix::addVectorToRow(const Vector& vec, int64_t i, real a) {